# Java 设计模式完整参考文档

> 来源: https://java-design-patterns.com/
> 生成日期: 2026-06-25
> 总模式数: 182
> 语言: 英文原文 + 简体中文标注

---

<!-- ============================================ -->
<!-- Creational 创建型模式 (14 个) -->
<!-- ============================================ -->

## [creational/abstract-factory] Abstract Factory 抽象工厂
> 官方文档: https://java-design-patterns.com/patterns/abstract-factory/

CreationalAbstractionDecouplingGang of FourInstantiationPolymorphismAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/abstract-factory/#also-known-as)

- Kit

## [Intent of Abstract Factory Design Pattern](https://java-design-patterns.com/patterns/abstract-factory/#intent-of-abstract-factory-design-pattern)

The Abstract Factory pattern in Java provides an interface for creating families of related or dependent objects without specifying their concrete classes, enhancing modularity and flexibility in software design.

## [Detailed Explanation of Abstract Factory Pattern with Real-World Examples](https://java-design-patterns.com/patterns/abstract-factory/#detailed-explanation-of-abstract-factory-pattern-with-real-world-examples)

Real-world example

> Imagine a furniture company that uses the Abstract Factory pattern in Java to produce various styles of furniture: modern, Victorian, and rustic. Each style includes products like chairs, tables, and sofas. To ensure consistency within each style, the company uses an Abstract Factory pattern.
>
> In this scenario, the Abstract Factory is an interface for creating families of related furniture objects (chairs, tables, sofas). Each concrete factory (ModernFurnitureFactory, VictorianFurnitureFactory, RusticFurnitureFactory) implements the Abstract Factory interface and creates a set of products that match the specific style. This way, clients can create a whole set of modern or Victorian furniture without worrying about the details of their instantiation. This maintains a consistent style and allows easy swapping of one style of furniture for another.

In plain words

> A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.

Wikipedia says

> The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes

Class diagram

![Abstract Factory class diagram](https://java-design-patterns.com/assets/img/abstract-factory.urm.194342a5.png)

## [Programmatic Example of Abstract Factory in Java](https://java-design-patterns.com/patterns/abstract-factory/#programmatic-example-of-abstract-factory-in-java)

To create a kingdom using the Abstract Factory pattern in Java, we need objects with a common theme. The elven kingdom needs an elven king, elven castle, and elven army whereas the orcish kingdom needs an orcish king, orcish castle, and orcish army. There is a dependency between the objects in the kingdom.

Translating the kingdom example above. First of all, we have some interfaces and implementation for the objects in the kingdom.

```java
public interface Castle {
    String getDescription();
}

public interface King {
    String getDescription();
}

public interface Army {
    String getDescription();
}

// Elven implementations ->
public class ElfCastle implements Castle {
    static final String DESCRIPTION = "This is the elven castle!";

    @Override
    public String getDescription() {
        return DESCRIPTION;
    }
}

public class ElfKing implements King {
    static final String DESCRIPTION = "This is the elven king!";

    @Override
    public String getDescription() {
        return DESCRIPTION;
    }
}

public class ElfArmy implements Army {
    static final String DESCRIPTION = "This is the elven Army!";

    @Override
    public String getDescription() {
        return DESCRIPTION;
    }
}

// Orcish implementations similarly -> ...
```

Then we have the abstraction and implementations for the kingdom factory.

```java
public interface KingdomFactory {
    Castle createCastle();

    King createKing();

    Army createArmy();
}

public class ElfKingdomFactory implements KingdomFactory {

    @Override
    public Castle createCastle() {
        return new ElfCastle();
    }

    @Override
    public King createKing() {
        return new ElfKing();
    }

    @Override
    public Army createArmy() {
        return new ElfArmy();
    }
}

// Orcish implementations similarly -> ...
```

Now, we can design a factory for our different kingdom factories. In this example, we created `FactoryMaker`, responsible for returning an instance of either `ElfKingdomFactory` or `OrcKingdomFactory`. The client can use `FactoryMaker` to create the desired concrete factory which, in turn, will produce different concrete objects (derived from `Army`, `King`, `Castle`). In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for.

```java
public static class FactoryMaker {

    public enum KingdomType {
        ELF, ORC
    }

    public static KingdomFactory makeFactory(KingdomType type) {
        return switch (type) {
            case ELF -> new ElfKingdomFactory();
            case ORC -> new OrcKingdomFactory();
        };
    }
}
```

Here is the main function of our example application:

```java
LOGGER.info("elf kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());

LOGGER.info("orc kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ORC);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());
```

The program output:

```
07:35:46.340 [main] INFO com.iluwatar.abstractfactory.App -- elf kingdom
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven army!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven castle!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven king!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- orc kingdom
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc army!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc castle!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king!
```

## [When to Use the Abstract Factory Pattern in Java](https://java-design-patterns.com/patterns/abstract-factory/#when-to-use-the-abstract-factory-pattern-in-java)

Use the Abstract Factory pattern in Java when:

- The system should be independent of how its products are created, composed, and represented.
- You need to configure the system with one of multiple families of products.
- A family of related product objects must be used together, enforcing consistency.
- You want to provide a class library of products, exposing only their interfaces, not their implementations.
- The lifetime of dependencies is shorter than the consumer's lifetime.
- Dependencies need to be constructed using runtime values or parameters.
- You need to choose which product to use from a family at runtime.
- Adding new products or families should not require changes to existing code.

## [Abstract Factory Pattern Java Tutorials](https://java-design-patterns.com/patterns/abstract-factory/#abstract-factory-pattern-java-tutorials)

- [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java)
- [Abstract Factory(Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory)

## [Benefits and Trade-offs of Abstract Factory Pattern](https://java-design-patterns.com/patterns/abstract-factory/#benefits-and-trade-offs-of-abstract-factory-pattern)

Benefits:

- Flexibility: Easily switch between product families without code modifications.

- Decoupling: Client code only interacts with abstract interfaces, promoting portability and maintainability.

- Reusability: Abstract factories and products facilitate component reuse across projects.

- Maintainability: Changes to individual product families are localized, simplifying updates.


Trade-offs:

- Complexity: Defining abstract interfaces and concrete factories adds initial overhead.

- Indirectness: Client code interacts with products indirectly through factories, potentially reducing transparency.


## [Real-World Applications of Abstract Factory Pattern in Java](https://java-design-patterns.com/patterns/abstract-factory/#real-world-applications-of-abstract-factory-pattern-in-java)

- Java Swing's `LookAndFeel` classes for providing different look-and-feel options.
- Various implementations in the Java Abstract Window Toolkit (AWT) for creating different GUI components.
- [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
- [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
- [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/abstract-factory/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Abstract Factory uses Factory Methods to create products.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Abstract Factory classes are often implemented as Singletons.
- [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Similar to Abstract Factory but focuses on configuring and managing a set of related objects in a flexible way.

## [References and Credits](https://java-design-patterns.com/patterns/abstract-factory/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Design Patterns in Java](https://amzn.to/3Syw0vC)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U)

---

## [creational/builder] Builder 建造者
> 官方文档: https://java-design-patterns.com/patterns/builder/

CreationalGang of FourInstantiationObject compositionAbout 4 min

* * *

## [Intent of Builder Design Pattern](https://java-design-patterns.com/patterns/builder/#intent-of-builder-design-pattern)

The Builder design pattern in Java, a fundamental creational pattern, allows for the step-by-step construction of complex objects. It separates the construction of a complex object from its representation so that the same construction process can create different representations.

## [Detailed Explanation of Builder Pattern with Real-World Examples](https://java-design-patterns.com/patterns/builder/#detailed-explanation-of-builder-pattern-with-real-world-examples)

Real-world example

> The Java Builder pattern is particularly useful in scenarios where object creation involves numerous parameters.
>
> Imagine you are building a customizable sandwich at a deli. The Builder design pattern in this context would involve a SandwichBuilder that allows you to specify each component of the sandwich, such as the type of bread, meat, cheese, vegetables, and condiments. Instead of having to know how to construct the sandwich from scratch, you use the SandwichBuilder to add each desired component step-by-step, ensuring you get exactly the sandwich you want. This separation of construction from the final product representation ensures that the same construction process can yield different types of sandwiches based on the specified components.

In plain words

> Allows you to create different flavors of an object while avoiding constructor pollution. Useful when there could be several flavors of an object. Or when there are a lot of steps involved in creation of an object.

Wikipedia says

> The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor antipattern.

With that in mind, let's explain what the telescoping constructor antipattern is. At some point, we have all encountered a constructor like the one below:

```java
public Hero(Profession profession,String name,HairType hairType,HairColor hairColor,Armor armor,Weapon weapon){
    // Value assignments
}
```

As you can see, the number of constructor parameters can quickly become overwhelming, making it difficult to understand their arrangement. Additionally, this list of parameters might continue to grow if you decide to add more options in the future. This is known as the telescoping constructor antipattern.

Sequence diagram

![Builder sequence diagram](https://java-design-patterns.com/assets/img/builder-sequence-diagram.56551873.png)

## [Programmatic Example of Builder Pattern in Java](https://java-design-patterns.com/patterns/builder/#programmatic-example-of-builder-pattern-in-java)

In this Java Builder pattern example, we construct different types of `Hero` objects with varying attributes.

Imagine a character generator for a role-playing game. The simplest option is to let the computer generate the character for you. However, if you prefer to manually select character details such as profession, gender, hair color, etc., the character creation becomes a step-by-step process that concludes once all selections are made.

A more sensible approach is to use the Builder pattern. First, let's consider the `Hero` that we want to create:

```java
public final class Hero {
    private final Profession profession;
    private final String name;
    private final HairType hairType;
    private final HairColor hairColor;
    private final Armor armor;
    private final Weapon weapon;

    private Hero(Builder builder) {
        this.profession = builder.profession;
        this.name = builder.name;
        this.hairColor = builder.hairColor;
        this.hairType = builder.hairType;
        this.weapon = builder.weapon;
        this.armor = builder.armor;
    }
}
```

Then we have the `Builder`:

```java
  public static class Builder {
    private final Profession profession;
    private final String name;
    private HairType hairType;
    private HairColor hairColor;
    private Armor armor;
    private Weapon weapon;

    public Builder(Profession profession, String name) {
        if (profession == null || name == null) {
            throw new IllegalArgumentException("profession and name can not be null");
        }
        this.profession = profession;
        this.name = name;
    }

    public Builder withHairType(HairType hairType) {
        this.hairType = hairType;
        return this;
    }

    public Builder withHairColor(HairColor hairColor) {
        this.hairColor = hairColor;
        return this;
    }

    public Builder withArmor(Armor armor) {
        this.armor = armor;
        return this;
    }

    public Builder withWeapon(Weapon weapon) {
        this.weapon = weapon;
        return this;
    }

    public Hero build() {
        return new Hero(this);
    }
}
```

Then it can be used as:

```java
  public static void main(String[] args) {

    var mage = new Hero.Builder(Profession.MAGE, "Riobard")
            .withHairColor(HairColor.BLACK)
            .withWeapon(Weapon.DAGGER)
            .build();
    LOGGER.info(mage.toString());

    var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill")
            .withHairColor(HairColor.BLOND)
            .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD)
            .build();
    LOGGER.info(warrior.toString());

    var thief = new Hero.Builder(Profession.THIEF, "Desmond")
            .withHairType(HairType.BALD)
            .withWeapon(Weapon.BOW)
            .build();
    LOGGER.info(thief.toString());
}
```

Program output:

```
16:28:06.058 [main] INFO com.iluwatar.builder.App -- This is a mage named Riobard with black hair and wielding a dagger.
16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a warrior named Amberjill with blond long curly hair wearing chain mail and wielding a sword.
16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a thief named Desmond with bald head and wielding a bow.
```

## [When to Use the Builder Pattern in Java](https://java-design-patterns.com/patterns/builder/#when-to-use-the-builder-pattern-in-java)

Use the Builder pattern when

- The Builder pattern is ideal for Java applications requiring complex object creation.
- The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled
- The construction process must allow different representations for the object that's constructed
- It's particularly useful when a product requires a lot of steps to be created and when these steps need to be executed in a specific sequence

## [Builder Pattern Java Tutorials](https://java-design-patterns.com/patterns/builder/#builder-pattern-java-tutorials)

- [Builder Design Pattern in Java (DigitalOcean)](https://www.journaldev.com/1425/builder-design-pattern-in-java)
- [Builder (Refactoring Guru)](https://refactoring.guru/design-patterns/builder)
- [Exploring Joshua Bloch’s Builder design pattern in Java (Java Magazine)](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java)

## [Real-World Applications of Builder Pattern in Java](https://java-design-patterns.com/patterns/builder/#real-world-applications-of-builder-pattern-in-java)

- StringBuilder in Java for constructing strings.
- java.lang.StringBuffer used to create mutable string objects.
- Java.nio.ByteBuffer as well as similar buffers such as FloatBuffer, IntBuffer, and others
- javax.swing.GroupLayout.Group#addComponent()
- Various GUI builders in IDEs that construct UI components.
- All implementations of [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html)
- [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder)
- [Apache Commons Option.Builder](https://commons.apache.org/proper/commons-cli/apidocs/org/apache/commons/cli/Option.Builder.html)

## [Benefits and Trade-offs of Builder Pattern](https://java-design-patterns.com/patterns/builder/#benefits-and-trade-offs-of-builder-pattern)

Benefits:

- More control over the construction process compared to other creational patterns
- Supports constructing objects step-by-step, defer construction steps or run steps recursively
- Can construct objects that require a complex assembly of sub-objects. The final product is detached from the parts that make it up, as well as their assembly process
- Single Responsibility Principle. You can isolate complex construction code from the business logic of the product

Trade-offs:

- The overall complexity of the code can increase since the pattern requires creating multiple new classes
- May increase memory usage due to the necessity of creating multiple builder objects

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/builder/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be used in conjunction with Builder to build parts of a complex object.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Builders often create objects from a prototype.
- [Step Builder](https://java-design-patterns.com/patterns/step-builder/): It is a variation of the Builder pattern that generates a complex object using a step-by-step approach. The Step Builder pattern is a good choice when you need to build an object with a large number of optional parameters, and you want to avoid the telescoping constructor antipattern.

## [References and Credits](https://java-design-patterns.com/patterns/builder/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [creational/dependency-injection] Dependency Injection 依赖注入
> 官方文档: https://java-design-patterns.com/patterns/dependency-injection/

CreationalDecouplingDependency managementInversion of controlAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/dependency-injection/#also-known-as)

- Inversion of Control (IoC)
- Dependency Inversion

## [Intent of Dependency Injection Design Pattern](https://java-design-patterns.com/patterns/dependency-injection/#intent-of-dependency-injection-design-pattern)

To decouple the creation of object dependencies from their usage, allowing for more flexible and testable code.

## [Detailed Explanation of Dependency Injection Pattern with Real-World Examples](https://java-design-patterns.com/patterns/dependency-injection/#detailed-explanation-of-dependency-injection-pattern-with-real-world-examples)

Real-world example

> Imagine a high-end restaurant where the chef needs various ingredients to prepare dishes. Instead of the chef personally going to different suppliers for each ingredient, a trusted supplier delivers all the required fresh ingredients daily. This allows the chef to focus on cooking without worrying about sourcing the ingredients.
>
> In the Dependency Injection design pattern, the trusted supplier acts as the "injector," providing the necessary dependencies (ingredients) to the chef (object). The chef can then use these dependencies without knowing where they came from, ensuring a clean separation between the creation and use of dependencies. This setup enhances efficiency, flexibility, and maintainability in the kitchen, much like in a software system.

In plain words

> Dependency Injection separates the creation of the client's dependencies from its own behavior.

Wikipedia says

> In software engineering, dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies.

Sequence diagram

![Dependency Injection sequence diagram](https://java-design-patterns.com/assets/img/dependency-injection-sequence-diagram.2c470262.png)

## [Programmatic Example of Dependency Injection Pattern in Java](https://java-design-patterns.com/patterns/dependency-injection/#programmatic-example-of-dependency-injection-pattern-in-java)

The old wizard likes to fill his pipe and smoke tobacco once in a while. However, he doesn't want to depend on a single tobacco brand only but likes to be able to enjoy them all interchangeably.

Let's first introduce the `Tobacco` interface and the concrete brands.

```java

@Slf4j
public abstract class Tobacco {

    public void smoke(Wizard wizard) {
        LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(),
                this.getClass().getSimpleName());
    }
}

public class SecondBreakfastTobacco extends Tobacco {
}

public class RivendellTobacco extends Tobacco {
}

public class OldTobyTobacco extends Tobacco {
}
```

Next here's the `Wizard` class hierarchy.

```java
public interface Wizard {

    void smoke();
}

public class AdvancedWizard implements Wizard {

    private final Tobacco tobacco;

    public AdvancedWizard(Tobacco tobacco) {
        this.tobacco = tobacco;
    }

    @Override
    public void smoke() {
        tobacco.smoke(this);
    }
}
```

Finally, we can show how easy it is to give the old wizard any brand of tobacco.

```java
public static void main(String[] args) {
    var simpleWizard = new SimpleWizard();
    simpleWizard.smoke();

    var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
    advancedWizard.smoke();

    var advancedSorceress = new AdvancedSorceress();
    advancedSorceress.setTobacco(new SecondBreakfastTobacco());
    advancedSorceress.smoke();

    var injector = Guice.createInjector(new TobaccoModule());
    var guiceWizard = injector.getInstance(GuiceWizard.class);
    guiceWizard.smoke();
}
```

The program output:

```
11:54:05.205 [main] INFO com.iluwatar.dependency.injection.Tobacco -- SimpleWizard smoking OldTobyTobacco
11:54:05.207 [main] INFO com.iluwatar.dependency.injection.Tobacco -- AdvancedWizard smoking SecondBreakfastTobacco
11:54:05.207 [main] INFO com.iluwatar.dependency.injection.Tobacco -- AdvancedSorceress smoking SecondBreakfastTobacco
11:54:05.308 [main] INFO com.iluwatar.dependency.injection.Tobacco -- GuiceWizard smoking RivendellTobacco
```

## [When to Use the Dependency Injection Pattern in Java](https://java-design-patterns.com/patterns/dependency-injection/#when-to-use-the-dependency-injection-pattern-in-java)

- When aiming to reduce the coupling between classes and increase the modularity of the application.
- In scenarios where the object creation process is complex or should be separated from the class usage.
- In applications requiring easier unit testing by allowing dependencies to be mocked or stubbed.
- Within frameworks or libraries that manage object lifecycles and dependencies, such as Spring or Jakarta EE (formerly Java EE).

## [Real-World Applications of Dependency Injection Pattern in Java](https://java-design-patterns.com/patterns/dependency-injection/#real-world-applications-of-dependency-injection-pattern-in-java)

- Frameworks like Spring, Jakarta EE, and Google Guice use Dependency Injection (DI) extensively to manage component lifecycles and dependencies.
- Desktop and web applications that require flexible architecture with easily interchangeable components.

## [Benefits and Trade-offs of Dependency Injection Pattern](https://java-design-patterns.com/patterns/dependency-injection/#benefits-and-trade-offs-of-dependency-injection-pattern)

Benefits:

- Enhances modularity and separation of concerns.
- Simplifies unit testing by allowing for easy mocking of dependencies.
- Increases flexibility and maintainability by promoting loose coupling.

Trade-offs:

- Can introduce complexity in the configuration, especially in large projects.
- Might increase the learning curve for developers unfamiliar with Dependency Injection patterns or frameworks.
- Requires careful management of object lifecycles and scopes.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/dependency-injection/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/) and [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Used to create instances that the DI mechanism will inject.
- [Service Locator](https://java-design-patterns.com/patterns/service-locator/): An alternative to DI for locating services or components, though it does not decouple the lookup process as effectively as DI.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with DI to provide a single instance of a service across the application.

## [References and Credits](https://java-design-patterns.com/patterns/dependency-injection/#references-and-credits)

- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5)
- [Dependency Injection: Design patterns using Spring and Guice](https://amzn.to/4aMyHkI)
- [Dependency Injection Principles, Practices, and Patterns](https://amzn.to/4aupmxe)
- [Google Guice: Agile Lightweight Dependency Injection Framework](https://amzn.to/4bTDbX0)
- [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://amzn.to/4ayCtxp)
- [Java Design Pattern Essentials](https://amzn.to/3xtPPxa)
- [Pro Java EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework](https://amzn.to/3J6Teoh)
- [Spring in Action](https://amzn.to/4asnpSG)

---

## [creational/factory] Factory 工厂
> 官方文档: https://java-design-patterns.com/patterns/factory/

CreationalAbstractionEncapsulationGang of FourInstantiationPolymorphismAbout 3 min

* * *

## [Intent of Factory Design Pattern](https://java-design-patterns.com/patterns/factory/#intent-of-factory-design-pattern)

The Factory Design Pattern in Java is a creational pattern that defines an interface for creating an object but allows subclasses to alter the type of objects that will be created. This pattern promotes flexibility and scalability in your codebase.

## [Detailed Explanation of Factory Pattern with Real-World Examples](https://java-design-patterns.com/patterns/factory/#detailed-explanation-of-factory-pattern-with-real-world-examples)

Real-world example

> Imagine a scenario in a bakery where different types of cakes are made using a Factory Design Pattern. The bakery's `CakeFactory` handles the creation process, allowing easy addition of new cake types without altering the core cake-making process. The `CakeFactory` can produce various types of cakes such as chocolate cake, vanilla cake, and strawberry cake. Instead of the bakery staff manually selecting ingredients and following specific recipes for each type of cake, they use the `CakeFactory` to handle the process. The customer simply requests a cake type, and the `CakeFactory` determines the appropriate ingredients and recipe to use, then creates the specific type of cake. This setup allows the bakery to easily add new cake types without modifying the core cake-making process, promoting flexibility and scalability.

Wikipedia says

> Factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class.

Sequence diagram

![Factory sequence diagram](https://java-design-patterns.com/assets/img/factory-sequence-diagram.f2ab8755.png)

## [Programmatic Example of Factory Pattern in Java](https://java-design-patterns.com/patterns/factory/#programmatic-example-of-factory-pattern-in-java)

Imagine an alchemist who is about to manufacture coins. The alchemist must be able to create both gold and copper coins and switching between them must be possible without modifying the existing source code. The factory pattern makes it possible by providing a static construction method which can be called with relevant parameters.

In Java, you can implement the Factory Pattern by defining an interface `Coin` and its implementations `GoldCoin` and `CopperCoin`. The `CoinFactory` class provides a static method `getCoin` to create coin objects based on the type.

```java
public interface Coin {
  String getDescription();
}
```

```java
public class GoldCoin implements Coin {

  static final String DESCRIPTION = "This is a gold coin.";

  @Override
  public String getDescription() {
    return DESCRIPTION;
  }
}
```

```java
public class CopperCoin implements Coin {

  static final String DESCRIPTION = "This is a copper coin.";

  @Override
  public String getDescription() {
    return DESCRIPTION;
  }
}
```

Enumeration below represents types of coins that we support (`GoldCoin` and `CopperCoin`).

```java
@RequiredArgsConstructor
@Getter
public enum CoinType {

  COPPER(CopperCoin::new),
  GOLD(GoldCoin::new);

  private final Supplier<Coin> constructor;
}
```

Then we have the static method `getCoin` to create coin objects encapsulated in the factory class `CoinFactory`.

```java
public class CoinFactory {

  public static Coin getCoin(CoinType type) {
    return type.getConstructor().get();
  }
}
```

Now, in the client code, we can generate various types of coins using the factory class.

```java
public static void main(String[] args) {
    LOGGER.info("The alchemist begins his work.");
    var coin1 = CoinFactory.getCoin(CoinType.COPPER);
    var coin2 = CoinFactory.getCoin(CoinType.GOLD);
    LOGGER.info(coin1.getDescription());
    LOGGER.info(coin2.getDescription());
}
```

Program output:

```
06:19:53.530 [main] INFO com.iluwatar.factory.App -- The alchemist begins his work.
06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a copper coin.
06:19:53.533 [main] INFO com.iluwatar.factory.App -- This is a gold coin.
```

## [When to Use the Factory Pattern in Java](https://java-design-patterns.com/patterns/factory/#when-to-use-the-factory-pattern-in-java)

- Use the Factory Design Pattern in Java when the class does not know beforehand the exact types and dependencies of the objects it needs to create.
- When a method returns one of several possible classes that share a common super class and wants to encapsulate the logic of which object to create.
- The pattern is commonly used when designing frameworks or libraries to give the best flexibility and isolation from concrete class types.

## [Real-World Applications of Factory Pattern in Java](https://java-design-patterns.com/patterns/factory/#real-world-applications-of-factory-pattern-in-java)

- [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--)
- [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-)
- [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--)
- [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-)
- [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) (returns different singleton objects, depending on a protocol)
- [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E))
- [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) and other similar methods.
- JavaFX uses Factory patterns for creating various UI controls tailored to the specifics of the user's environment.

## [Benefits and Trade-offs of Factory Pattern](https://java-design-patterns.com/patterns/factory/#benefits-and-trade-offs-of-factory-pattern)

Benefits:

- Implementing the Factory Pattern in your Java application reduces coupling between the implementation and the classes it uses.
- Supports the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle), as the system can introduce new types without changing existing code.

Trade-offs:

- The code can become more complicated due to the introduction of multiple additional classes.
- Overuse can make the code less readable if the underlying complexity of the object creation is low or unnecessary.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/factory/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be considered a kind of Factory that works with groups of products.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with Factory to ensure that a class has only one instance.
- [Builder](https://java-design-patterns.com/patterns/builder/): Separates the construction of a complex object from its representation, similar to how factories manage instantiation.
- [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/): Is a factory of immutable content with separated builder and factory interfaces.

## [References and Credits](https://java-design-patterns.com/patterns/factory/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG)

---

## [creational/factory-kit] Factory Kit
> 官方文档: https://java-design-patterns.com/patterns/factory-kit/

CreationalAbstractionDecouplingEncapsulationGenericInstantiationObject compositionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/factory-kit/#also-known-as)

- Object Kit
- Toolkit

## [Intent of Factory Kit Design Pattern](https://java-design-patterns.com/patterns/factory-kit/#intent-of-factory-kit-design-pattern)

The Factory Kit Pattern in Java is a powerful design pattern that helps in creating factories with separated builder and factory interfaces. This pattern is essential for managing complex object creation scenarios.

## [Detailed Explanation of Factory Kit Pattern with Real-World Examples](https://java-design-patterns.com/patterns/factory-kit/#detailed-explanation-of-factory-kit-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Factory Kit Pattern is a restaurant kitchen where different types of dishes are prepared efficiently. This setup promotes flexibility and consistency, similar to how the Factory Kit Pattern operates in Java. Imagine the kitchen has a central station with various ingredients and recipes registered for different dishes. When an order comes in, the chef consults this central station to gather the necessary ingredients and follow the registered recipe to prepare the dish. This setup allows the kitchen to efficiently manage and switch between different dish preparations without the need for each chef to know the specifics of every recipe, promoting flexibility and consistency in the cooking process.

In plain words

> Factory kit is a configurable object builder, a factory to create factories.

Sequence diagram

![Factory Kit sequence diagram](https://java-design-patterns.com/assets/img/factory-kit-sequence-diagram.5c28a9fb.png)

## [Programmatic Example of Factory Kit Pattern in Java](https://java-design-patterns.com/patterns/factory-kit/#programmatic-example-of-factory-kit-pattern-in-java)

Imagine a magical weapon factory in Java capable of creating any desired weapon using the Factory Kit Pattern. This pattern allows for configurable object builders, making it ideal for scenarios where the types of objects are not known upfront.

Upon activation, the master recites the names of the weapon types needed to configure it. Once set up, any of these weapon types can be summoned instantly.

Let's first define the simple `Weapon` hierarchy.

```java
public interface Weapon {
}

public enum WeaponType {
    SWORD,
    AXE,
    BOW,
    SPEAR
}

public class Sword implements Weapon {
    @Override
    public String toString() {
        return "Sword";
    }
}

// Axe, Bow, and Spear are defined similarly...
```

Next, we define a functional interface that allows adding a builder with a name to the factory.

```java
public interface Builder {
    void add(WeaponType name, Supplier<Weapon> supplier);
}
```

The meat of the example is the `WeaponFactory` interface that effectively implements the factory kit pattern. The method `#factory` is used to configure the factory with the classes it needs to be able to construct. The method `#create` is then used to create object instances.

```java
public interface WeaponFactory {

    static WeaponFactory factory(Consumer<Builder> consumer) {
        var map = new HashMap<WeaponType, Supplier<Weapon>>();
        consumer.accept(map::put);
        return name -> map.get(name).get();
    }

    Weapon create(WeaponType name);
}
```

Now, we can show how `WeaponFactory` can be used.

```java
  public static void main(String[] args) {
    var factory = WeaponFactory.factory(builder -> {
        builder.add(WeaponType.SWORD, Sword::new);
        builder.add(WeaponType.AXE, Axe::new);
        builder.add(WeaponType.SPEAR, Spear::new);
        builder.add(WeaponType.BOW, Bow::new);
    });
    var list = new ArrayList<Weapon>();
    list.add(factory.create(WeaponType.AXE));
    list.add(factory.create(WeaponType.SPEAR));
    list.add(factory.create(WeaponType.SWORD));
    list.add(factory.create(WeaponType.BOW));
    list.forEach(weapon -> LOGGER.info("{}", weapon.toString()));
}
```

Here is the console output when the example is run.

```
06:32:23.026 [main] INFO com.iluwatar.factorykit.App -- Axe
06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Spear
06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Sword
06:32:23.029 [main] INFO com.iluwatar.factorykit.App -- Bow
```

## [When to Use the Factory Kit Pattern in Java](https://java-design-patterns.com/patterns/factory-kit/#when-to-use-the-factory-kit-pattern-in-java)

Use the Factory Kit Pattern when

- The factory class cannot anticipate the types of objects it must create, and a new instance of a custom builder is needed.
- A new instance of a custom builder is needed instead of a global one.
- The types of objects that the factory can build need to be defined outside the class.
- The builder and creator interfaces need to be separated.
- Game developments and other applications that have user customization.

## [Factory Kit Pattern Java Tutorials](https://java-design-patterns.com/patterns/factory-kit/#factory-kit-pattern-java-tutorials)

- [Factory Kit Pattern (Diego Pacheco)](https://diego-pacheco.medium.com/factory-kit-pattern-66d5ccb0c405)

## [Real-World Applications of Factory Kit Pattern in Java](https://java-design-patterns.com/patterns/factory-kit/#real-world-applications-of-factory-kit-pattern-in-java)

- In Java libraries such as the Java Development Kit (JDK) where different rendering engines might be instantiated based on the runtime environment.
- Frameworks like Spring or applications where dependency injection is heavily used, often implement this pattern to manage object creation more flexibly.

## [Benefits and Trade-offs of Factory Kit Pattern](https://java-design-patterns.com/patterns/factory-kit/#benefits-and-trade-offs-of-factory-kit-pattern)

Benefits:

- The Factory Kit Pattern in Java promotes loose coupling by eliminating the need to bind application-specific classes into the code.
- It simplifies the code by shifting the responsibility of instantiation to a factory object, making the development process more efficient.

Trade-offs:

- Can introduce complexity into the code by requiring additional classes and interfaces.
- Sometimes can lead to dependency issues if not properly managed.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/factory-kit/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Often used together with the Factory Kit to create families of related objects.
- [Builder](https://java-design-patterns.com/patterns/builder/): Can be used to construct complex objects step-by-step using a similar approach.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Objects that are created by cloning a prototypical instance often use a factory to manage it.

## [References and Credits](https://java-design-patterns.com/patterns/factory-kit/#references-and-credits)

- [Design Pattern Reloaded (Remi Forax)](https://www.youtube.com/watch?v=-k2X7guaArU)

---

## [creational/factory-method] Factory Method 工厂方法
> 官方文档: https://java-design-patterns.com/patterns/factory-method/

CreationalEncapsulationGang of FourInstantiationObject compositionPolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/factory-method/#also-known-as)

- Virtual Constructor

## [Intent of Factory Method Design Pattern](https://java-design-patterns.com/patterns/factory-method/#intent-of-factory-method-design-pattern)

Define an interface for creating an object using the Factory Method Pattern, but let subclasses decide which class to instantiate. This creational design pattern lets a class defer instantiation to subclasses, enhancing code flexibility and maintenance.

## [Detailed Explanation of Factory Method Pattern with Real-World Examples](https://java-design-patterns.com/patterns/factory-method/#detailed-explanation-of-factory-method-pattern-with-real-world-examples)

Real-world example

> Imagine a logistics company that needs to deliver different types of packages: standard, express, and oversized. The company has a central system that processes delivery requests but does not know the specifics of how each package type is handled. To manage this, the company uses a Factory Method pattern.
>
> In this setup, there is a central `DeliveryRequest` class with a method `createPackage()`. This method is overridden in subclasses like `StandardDelivery`, `ExpressDelivery`, and `OversizedDelivery`, each of which knows how to create and manage the respective package type. This way, the central system can handle delivery requests without needing to know the details of how each package type is created and processed, allowing for flexibility and easier maintenance.

In plain words

> It provides a way to delegate the instantiation logic to child classes.

Wikipedia says

> In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method — either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

Sequence diagram

![Factory Method sequence diagram](https://java-design-patterns.com/assets/img/factory-method-sequence-diagram.6d24f1dc.png)

## [Programmatic Example of Factory Method Pattern in Java](https://java-design-patterns.com/patterns/factory-method/#programmatic-example-of-factory-method-pattern-in-java)

The Factory Method approach is pivotal in Java Design Patterns for achieving flexible and maintainable code as we see in the following example.

Blacksmith manufactures weapons. Elves require Elvish weapons and orcs require Orcish weapons. Depending on the customer at hand the right type of blacksmith is summoned.

First of all, we have a `Blacksmith` interface and some implementations for it:

```java
public interface Blacksmith {
  Weapon manufactureWeapon(WeaponType weaponType);
}

public class ElfBlacksmith implements Blacksmith {
  public Weapon manufactureWeapon(WeaponType weaponType) {
    return ELFARSENAL.get(weaponType);
  }
}

public class OrcBlacksmith implements Blacksmith {
  public Weapon manufactureWeapon(WeaponType weaponType) {
    return ORCARSENAL.get(weaponType);
  }
}
```

When the customers come, the correct type of blacksmith is summoned and requested weapons are manufactured:

```java
public static void main(String[] args) {

    Blacksmith blacksmith = new OrcBlacksmith();
    Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
    LOGGER.info(MANUFACTURED, blacksmith, weapon);
    weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
    LOGGER.info(MANUFACTURED, blacksmith, weapon);

    blacksmith = new ElfBlacksmith();
    weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
    LOGGER.info(MANUFACTURED, blacksmith, weapon);
    weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
    LOGGER.info(MANUFACTURED, blacksmith, weapon);
}
```

Program output:

```
06:40:07.269 [main] INFO com.iluwatar.factory.method.App -- The orc blacksmith manufactured an orcish spear
06:40:07.271 [main] INFO com.iluwatar.factory.method.App -- The orc blacksmith manufactured an orcish axe
06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven spear
06:40:07.272 [main] INFO com.iluwatar.factory.method.App -- The elf blacksmith manufactured an elven axe
```

## [When to Use the Factory Method Pattern in Java](https://java-design-patterns.com/patterns/factory-method/#when-to-use-the-factory-method-pattern-in-java)

Use the Factory Method Pattern in Java when:

- Class cannot anticipate the class of objects it must create.
- Class wants its subclasses to specify the objects it creates.
- Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

## [Real-World Applications of Factory Method Pattern in Java](https://java-design-patterns.com/patterns/factory-method/#real-world-applications-of-factory-method-pattern-in-java)

- [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--)
- [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-)
- [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--)
- [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-)
- [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-)
- [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-)
- [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--)
- Frameworks that run application components, configured dynamically at runtime.

## [Benefits and Trade-offs of Factory Method Pattern](https://java-design-patterns.com/patterns/factory-method/#benefits-and-trade-offs-of-factory-method-pattern)

Benefits:

- The Factory Method Pattern provides hooks for subclasses, enhancing code flexibility and maintainability.
- Connects parallel class hierarchies.
- Eliminates the need to bind application-specific classes into the code. The code only deals with the product interface; hence it can work with any user-defined concrete product classes.

Trade-offs:

- Can complicate the code by requiring the addition of new subclasses to implement the extended factory methods.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/factory-method/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Factory methods are often called within Abstract Factory patterns.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): A factory method that returns a new instance of a class that is a clone of a prototype class.

## [References and Credits](https://java-design-patterns.com/patterns/factory-method/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG)
- [Patterns of Enterprise Application Architecture](https://amzn.to/4b2ZxoM)

---

## [creational/monostate] Monostate
> 官方文档: https://java-design-patterns.com/patterns/monostate/

CreationalEncapsulationInstantiationObject compositionPersistencePolymorphismAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/monostate/#also-known-as)

- Borg

## [Intent of Monostate Design Pattern](https://java-design-patterns.com/patterns/monostate/#intent-of-monostate-design-pattern)

The Monostate pattern is an alternative approach to achieving a singleton-like behavior in object-oriented design, ensuring a shared state in Java applications. It enforces a unique behavior where all instances of a class share the same state. Unlike the Singleton pattern, which restricts a class to a single instance, Monostate allows for multiple instances but ensures they all have a shared state.

## [Detailed Explanation of Monostate Pattern with Real-World Examples](https://java-design-patterns.com/patterns/monostate/#detailed-explanation-of-monostate-pattern-with-real-world-examples)

Real-word example

> Imagine a library with multiple desks where patrons can access the library's catalog. While each desk appears to be independent, any changes made to the catalog (like adding or removing a book) are immediately reflected at all desks. This setup ensures that no matter which desk a patron uses, they see the exact same, up-to-date catalog, similar to how the Monostate pattern maintains a shared state across all instances in Java. This is analogous to the Monostate pattern, where multiple instances of a class share the same state, ensuring consistent data across all instances.

In plain words

> Monostate allows multiple instances of a class to share the same state by channeling their state management through a common shared structure. This ensures consistent state across all instances while maintaining the facade of independent objects.

[wiki.c2.com](http://wiki.c2.com/) says

> A monostate is a "conceptual singleton" - all data members of a monostate are static, so all instances of the monostate use the same (static) data. Applications using a monostate can create any number of instances that they desire, as each instance uses the same data.

Flowchart

![Monostate flowchart](https://java-design-patterns.com/assets/img/monostate-flowchart.1a1bb52d.png)

## [Programmatic Example of Monostate Pattern in Java](https://java-design-patterns.com/patterns/monostate/#programmatic-example-of-monostate-pattern-in-java)

The Monostate pattern in Java ensures that all instances of a class share the same state, making it a great Singleton alternative for maintaining consistent data. This is achieved by using static fields in the class. Any changes to these fields will be reflected across all instances of the class. This pattern is useful when you want to avoid global variables but still need a shared state across multiple instances.

Let's take a look at the `LoadBalancer` class from the `monostate` module:

```java
public class LoadBalancer {
    private static List<Server> servers = new ArrayList<>();
    private static int nextServerIndex = 0;

    public LoadBalancer() {
        // Initialize servers
        servers.add(new Server("192.168.0.1", 8080, 1));
        servers.add(new Server("192.168.0.2", 8080, 2));
        servers.add(new Server("192.168.0.3", 8080, 3));
    }

    public void serverRequest(Request request) {
        Server server = servers.get(nextServerIndex);
        server.serve(request);
        nextServerIndex = (nextServerIndex + 1) % servers.size();
    }
}
```

In this class, `servers` and `nextServerIndex` are static fields. This means that they are shared across all instances of `LoadBalancer`. The method `serverRequest` is used to serve a request and then update the `nextServerIndex` to the next server in the list.

Now, let's see how this works in practice:

```java
public class App {
    public static void main(String[] args) {
        LoadBalancer loadBalancer1 = new LoadBalancer();
        LoadBalancer loadBalancer2 = new LoadBalancer();

        // Both instances share the same state
        loadBalancer1.serverRequest(new Request("Hello"));  // Server 1 serves the request
        loadBalancer2.serverRequest(new Request("Hello World"));  // Server 2 serves the request
    }
}
```

In this example, we create two instances of `LoadBalancer`: `loadBalancer1` and `loadBalancer2`. They share the same state. When we make a request via `loadBalancer1`, the request is served by the first server. When we make a request via `loadBalancer2`, the request is served by the second server, not the first one, because the `nextServerIndex` has been updated by `loadBalancer1`. This demonstrates the Monostate pattern in action.

## [When to Use the Monostate Pattern in Java](https://java-design-patterns.com/patterns/monostate/#when-to-use-the-monostate-pattern-in-java)

Use the Monostate pattern in Java design patterns when

1. **Shared State Across Instances:** All instances of a class must share the same state. Changes in one instance should be reflected across all instances. Monostate offers more flexibility compared to the traditional Singleton pattern.

2. **Transparent Usage:** Unlike Singleton, which can be less transparent in its usage, Monostate allows for a more transparent way of sharing state across instances. Clients interact with instances of the Monostate class as if they were regular instances, unaware of the shared state.

3. **Subclass Flexibility:** Monostate provides an advantage over Singleton when it comes to extending behavior through subclasses. Subclasses of a Monostate class can introduce additional behavior or modify existing behavior while still sharing the same state as instances of the base class. This allows for dynamic and diverse behaviors across different parts of an application, all while maintaining a shared state.

4. **Avoiding Global Variables:** The pattern is applicable when you want to avoid global variables but still need a shared state across multiple instances.

5. **Integration with Existing Systems:** Monostate can be more easily integrated into existing systems that expect to work with instances rather than a single global instance. This can lead to a smoother transition when refactoring code to use shared state.

6. **Consistent Configuration or State Management:** In scenarios where you need consistent configuration management or state management across different parts of an application, Monostate provides a pattern to ensure all parts of the system are in sync.


## [Real-World Applications of Monostate Pattern in Java](https://java-design-patterns.com/patterns/monostate/#real-world-applications-of-monostate-pattern-in-java)

- Configuration settings that need to be shared and accessible by various parts of an application.
- Resource pools where the state needs to be consistent across different consumers.

## [Benefits and Trade-offs of Monostate Pattern](https://java-design-patterns.com/patterns/monostate/#benefits-and-trade-offs-of-monostate-pattern)

Benefits:

- Provides a shared state without restricting the creation of multiple instances.
- Ensures consistency of data across instances.

Trade-offs:

- Can lead to hidden dependencies due to shared state, making the system harder to understand and debug.
- Reduces the flexibility to have instances with independent states.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/monostate/#related-java-design-patterns)

- [Singleton](https://java-design-patterns.com/patterns/singleton/): Both Singleton and Monostate patterns ensure a single shared state, but the Monostate pattern in Java allows for multiple instances with the same state, making it a unique object-oriented design approach.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Flyweight shares state to reduce memory usage, similar to how Monostate shares state among instances.

## [References and Credits](https://java-design-patterns.com/patterns/monostate/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [creational/multiton] Multiton
> 官方文档: https://java-design-patterns.com/patterns/multiton/

CreationalDecouplingInstantiationObject compositionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/multiton/#also-known-as)

- Registry of Singletons

## [Intent of Multiton Design Pattern](https://java-design-patterns.com/patterns/multiton/#intent-of-multiton-design-pattern)

The Multiton pattern in Java ensures a class has only unique named instances, providing a global point of access to them. Each named instance is accessed through a unique key, making it an essential part of Java design patterns.

## [Detailed Explanation of Multiton Pattern with Real-World Examples](https://java-design-patterns.com/patterns/multiton/#detailed-explanation-of-multiton-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Multiton pattern is a printer management system in a large office. In this scenario, the office has several printers, each serving a different department. Instead of creating a new printer object every time a printing request is made, the system uses the Multiton pattern to ensure that each department has exactly one printer instance. When a printing request comes from a specific department, the system checks the registry of printer instances and retrieves the existing printer for that department. If no printer exists for that department, it creates one, registers it, and then returns it. This ensures efficient management of printer resources and prevents unnecessary creation of multiple printer instances for the same department.

In plain words

> The Multiton pattern is an extension of the Singleton pattern, offering a way to have a map of unique named instances instead of a single instance. This makes it a valuable Java design pattern for managing named instances efficiently.

Wikipedia says

> In software engineering, the multiton pattern is a design pattern which generalizes the singleton pattern. Whereas the singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multiple instances, which it manages through the use of a map.

Flowchart

![Multiton flowchart](https://java-design-patterns.com/assets/img/multiton-flowchart.3ceec088.png)

## [Programmatic Example of Multiton Pattern in Java](https://java-design-patterns.com/patterns/multiton/#programmatic-example-of-multiton-pattern-in-java)

In this tutorial, we’ll explore how to implement the Multiton pattern in Java, covering its structure, benefits, and providing code examples. By following these implementation tips, you’ll be able to effectively utilize this Java design pattern.

The Nazgûl, also called ringwraiths or the Nine Riders, are Sauron's most terrible servants. By definition, there's always nine of them.

`Nazgul` is the multiton class.

```java
public enum NazgulName {

    KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA
}

public final class Nazgul {

    private static final Map<NazgulName, Nazgul> nazguls;

    @Getter
    private final NazgulName name;

    static {
        nazguls = new ConcurrentHashMap<>();
        nazguls.put(NazgulName.KHAMUL, new Nazgul(NazgulName.KHAMUL));
        nazguls.put(NazgulName.MURAZOR, new Nazgul(NazgulName.MURAZOR));
        nazguls.put(NazgulName.DWAR, new Nazgul(NazgulName.DWAR));
        nazguls.put(NazgulName.JI_INDUR, new Nazgul(NazgulName.JI_INDUR));
        nazguls.put(NazgulName.AKHORAHIL, new Nazgul(NazgulName.AKHORAHIL));
        nazguls.put(NazgulName.HOARMURATH, new Nazgul(NazgulName.HOARMURATH));
        nazguls.put(NazgulName.ADUNAPHEL, new Nazgul(NazgulName.ADUNAPHEL));
        nazguls.put(NazgulName.REN, new Nazgul(NazgulName.REN));
        nazguls.put(NazgulName.UVATHA, new Nazgul(NazgulName.UVATHA));
    }

    private Nazgul(NazgulName name) {
        this.name = name;
    }

    public static Nazgul getInstance(NazgulName name) {
        return nazguls.get(name);
    }
}
```

And here's how we access the `Nazgul` instances.

```java
  public static void main(String[] args) {
    // eagerly initialized multiton
    LOGGER.info("Printing out eagerly initialized multiton contents");
    LOGGER.info("KHAMUL={}", Nazgul.getInstance(NazgulName.KHAMUL));
    LOGGER.info("MURAZOR={}", Nazgul.getInstance(NazgulName.MURAZOR));
    LOGGER.info("DWAR={}", Nazgul.getInstance(NazgulName.DWAR));
    LOGGER.info("JI_INDUR={}", Nazgul.getInstance(NazgulName.JI_INDUR));
    LOGGER.info("AKHORAHIL={}", Nazgul.getInstance(NazgulName.AKHORAHIL));
    LOGGER.info("HOARMURATH={}", Nazgul.getInstance(NazgulName.HOARMURATH));
    LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL));
    LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN));
    LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA));

    // enum multiton
    LOGGER.info("Printing out enum-based multiton contents");
    LOGGER.info("KHAMUL={}", NazgulEnum.KHAMUL);
    LOGGER.info("MURAZOR={}", NazgulEnum.MURAZOR);
    LOGGER.info("DWAR={}", NazgulEnum.DWAR);
    LOGGER.info("JI_INDUR={}", NazgulEnum.JI_INDUR);
    LOGGER.info("AKHORAHIL={}", NazgulEnum.AKHORAHIL);
    LOGGER.info("HOARMURATH={}", NazgulEnum.HOARMURATH);
    LOGGER.info("ADUNAPHEL={}", NazgulEnum.ADUNAPHEL);
    LOGGER.info("REN={}", NazgulEnum.REN);
    LOGGER.info("UVATHA={}", NazgulEnum.UVATHA);
}
```

Program output:

```
15:16:10.597 [main] INFO com.iluwatar.multiton.App -- Printing out eagerly initialized multiton contents
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- KHAMUL=com.iluwatar.multiton.Nazgul@4141d797
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- MURAZOR=com.iluwatar.multiton.Nazgul@38cccef
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- DWAR=com.iluwatar.multiton.Nazgul@5679c6c6
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- JI_INDUR=com.iluwatar.multiton.Nazgul@27ddd392
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- AKHORAHIL=com.iluwatar.multiton.Nazgul@19e1023e
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- HOARMURATH=com.iluwatar.multiton.Nazgul@7cef4e59
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- ADUNAPHEL=com.iluwatar.multiton.Nazgul@64b8f8f4
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- REN=com.iluwatar.multiton.Nazgul@2db0f6b2
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- UVATHA=com.iluwatar.multiton.Nazgul@3cd1f1c8
15:16:10.600 [main] INFO com.iluwatar.multiton.App -- Printing out enum-based multiton contents
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- KHAMUL=KHAMUL
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- MURAZOR=MURAZOR
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- DWAR=DWAR
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- JI_INDUR=JI_INDUR
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- AKHORAHIL=AKHORAHIL
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- HOARMURATH=HOARMURATH
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- ADUNAPHEL=ADUNAPHEL
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- REN=REN
15:16:10.601 [main] INFO com.iluwatar.multiton.App -- UVATHA=UVATHA
```

## [When to Use the Multiton Pattern in Java](https://java-design-patterns.com/patterns/multiton/#when-to-use-the-multiton-pattern-in-java)

Use cases for the Multiton pattern in Java

- A class must have named instances, but only one instance for each unique key.
- Global access to these instances is necessary without requiring global variables.
- You want to manage shared resources categorized by key.

## [Real-World Applications of Multiton Pattern in Java](https://java-design-patterns.com/patterns/multiton/#real-world-applications-of-multiton-pattern-in-java)

- Managing database connections in different contexts.
- Configuration settings for different environments in an application.

## [Benefits and Trade-offs of Multiton Pattern](https://java-design-patterns.com/patterns/multiton/#benefits-and-trade-offs-of-multiton-pattern)

Benefits:

- Ensures controlled access to instances based on key.
- Reduces global state usage by encapsulating instance management within the pattern.

Trade-offs:

- Increased memory usage if not managed properly due to multiple instances.
- Potential issues with concurrency if not implemented with thread safety in mind.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/multiton/#related-java-design-patterns)

- [Singleton](https://java-design-patterns.com/patterns/singleton/): Multiton can be seen as an extension of the Singleton pattern where Singleton allows only one instance of a class, Multiton allows one instance per key.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Multiton uses a method to create or retrieve instances, similar to how a Factory Method controls object creation.

## [References and Credits](https://java-design-patterns.com/patterns/multiton/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)

---

## [creational/object-pool] Object Pool 对象池
> 官方文档: https://java-design-patterns.com/patterns/object-pool/

CreationalGame programmingInstantiationMemory managementPerformanceResource managementScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/object-pool/#also-known-as)

- Resource Pool

## [Intent of Object Pool Design Pattern](https://java-design-patterns.com/patterns/object-pool/#intent-of-object-pool-design-pattern)

The Object Pool design pattern in Java manages a pool of reusable objects, optimizing memory management and application performance by recycling objects rather than creating and destroying them repeatedly.

## [Detailed Explanation of Object Pool Pattern with Real-World Examples](https://java-design-patterns.com/patterns/object-pool/#detailed-explanation-of-object-pool-pattern-with-real-world-examples)

Real-world example

> Imagine a library with a limited number of study rooms that are frequently in demand. Instead of each student building their own study room whenever they need one, the library manages a pool of available study rooms. When a student needs a study room, they check one out from the pool. After they are done, they return the room back to the pool for others to use. This ensures that the study rooms are efficiently utilized without the need to build new rooms each time, thus saving time and resources, similar to how the Object Pool pattern manages the reuse of expensive objects in software.

In plain words

> Object Pool manages a set of instances instead of creating and destroying them on demand.

Wikipedia says

> The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand.

Sequence diagram

![Object Pool sequence diagram](https://java-design-patterns.com/assets/img/object-pool-sequence-diagram.0123c7cd.png)

## [Programmatic Example of Object Pool Pattern in Java](https://java-design-patterns.com/patterns/object-pool/#programmatic-example-of-object-pool-pattern-in-java)

In our war game we need to use oliphaunts, massive and mythic beasts, but the problem is that they are extremely expensive to create. The solution is to create a pool of them, track which ones are in-use, and instead of disposing them re-use the instances.

Here's the basic `Oliphaunt` class. These giants are very expensive to create.

```java
public class Oliphaunt {

    private static final AtomicInteger counter = new AtomicInteger(0);

    @Getter
    private final int id;

    public Oliphaunt() {
        id = counter.incrementAndGet();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            LOGGER.error("Error occurred: ", e);
        }
    }

    @Override
    public String toString() {
        return String.format("Oliphaunt id=%d", id);
    }
}
```

Next, we present the `ObjectPool` and more specifically `OliphauntPool`.

```java
public abstract class ObjectPool<T> {

  private final Set<T> available = new HashSet<>();
  private final Set<T> inUse = new HashSet<>();

  protected abstract T create();

  public synchronized T checkOut() {
    if (available.isEmpty()) {
      available.add(create());
    }
    var instance = available.iterator().next();
    available.remove(instance);
    inUse.add(instance);
    return instance;
  }

  public synchronized void checkIn(T instance) {
    inUse.remove(instance);
    available.add(instance);
  }

  @Override
  public synchronized String toString() {
    return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
  }
}

public class OliphauntPool extends ObjectPool<Oliphaunt> {

  @Override
  protected Oliphaunt create() {
    return new Oliphaunt();
  }
}
```

Finally, here's how we utilize the pool.

```java
public static void main(String[] args) {
    var pool = new OliphauntPool();
    LOGGER.info(pool.toString());
    var oliphaunt1 = pool.checkOut();
    String checkedOut = "Checked out {}";

    LOGGER.info(checkedOut, oliphaunt1);
    LOGGER.info(pool.toString());
    var oliphaunt2 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt2);
    var oliphaunt3 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt3);
    LOGGER.info(pool.toString());
    LOGGER.info("Checking in {}", oliphaunt1);
    pool.checkIn(oliphaunt1);
    LOGGER.info("Checking in {}", oliphaunt2);
    pool.checkIn(oliphaunt2);
    LOGGER.info(pool.toString());
    var oliphaunt4 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt4);
    var oliphaunt5 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt5);
    LOGGER.info(pool.toString());
}
```

Program output:

```
21:21:55.126 [main] INFO com.iluwatar.object.pool.App -- Pool available=0 inUse=0
21:21:56.130 [main] INFO com.iluwatar.object.pool.App -- Checked out Oliphaunt id=1
21:21:56.132 [main] INFO com.iluwatar.object.pool.App -- Pool available=0 inUse=1
21:21:57.137 [main] INFO com.iluwatar.object.pool.App -- Checked out Oliphaunt id=2
21:21:58.143 [main] INFO com.iluwatar.object.pool.App -- Checked out Oliphaunt id=3
21:21:58.145 [main] INFO com.iluwatar.object.pool.App -- Pool available=0 inUse=3
21:21:58.145 [main] INFO com.iluwatar.object.pool.App -- Checking in Oliphaunt id=1
21:21:58.145 [main] INFO com.iluwatar.object.pool.App -- Checking in Oliphaunt id=2
21:21:58.146 [main] INFO com.iluwatar.object.pool.App -- Pool available=2 inUse=1
21:21:58.146 [main] INFO com.iluwatar.object.pool.App -- Checked out Oliphaunt id=2
21:21:58.146 [main] INFO com.iluwatar.object.pool.App -- Checked out Oliphaunt id=1
21:21:58.147 [main] INFO com.iluwatar.object.pool.App -- Pool available=0 inUse=3
```

## [When to Use the Object Pool Pattern in Java](https://java-design-patterns.com/patterns/object-pool/#when-to-use-the-object-pool-pattern-in-java)

Use the Object Pool pattern when

- You need to frequently create and destroy objects, leading to high resource allocation and deallocation costs.
- The objects are expensive to create and maintain (e.g., database connections, thread pools).
- A fixed number of objects need to be controlled, like in connection pooling.
- Object reuse can significantly improve system performance and resource management.

## [Real-World Applications of Object Mother Pattern in Java](https://java-design-patterns.com/patterns/object-pool/#real-world-applications-of-object-mother-pattern-in-java)

- Database connection pooling in Java applications.
- Thread pooling in Java concurrent programming.
- Pooling of socket connections in network applications.
- Object pools in game development for frequently created and destroyed game objects.

## [Benefits and Trade-offs of Object Pool Pattern](https://java-design-patterns.com/patterns/object-pool/#benefits-and-trade-offs-of-object-pool-pattern)

Benefits:

- Improved Performance: Reduces the overhead of object creation and garbage collection.
- Resource Management: Controls the number of instances, reducing resource contention and limiting resource usage.
- Scalability: Allows the application to handle more requests by reusing a fixed number of objects.

Trade-offs:

- Complexity: Adds complexity to the codebase, requiring careful management of the pool.
- Thread Safety: Requires careful handling of concurrent access to the pool, introducing potential synchronization issues.
- Initialization Cost: Initial creation of the pool can be resource-intensive.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/object-pool/#related-java-design-patterns)

- [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensures a single instance of the pool is used, providing a global point of access.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Shares fine-grained objects to reduce memory usage, complementing object pooling by managing object state efficiently.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used to create objects within the pool, abstracting the instantiation process.

## [References and Credits](https://java-design-patterns.com/patterns/object-pool/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)

---

## [creational/prototype] Prototype 原型
> 官方文档: https://java-design-patterns.com/patterns/prototype/

CreationalGang of FourInstantiationObject compositionPolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/prototype/#also-known-as)

- Clone

## [Intent of Prototype Design Pattern](https://java-design-patterns.com/patterns/prototype/#intent-of-prototype-design-pattern)

The Prototype pattern is used to specify the kinds of objects to create using a prototypical instance, and create new instances through object cloning.

## [Detailed Explanation of Prototype Pattern with Real-World Examples](https://java-design-patterns.com/patterns/prototype/#detailed-explanation-of-prototype-pattern-with-real-world-examples)

Real-world example

> Imagine a company that manufactures custom-designed furniture. Instead of creating each piece from scratch every time an order is placed, they keep prototypes of their most popular designs. When a customer places an order for a specific design, the company simply clones the prototype of that design and makes the necessary customizations. This approach saves time and resources as the basic structure and design details are already in place, allowing the company to quickly fulfill orders with consistent quality.
>
> In this scenario, the furniture prototypes act like object prototypes in software, enabling efficient creation of new, customized pieces based on existing models.

In plain words

> Create an object based on an existing object through cloning.

Wikipedia says

> The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.

Sequence diagram

![Prototype sequence diagram](https://java-design-patterns.com/assets/img/prototype-sequence-diagram.656c633d.png)

## [Programmatic Example of Prototype Pattern in Java](https://java-design-patterns.com/patterns/prototype/#programmatic-example-of-prototype-pattern-in-java)

In Java, the prototype pattern is recommended to be implemented as follows. First, create an interface with a method for cloning objects. In this example, `Prototype` interface accomplishes this with its `copy` method.

```java
public abstract class Prototype<T> implements Cloneable {
    @SneakyThrows
    public T copy() {
        return (T) super.clone();
    }
}
```

Our example contains a hierarchy of different creatures. For example, let's look at `Beast` and `OrcBeast` classes.

```java
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public abstract class Beast extends Prototype<Beast> {
  public Beast(Beast source) {}
}
```

```java
@EqualsAndHashCode(callSuper = false)
@RequiredArgsConstructor
public class OrcBeast extends Beast {

  private final String weapon;

  public OrcBeast(OrcBeast orcBeast) {
    super(orcBeast);
    this.weapon = orcBeast.weapon;
  }

  @Override
  public String toString() {
    return "Orcish wolf attacks with " + weapon;
  }
}
```

We don't want to go into too many details, but the full example contains also base classes `Mage` and `Warlord` and there are specialized implementations of those for elves and orcs.

To take full advantage of the prototype pattern, we create `HeroFactory` and `HeroFactoryImpl` classes to produce different kinds of creatures from prototypes.

```java
public interface HeroFactory {
  Mage createMage();
  Warlord createWarlord();
  Beast createBeast();
}
```

```java
@RequiredArgsConstructor
public class HeroFactoryImpl implements HeroFactory {

  private final Mage mage;
  private final Warlord warlord;
  private final Beast beast;

  public Mage createMage() {
    return mage.copy();
  }

  public Warlord createWarlord() {
    return warlord.copy();
  }

  public Beast createBeast() {
    return beast.copy();
  }
}
```

Now, we are able to show the full prototype pattern in action producing new creatures by cloning existing instances.

```java
public static void main(String[] args) {
    var factory = new HeroFactoryImpl(
            new ElfMage("cooking"),
            new ElfWarlord("cleaning"),
            new ElfBeast("protecting")
    );
    var mage = factory.createMage();
    var warlord = factory.createWarlord();
    var beast = factory.createBeast();
    LOGGER.info(mage.toString());
    LOGGER.info(warlord.toString());
    LOGGER.info(beast.toString());

    factory = new HeroFactoryImpl(
            new OrcMage("axe"),
            new OrcWarlord("sword"),
            new OrcBeast("laser")
    );
    mage = factory.createMage();
    warlord = factory.createWarlord();
    beast = factory.createBeast();
    LOGGER.info(mage.toString());
    LOGGER.info(warlord.toString());
    LOGGER.info(beast.toString());
}
```

Here's the console output from running the example.

```
08:36:19.012 [main] INFO com.iluwatar.prototype.App -- Elven mage helps in cooking
08:36:19.013 [main] INFO com.iluwatar.prototype.App -- Elven warlord helps in cleaning
08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Elven eagle helps in protecting
08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish mage attacks with axe
08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish warlord attacks with sword
08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish wolf attacks with laser
```

## [When to Use the Prototype Pattern in Java](https://java-design-patterns.com/patterns/prototype/#when-to-use-the-prototype-pattern-in-java)

- When the classes to instantiate are specified at run-time, for example, by dynamic loading.
- To avoid building a class hierarchy of factories that parallels the class hierarchy of products.
- When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.
- When object creation is expensive compared to cloning.
- When the concrete classes to instantiate are unknown until runtime.

## [Real-World Applications of Prototype Pattern in Java](https://java-design-patterns.com/patterns/prototype/#real-world-applications-of-prototype-pattern-in-java)

- In Java, the `Object.clone()` method is a classic implementation of the Prototype pattern.
- GUI libraries often use prototypes for creating buttons, windows, and other widgets.
- In game development, creating multiple objects (like enemy characters) with similar attributes.

## [Benefits and Trade-offs of Prototype Pattern](https://java-design-patterns.com/patterns/prototype/#benefits-and-trade-offs-of-prototype-pattern)

Benefits:

Leveraging the Prototype pattern in Java applications

- Hides the complexities of instantiating new objects.
- Reduces the number of classes.
- Allows adding and removing objects at runtime.

Trade-offs:

- Requires implementing a cloning mechanism which might be complex.
- Deep cloning can be difficult to implement correctly, especially if the classes have complex object graphs with circular references.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/prototype/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Both involve creating objects, but Prototype uses cloning of a prototype instance whereas Abstract Factory creates objects using factory methods.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Singleton can use a prototype for creating instances if it allows cloning of its single instance.
- [Composite](https://java-design-patterns.com/patterns/composite/): Prototypes are often used within composites to allow for dynamic creation of component trees.

## [References and Credits](https://java-design-patterns.com/patterns/prototype/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)

---

## [creational/registry] Registry
> 官方文档: https://java-design-patterns.com/patterns/registry/

CreationalAPI designData accessDecouplingDependency managementEnterprise patternsInstantiationAbout 3 min

* * *

## [Intent of Registry Design Pattern](https://java-design-patterns.com/patterns/registry/#intent-of-registry-design-pattern)

Registry Design Pattern centralizes the creation and management of a global set of objects, providing a single point of access and ensuring controlled instantiation.

## [Detailed Explanation of Registry Pattern with Real-World Examples](https://java-design-patterns.com/patterns/registry/#detailed-explanation-of-registry-pattern-with-real-world-examples)

Real-world example

> In a large corporation, managing IT assets such as laptops, desktops, servers, and software licenses can be challenging. To streamline this process, the company uses a centralized IT Asset Management System, which functions as a Registry.
>
> - The system provides a single point of access for registering, tracking, and retrieving information about all IT assets.
> - When a new device or software is procured, it is registered in the system with details such as serial number, purchase date, warranty period, and assigned user.
> - IT staff can query the system to get details about any asset, check its current status, and update information as needed.
> - This centralized management promotes efficient utilization and maintenance of assets, ensures compliance with software licenses, and helps in planning for upgrades or replacements.
>
> In this analogy, the IT Asset Management System acts as a Registry, managing the lifecycle and providing global access to information about IT assets within the organization.

In plain words

> Registry is a well-known object that other objects can use to find common objects and services.

[wiki.c2.com](http://wiki.c2.com/) says

> A registry is a global association from keys to objects, allowing the objects to be reached from anywhere. It involves two methods: one that takes a key and an object and add objects to the registry and one that takes a key and returns the object for the key. It's similar to the MultitonPattern, but doesn't restrict instances to only those in the registry.

Flowchart

![Registry flowchart](https://java-design-patterns.com/assets/img/registry-flowchart.8e4ba616.png)

## [Programmatic Example of Registry Pattern in Java](https://java-design-patterns.com/patterns/registry/#programmatic-example-of-registry-pattern-in-java)

The Registry design pattern is a well-known pattern used in software design where objects are stored and provide a global point of access to them. This pattern is particularly useful when you need to manage a global collection of objects, decouple the creation of objects from their usage, ensure a controlled lifecycle for objects, and avoid redundant creation of objects.

First, we have the `Customer` record. It represents the objects that will be stored in the registry. Each `Customer` has an `id` and a `name`.

```java
public record Customer(String id, String name) {

    @Override
    public String toString() {
        return "Customer{"
                + "id='" + id + '\''
                + ", name='" + name + '\''
                + '}';
    }
}
```

Next, we have the `CustomerRegistry` class. This class is the actual registry where `Customer` objects are stored. It provides methods to add and retrieve customers. The `CustomerRegistry` is a singleton, meaning there is only one instance of it in the application.

```java
public final class CustomerRegistry {

    @Getter
    private static final CustomerRegistry instance = new CustomerRegistry();

    private final Map<String, Customer> customerMap;

    private CustomerRegistry() {
        customerMap = new ConcurrentHashMap<>();
    }

    public Customer addCustomer(Customer customer) {
        return customerMap.put(customer.id(), customer);
    }

    public Customer getCustomer(String id) {
        return customerMap.get(id);
    }

}
```

Finally, we have the `App` class. This class demonstrates how to use the `CustomerRegistry`. It creates two `Customer` objects, adds them to the `CustomerRegistry`, and then retrieves them.

```java
public class App {

  private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

  public static void main(String[] args) {
    CustomerRegistry customerRegistry = CustomerRegistry.getInstance();
    var john = new Customer("1", "John");
    customerRegistry.addCustomer(john);
    var julia = new Customer("2", "Julia");
    customerRegistry.addCustomer(julia);

    LOGGER.info("John {}", customerRegistry.getCustomer("1"));
    LOGGER.info("Julia {}", customerRegistry.getCustomer("2"));
  }

}
```

In this example, the `CustomerRegistry` provides a global point of access to `Customer` objects. This allows us to manage these objects in a centralized way, promoting reuse and sharing, and facilitating decoupling between components.

Running the example produces the following output:

```
09:55:31.109 [main] INFO com.iluwatar.registry.App -- John Customer{id='1', name='John'}
09:55:31.113 [main] INFO com.iluwatar.registry.App -- Julia Customer{id='2', name='Julia'}
```

## [When to Use the Registry Pattern in Java](https://java-design-patterns.com/patterns/registry/#when-to-use-the-registry-pattern-in-java)

- When you need to manage a global collection of objects.
- When you need to decouple the creation of objects from their usage.
- When you need to ensure a controlled lifecycle for objects, such as services or resources.
- When you want to avoid redundant creation of objects.

## [Real-World Applications of Registry Pattern in Java](https://java-design-patterns.com/patterns/registry/#real-world-applications-of-registry-pattern-in-java)

- Managing database connections in an enterprise application.
- Providing a central place to register and retrieve services or components in a modular application.
- Creating a central configuration registry that various parts of an application can access.

## [Benefits and Trade-offs of Registry Pattern](https://java-design-patterns.com/patterns/registry/#benefits-and-trade-offs-of-registry-pattern)

Benefits:

Key advantages of adopting the Registry pattern in Java

- Centralizes object management, making the application easier to maintain.
- Promotes reuse and sharing of objects, which can reduce memory footprint and initialization time.
- Facilitates decoupling between components.

Trade-offs:

- Can become a bottleneck if not implemented efficiently.
- May introduce a single point of failure if the registry is not designed to be fault-tolerant.
- Increases complexity in managing the lifecycle of objects.

## [Related Patterns](https://java-design-patterns.com/patterns/registry/#related-patterns)

- [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used in conjunction with the Registry to ensure there is a single instance of the Registry.
- [Factory](https://java-design-patterns.com/patterns/factory/): Used to encapsulate the instantiation logic that might be needed when objects are retrieved from the Registry.
- [Service Locator](https://java-design-patterns.com/patterns/service-locator/): A pattern that is similar in intent and structure, often used interchangeably with the Registry.
- [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): Provides an alternative method for managing dependencies, which can sometimes replace the need for a Registry.
- [Multiton](https://java-design-patterns.com/patterns/multiton/): Similar to the Registry in that it manages multiple instances, but does so based on keys, ensuring only one instance per key.

## [References and Credits](https://java-design-patterns.com/patterns/registry/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Registry (Martin Fowler)](https://www.martinfowler.com/eaaCatalog/registry.html)
- [Registry pattern (wiki.c2.com)](https://wiki.c2.com/?RegistryPattern)

---

## [creational/singleton] Singleton 单例
> 官方文档: https://java-design-patterns.com/patterns/singleton/

CreationalGang of FourInstantiationLazy initializationResource managementAbout 2 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/singleton/#also-known-as)

- Single Instance

## [Intent of Singleton Design Pattern](https://java-design-patterns.com/patterns/singleton/#intent-of-singleton-design-pattern)

Ensure a Java class only has one instance, and provide a global point of access to this singleton instance.

## [Detailed Explanation of Singleton Pattern with Real-World Examples](https://java-design-patterns.com/patterns/singleton/#detailed-explanation-of-singleton-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Singleton pattern is a government issuing a passport. In a country, each citizen can only be issued one valid passport at a time. The passport office ensures that no duplicate passports are issued to the same person. Whenever a citizen needs to travel, they must use this single passport, which serves as the unique, globally recognized identifier for their travel credentials. This controlled access and unique instance management mirrors how the Singleton pattern ensures efficient object management in Java applications.

In plain words

> Ensures that only one object of a particular class is ever created.

Wikipedia says

> In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Sequence diagram

![Singleton Pattern sequence diagram](https://java-design-patterns.com/assets/img/singleton-sequence-diagram.250259c3.png)

## [Programmatic Example of Singleton Pattern in Java](https://java-design-patterns.com/patterns/singleton/#programmatic-example-of-singleton-pattern-in-java)

Joshua Bloch, Effective Java 2nd Edition p.18

> A single-element enum type is the best way to implement a singleton

```java
public enum EnumIvoryTower {
  INSTANCE
}
```

Then in order to use:

```java
    var enumIvoryTower1 = EnumIvoryTower.INSTANCE;
    var enumIvoryTower2 = EnumIvoryTower.INSTANCE;
    LOGGER.info("enumIvoryTower1={}", enumIvoryTower1);
    LOGGER.info("enumIvoryTower2={}", enumIvoryTower2);
```

The console output

```
enumIvoryTower1=com.iluwatar.singleton.EnumIvoryTower@1221555852
enumIvoryTower2=com.iluwatar.singleton.EnumIvoryTower@1221555852
```

## [When to Use the Singleton Pattern in Java](https://java-design-patterns.com/patterns/singleton/#when-to-use-the-singleton-pattern-in-java)

Use the Singleton pattern when

- There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
- When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code

## [Real-World Applications of Singleton Pattern in Java](https://java-design-patterns.com/patterns/singleton/#real-world-applications-of-singleton-pattern-in-java)

- The logging class
- Configuration classes in many applications
- Connection pools
- File manager
- [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29)
- [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--)
- [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--)

## [Benefits and Trade-offs of Singleton Pattern](https://java-design-patterns.com/patterns/singleton/#benefits-and-trade-offs-of-singleton-pattern)

Benefits:

- Controlled access to the single instance.
- Reduced namespace pollution.
- Allows refinement of operations and representation.
- Permits a variable number of instances (more than one, if desired).
- More flexible than class operations.

Trade-offs:

- Difficult to test due to global state.
- Potentially more complex lifecycle management.
- Can introduce bottlenecks if used in a concurrent context without careful synchronization.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/singleton/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Often used to ensure a class only has one instance.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Singleton pattern can be implemented using a Factory Method to encapsulate the creation logic.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Avoids the need to create instances, can work alongside Singleton to manage unique instances.

## [References and Credits](https://java-design-patterns.com/patterns/singleton/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [creational/step-builder] Step Builder
> 官方文档: https://java-design-patterns.com/patterns/step-builder/

CreationalCode simplificationDomainEncapsulationExtensibilityInstantiationInterfaceAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/step-builder/#also-known-as)

- Fluent Builder

## [Intent of Step Builder Design Pattern](https://java-design-patterns.com/patterns/step-builder/#intent-of-step-builder-design-pattern)

The Step Builder pattern in Java is an advanced technique to create complex objects with clarity and flexibility. It is perfect for scenarios requiring meticulous step-by-step object construction.

## [Detailed Explanation of Step Builder Pattern with Real-World Examples](https://java-design-patterns.com/patterns/step-builder/#detailed-explanation-of-step-builder-pattern-with-real-world-examples)

Real-world example

> Imagine a scenario where you are assembling a custom computer. The process involves several steps: selecting the CPU, choosing the motherboard, adding memory, picking a graphics card, and installing storage. Each step builds on the previous one, gradually creating a fully functional computer. This step-by-step assembly process mirrors the Step Builder design pattern, ensuring that each component is correctly chosen and installed in a structured manner, ultimately resulting in a custom-built computer that meets specific requirements and preferences.

In plain words

> The Step Builder pattern constructs complex objects incrementally through a series of defined steps, ensuring clarity and flexibility in the creation process.

Wikipedia says

> The Step Builder pattern is a variation of the Builder design pattern, designed to provide a flexible solution for constructing complex objects step-by-step. This pattern is particularly useful when an object requires multiple initialization steps, which can be done incrementally to ensure clarity and flexibility in the creation process.

Sequence diagram

![Step Builder sequence diagram](https://java-design-patterns.com/assets/img/step-builder-sequence-diagram.55982e6f.png)

## [Programmatic Example of Step Builder Pattern in Java](https://java-design-patterns.com/patterns/step-builder/#programmatic-example-of-step-builder-pattern-in-java)

The Step Builder pattern in Java is an extension of the Builder pattern that guides the user through the creation of an object in a step-by-step manner. This pattern improves the user experience by only showing the next step methods available, and not showing the build method until it's the right time to build the object.

Let's consider a `Character` class that has many attributes such as `name`, `fighterClass`, `wizardClass`, `weapon`, `spell`, and `abilities`.

```java
@Getter
@Setter
public class Character {

  private String name;
  private String fighterClass;
  private String wizardClass;
  private String weapon;
  private String spell;
  private List<String> abilities;

  public Character(String name) {
    this.name = name;
  }

  // toString method omitted
}
```

Creating an instance of this class can be complex due to the number of attributes. This is where the Step Builder pattern comes in handy.

We create a `CharacterStepBuilder` class that guides the user through the creation of a `Character` object.

```java
public class CharacterStepBuilder {

  // Builder steps and methods...

  public static NameStep newBuilder() {
    return new Steps();
  }

  // Steps implementation...
}
```

The `CharacterStepBuilder` class defines a series of nested interfaces, each representing a step in the construction process. Each interface declares a method for the next step, guiding the user through the construction of a `Character` object.

```java
public interface NameStep {
  ClassStep name(String name);
}
```

```java
public interface ClassStep {
  WeaponStep fighterClass(String fighterClass);
  SpellStep wizardClass(String wizardClass);
}

// More steps...
```

The `Steps` class implements all these interfaces and finally builds the `Character` object.

```java
private static class Steps implements NameStep, ClassStep, WeaponStep, SpellStep, BuildStep {

  private String name;
  private String fighterClass;
  private String wizardClass;
  private String weapon;
  private String spell;
  private List<String> abilities;

  // Implement the methods for each step...

  @Override
  public Character build() {
    return new Character(name, fighterClass, wizardClass, weapon, spell, abilities);
  }
}
```

Now, creating a `Character` object becomes a guided process:

```java
public static void main(String[] args) {

    var warrior = CharacterStepBuilder
            .newBuilder()
            .name("Amberjill")
            .fighterClass("Paladin")
            .withWeapon("Sword")
            .noAbilities()
            .build();

    LOGGER.info(warrior.toString());

    var mage = CharacterStepBuilder
            .newBuilder()
            .name("Riobard")
            .wizardClass("Sorcerer")
            .withSpell("Fireball")
            .withAbility("Fire Aura")
            .withAbility("Teleport")
            .noMoreAbilities()
            .build();

    LOGGER.info(mage.toString());

    var thief = CharacterStepBuilder
            .newBuilder()
            .name("Desmond")
            .fighterClass("Rogue")
            .noWeapon()
            .build();

    LOGGER.info(thief.toString());
}
```

Console output:

```
12:58:13.887 [main] INFO com.iluwatar.stepbuilder.App -- This is a Paladin named Amberjill armed with a Sword.
12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Sorcerer named Riobard armed with a Fireball and wielding [Fire Aura, Teleport] abilities.
12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Rogue named Desmond armed with a with nothing.
```

## [When to Use the Step Builder Pattern in Java](https://java-design-patterns.com/patterns/step-builder/#when-to-use-the-step-builder-pattern-in-java)

The Step Builder pattern in Java is used

- When constructing an object that requires multiple initialization steps.
- When object construction is complex and involves many parameters.
- When you want to provide a clear, readable, and maintainable way to construct an object in a step-by-step manner.

## [Step Builder Pattern Java Tutorials](https://java-design-patterns.com/patterns/step-builder/#step-builder-pattern-java-tutorials)

- [Step Builder (Marco Castigliego)](http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html)

## [Real-World Applications of Step Builder Pattern in Java](https://java-design-patterns.com/patterns/step-builder/#real-world-applications-of-step-builder-pattern-in-java)

- Complex configuration settings in Java applications.
- Constructing objects for database records with multiple fields.
- Building UI elements where each step configures a different part of the interface.

## [Benefits and Trade-offs of Step Builder Pattern](https://java-design-patterns.com/patterns/step-builder/#benefits-and-trade-offs-of-step-builder-pattern)

Benefits:

- Improves code readability and maintainability by providing a clear and concise way to construct objects.
- Enhances flexibility in creating objects as it allows variations in the construction process.
- Encourages immutability by separating the construction process from the object's representation.

Trade-offs:

- May result in more complex code due to the additional classes and interfaces required.
- Can lead to verbose code when many steps are involved.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/step-builder/#related-java-design-patterns)

- [Builder](https://java-design-patterns.com/patterns/builder/): Both patterns help in constructing complex objects. Step Builder is a variation that emphasizes incremental step-by-step construction.
- [Fluent Interface](https://java-design-patterns.com/patterns/fluentinterface/): Often used in conjunction with the Step Builder pattern to provide a fluent API for constructing objects.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Sometimes used with the Step Builder pattern to encapsulate the creation logic of the builder itself.

## [References and Credits](https://java-design-patterns.com/patterns/step-builder/#references-and-credits)

- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)

---

## [creational/type-object] Type Object
> 官方文档: https://java-design-patterns.com/patterns/type-object/

CreationalAbstractionCode simplificationData processingGame programmingExtensibilityInstantiationObject compositionPolymorphismAbout 6 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/type-object/#also-known-as)

- Type Descriptor
- Type Safe Enumeration

## [Intent of Type Object Design Pattern](https://java-design-patterns.com/patterns/type-object/#intent-of-type-object-design-pattern)

Allow creation of flexible and extensible sets of related types.

## [Detailed Explanation of Type Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/type-object/#detailed-explanation-of-type-object-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Type Object pattern can be seen in a role-playing game (RPG) character customization system. In such a game, players can choose from various character classes like Warrior, Mage, and Archer, each with its unique set of abilities and attributes. The Type Object pattern allows the game to define these character classes and their behaviors dynamically. Instead of hardcoding the details of each class, the game uses a flexible system where new character types can be added or existing ones modified without changing the underlying game logic. This extensibility lets the developers introduce new character classes through updates or expansions, keeping the game fresh and engaging for players.

In plain words

> Type Object pattern enables dynamic creation and management of flexible and extensible sets of related classes, ideal for Java developers seeking modularity without modifying existing codebase.

[gameprogrammingpatterns.com](http://gameprogrammingpatterns.com/) says

> Define a type object class and a typed object class. Each type object instance represents a different logical type. Each typed object stores a reference to the type object that describes its type.

Flowchart

![Type Object Pattern Flowchart](https://java-design-patterns.com/assets/img/type-object-flowchart.1100754c.png)

## [Programmatic Example of Type Object Pattern in Java](https://java-design-patterns.com/patterns/type-object/#programmatic-example-of-type-object-pattern-in-java)

The Type Object pattern is a design pattern that allows for the creation of flexible and reusable objects by creating a class with a field that represents the 'type' of the object. This design pattern proves invaluable for scenarios where anticipated Java types are undefined upfront, or when modifications or additions are required, ensuring efficient Java development without frequent recompilations.

In the provided code, the Type Object pattern is implemented in a mini candy-crush game. The game has many different candies, which may change over time as the game is upgraded.

Let's break down the key components of this implementation:

1. **Candy Class**: This class represents the 'type' object in this pattern. Each `Candy` has a `name`, `parent`, `points`, and `type`. The `type` is an enum that can be either `CRUSHABLE_CANDY` or `REWARD_FRUIT`.

```java
class Candy {
  String name;
  Candy parent;
  String parentName;
  int points;
  Type type;

  Candy(String name, String parentName, Type type, int points) {
    // constructor implementation
  }

  int getPoints() {
    // implementation
  }

  Type getType() {
    // implementation
  }

  void setPoints(int a) {
    // implementation
  }
}
```

2. **JsonParser Class**: This class is responsible for parsing the JSON file that contains the details about the candies. It creates a `Candy` object for each candy in the JSON file and stores them in a `Hashtable`.

```java
public class JsonParser {
  Hashtable<String, Candy> candies;

  JsonParser() {
    this.candies = new Hashtable<>();
  }

  void parse() throws JsonParseException {
    // implementation
  }

  void setParentAndPoints() {
    // implementation
  }
}
```

3. **Cell Class**: This class represents a cell in the game matrix. Each cell contains a candy that can be crushed. It also contains information on how crushing can be done, how the matrix is to be reconfigured, and how points are to be gained.

```java
class Cell {
  Candy candy;
  int positionX;
  int positionY;

  Cell() {
    // implementation
  }

  Cell(Candy candy, int positionX, int positionY) {
    // implementation
  }

  void crush(CellPool pool, Cell[][] cellMatrix) {
    // implementation
  }

  // other methods...
}
```

4. **CandyGame Class**: This class contains the rules for the continuation of the game.

```java
class CandyGame {
  Cell[][] cells;
  CellPool pool;
  int totalPoints;

  CandyGame(int num, CellPool pool) {
    // implementation
  }

  boolean continueRound() {
    // implementation
  }

  // other methods...
}
```

5. **CellPool Class**: This class is a pool that reuses the candy cells that have been crushed instead of creating new ones repeatedly.

```java
class CellPool {
  int pointer;
  List<Cell> pool;
  Candy[] randomCode;

  CellPool(int num) {
    // implementation
  }

  void addNewCell(Cell c) {
    // implementation
  }

  Candy[] assignRandomCandytypes() {
    // implementation
  }

  Cell getNewCell() {
    // implementation
  }
}
```

6. **App Class**: This class contains the main method that starts the game.

```java
@Slf4j
public class App {
  public static void main(String[] args) {
      var givenTime = 50; //50ms
      var toWin = 500; //points
      var pointsWon = 0;
      var numOfRows = 3;
      var start = System.currentTimeMillis();
      var end = System.currentTimeMillis();
      var round = 0;
      while (pointsWon < toWin && end - start < givenTime) {
          round++;
          var pool = new CellPool(numOfRows * numOfRows + 5);
          var cg = new CandyGame(numOfRows, pool);
          if (round > 1) {
              LOGGER.info("Refreshing..");
          } else {
              LOGGER.info("Starting game..");
          }
          cg.printGameStatus();
          end = System.currentTimeMillis();
          cg.round((int) (end - start), givenTime);
          pointsWon += cg.totalPoints;
          end = System.currentTimeMillis();
      }
      LOGGER.info("Game Over");
      if (pointsWon >= toWin) {
          LOGGER.info("" + pointsWon);
          LOGGER.info("You win!!");
      } else {
          LOGGER.info("" + pointsWon);
          LOGGER.info("Sorry, you lose!");
      }
  }
}
```

Let's break down what happens in `App` class.

1. The `main` method is the entry point of the application. It starts by initializing several variables:

- `givenTime` is set to 50 milliseconds. This is the time limit for the game.
- `toWin` is set to 500 points. This is the target score to win the game.
- `pointsWon` is initialized to 0. This variable keeps track of the total points won so far.
- `numOfRows` is set to 3. This is the number of rows in the game grid.
- `start` and `end` are both set to the current system time in milliseconds. These variables are used to track the elapsed time.
- `round` is initialized to 0. This variable keeps track of the current round number.

02. The game enters a loop that continues until either the player has won enough points (`pointsWon >= toWin`) or the time limit has been reached (`end - start < givenTime`).

03. At the start of each round, a new `CellPool` and `CandyGame` are created. The `CellPool` is initialized with a size based on the number of cells in the game grid (`numOfRows * numOfRows + 5`). The `CandyGame` is initialized with the number of rows and the `CellPool`.

04. If it's not the first round, a message "Refreshing.." is logged. If it is the first round, a message "Starting game.." is logged.

05. The current game status is printed by calling `cg.printGameStatus()`.

06. The `end` time is updated to the current system time.

07. The game round is played by calling `cg.round((int) (end - start), givenTime)`. The elapsed time and the time limit are passed as arguments.

08. The points won in the round are added to the total points.

09. The `end` time is updated again to the current system time.

10. After the loop, a "Game Over" message is logged.

11. If the total points won is greater than or equal to the target score, a winning message is logged. Otherwise, a losing message is logged.


This is a simplified version of a game similar to Candy Crush, where the player tries to score as many points as possible within a given time limit. The game is played in rounds, and the player's score and the elapsed time are tracked throughout the game.

Console output:

```
14:36:14.453 [main] INFO com.iluwatar.typeobject.App -- Starting game..
14:36:14.455 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --        cherry       |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --        mango        |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --   purple popsicle   |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --   purple popsicle   |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --        mango        |
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.458 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.459 [main] INFO com.iluwatar.typeobject.CandyGame -- +20 points!
...
...
...
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --        cherry       |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --        mango        |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   purple popsicle   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame -- +20 points!
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --        cherry       |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   purple popsicle   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   green jellybean   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --        mango        |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --   purple popsicle   |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --      orange gum     |
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.CandyGame --
14:36:14.465 [main] INFO com.iluwatar.typeobject.App -- Game Over
14:36:14.465 [main] INFO com.iluwatar.typeobject.App -- 660
14:36:14.465 [main] INFO com.iluwatar.typeobject.App -- You win!!
```

In this implementation, the Type Object pattern allows for the flexible creation of `Candy` objects. The type of each candy is determined at runtime by parsing a JSON file, which makes it easy to add, modify, or remove candy types without having to recompile the code.

## [When to Use the Type Object Pattern in Java](https://java-design-patterns.com/patterns/type-object/#when-to-use-the-type-object-pattern-in-java)

This pattern can be used when:

- Use when you need to create an extensible set of related classes without modifying existing code.
- Ideal for scenarios where types and their behaviors need to be defined at runtime or in a flexible manner.
- Suitable for situations where the number of types is large and may change over time.
- The difference between the different 'types' of objects is the data, not the behaviour.

## [Type Object Pattern Java Tutorials](https://java-design-patterns.com/patterns/type-object/#type-object-pattern-java-tutorials)

- [Types as Objects Pattern (Jon Pearce)](http://www.cs.sjsu.edu/~pearce/modules/patterns/analysis/top.htm)

## [Real-World Applications of Type Object Pattern in Java](https://java-design-patterns.com/patterns/type-object/#real-world-applications-of-type-object-pattern-in-java)

- Java Collections Framework: Utilizing various collection types like List, Set, and Map.
- Graphics Libraries: Defining different shapes with specific properties and behaviors.
- Game Development: Creating different types of characters or items with unique attributes and behaviors.

## [Benefits and Trade-offs of Type Object Pattern](https://java-design-patterns.com/patterns/type-object/#benefits-and-trade-offs-of-type-object-pattern)

Benefits:

- Increases flexibility and extensibility of the code.
- Simplifies the addition of new types without modifying existing code.
- Enhances code readability by organizing related behaviors and properties.

Trade-offs:

- Can increase complexity if not managed properly.
- May lead to performance overhead due to dynamic type checking and handling.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/type-object/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used in conjunction with Type Object to create instances of the types.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in that it defines a family of algorithms or behaviors, but focuses more on interchangeable behaviors.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Can be used to create new instances by copying existing ones, supporting dynamic and flexible type creation.

## [References and Credits](https://java-design-patterns.com/patterns/type-object/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Type Object (Game Programming Patterns)](http://gameprogrammingpatterns.com/type-object.html)

---

<!-- ============================================ -->
<!-- Structural 结构型模式 (35 个) -->
<!-- ============================================ -->

## [structural/abstract-document] Abstract Document
> 官方文档: https://java-design-patterns.com/patterns/abstract-document/

StructuralAbstractionDecouplingDynamic typingEncapsulationExtensibilityPolymorphismAbout 5 min

* * *

## [Intent of Abstract Document Design Pattern](https://java-design-patterns.com/patterns/abstract-document/#intent-of-abstract-document-design-pattern)

The Abstract Document design pattern in Java is a crucial structural design pattern that provides a consistent way to handle hierarchical and tree-like data structures by defining a common interface for various document types. It separates the core document structure from specific data formats, enabling dynamic updates and simplified maintenance.

## [Detailed Explanation of Abstract Document Pattern with Real-World Examples](https://java-design-patterns.com/patterns/abstract-document/#detailed-explanation-of-abstract-document-pattern-with-real-world-examples)

The Abstract Document design pattern in Java allows dynamic handling of non-static properties. This pattern uses concept of traits to enable type safety and separate properties of different classes into set of interfaces.

Real-world example

> Consider a library system implementing the Abstract Document design pattern in Java, where books can have diverse formats and attributes: physical books, eBooks, and audiobooks. Each format has unique properties, such as page count for physical books, file size for eBooks, and duration for audiobooks. The Abstract Document design pattern allows the library system to manage these diverse formats flexibly. By using this pattern, the system can store and retrieve properties dynamically, without needing a rigid structure for each book type, making it easier to add new formats or attributes in the future without significant changes to the codebase.

In plain words

> Abstract Document pattern allows attaching properties to objects without them knowing about it.

Wikipedia says

> An object-oriented structural design pattern for organizing objects in loosely typed key-value stores and exposing the data using typed views. The purpose of the pattern is to achieve a high degree of flexibility between components in a strongly typed language where new properties can be added to the object-tree on the fly, without losing the support of type-safety. The pattern makes use of traits to separate different properties of a class into different interfaces.

Class diagram

![Abstract Document class diagram](https://java-design-patterns.com/assets/img/abstract-document.bea8a0de.png)

## [Programmatic Example of Abstract Document Pattern in Java](https://java-design-patterns.com/patterns/abstract-document/#programmatic-example-of-abstract-document-pattern-in-java)

Consider a car that consists of multiple parts. However, we don't know if the specific car really has all the parts, or just some of them. Our cars are dynamic and extremely flexible.

Let's first define the base classes `Document` and `AbstractDocument`. They basically make the object hold a property map and any amount of child objects.

```java
public interface Document {

    Void put(String key, Object value);

    Object get(String key);

    <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor);
}

public abstract class AbstractDocument implements Document {

    private final Map<String, Object> properties;

    protected AbstractDocument(Map<String, Object> properties) {
        Objects.requireNonNull(properties, "properties map is required");
        this.properties = properties;
    }

    @Override
    public Void put(String key, Object value) {
        properties.put(key, value);
        return null;
    }

    @Override
    public Object get(String key) {
        return properties.get(key);
    }

    @Override
    public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
        return Stream.ofNullable(get(key))
                .filter(Objects::nonNull)
                .map(el -> (List<Map<String, Object>>) el)
                .findAny()
                .stream()
                .flatMap(Collection::stream)
                .map(constructor);
    }

    // Other properties and methods...
}
```

Next we define an enum `Property` and a set of interfaces for type, price, model and parts. This allows us to create static looking interface to our `Car` class.

```java
public enum Property {

    PARTS, TYPE, PRICE, MODEL
}

public interface HasType extends Document {

    default Optional<String> getType() {
        return Optional.ofNullable((String) get(Property.TYPE.toString()));
    }
}

public interface HasPrice extends Document {

    default Optional<Number> getPrice() {
        return Optional.ofNullable((Number) get(Property.PRICE.toString()));
    }
}

public interface HasModel extends Document {

    default Optional<String> getModel() {
        return Optional.ofNullable((String) get(Property.MODEL.toString()));
    }
}

public interface HasParts extends Document {

    default Stream<Part> getParts() {
        return children(Property.PARTS.toString(), Part::new);
    }
}

public class Part extends AbstractDocument implements HasType, HasModel, HasPrice {

    public Part(Map<String, Object> properties) {
        super(properties);
    }
}
```

Now we are ready to introduce the `Car`.

```java
public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts {

    public Car(Map<String, Object> properties) {
        super(properties);
    }
}
```

And finally here's how we construct and use the `Car` in a full example.

```java
  public static void main(String[] args) {
    LOGGER.info("Constructing parts and car");

    var wheelProperties = Map.of(
            Property.TYPE.toString(), "wheel",
            Property.MODEL.toString(), "15C",
            Property.PRICE.toString(), 100L);

    var doorProperties = Map.of(
            Property.TYPE.toString(), "door",
            Property.MODEL.toString(), "Lambo",
            Property.PRICE.toString(), 300L);

    var carProperties = Map.of(
            Property.MODEL.toString(), "300SL",
            Property.PRICE.toString(), 10000L,
            Property.PARTS.toString(), List.of(wheelProperties, doorProperties));

    var car = new Car(carProperties);

    LOGGER.info("Here is our car:");
    LOGGER.info("-> model: {}", car.getModel().orElseThrow());
    LOGGER.info("-> price: {}", car.getPrice().orElseThrow());
    LOGGER.info("-> parts: ");
    car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}",
            p.getType().orElse(null),
            p.getModel().orElse(null),
            p.getPrice().orElse(null))
    );
}
```

The program output:

```
07:21:57.391 [main] INFO com.iluwatar.abstractdocument.App -- Constructing parts and car
07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- Here is our car:
07:21:57.393 [main] INFO com.iluwatar.abstractdocument.App -- -> model: 300SL
07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> price: 10000
07:21:57.394 [main] INFO com.iluwatar.abstractdocument.App -- -> parts:
07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- 	wheel/15C/100
07:21:57.395 [main] INFO com.iluwatar.abstractdocument.App -- 	door/Lambo/300
```

## [When to Use the Abstract Document Pattern in Java](https://java-design-patterns.com/patterns/abstract-document/#when-to-use-the-abstract-document-pattern-in-java)

The Abstract Document design pattern is especially beneficial in scenarios requiring management of different document types in Java that share some common attributes or behaviors, but also have unique attributes or behaviors specific to their individual types. Here are some scenarios where the Abstract Document design pattern can be applicable:

- Content Management Systems (CMS): In a CMS, you might have various types of content such as articles, images, videos, etc. Each type of content could have shared attributes like creation date, author, and tags, while also having specific attributes like image dimensions for images or video duration for videos.

- File Systems: If you're designing a file system where different types of files need to be managed, such as documents, images, audio files, and directories, the Abstract Document pattern can help provide a consistent way to access attributes like file size, creation date, etc., while allowing for specific attributes like image resolution or audio duration.

- E-commerce Systems: An e-commerce platform might have different product types such as physical products, digital downloads, and subscriptions. Each type could share common attributes like name, price, and description, while having unique attributes like shipping weight for physical products or download link for digital products.

- Medical Records Systems: In healthcare, patient records might include various types of data such as demographics, medical history, test results, and prescriptions. The Abstract Document pattern can help manage shared attributes like patient ID and date of birth, while accommodating specialized attributes like test results or prescribed medications.

- Configuration Management: When dealing with configuration settings for software applications, there can be different types of configuration elements, each with its own set of attributes. The Abstract Document pattern can be used to manage these configuration elements while ensuring a consistent way to access and manipulate their attributes.

- Educational Platforms: Educational systems might have various types of learning materials such as text-based content, videos, quizzes, and assignments. Common attributes like title, author, and publication date can be shared, while unique attributes like video duration or assignment due dates can be specific to each type.

- Project Management Tools: In project management applications, you could have different types of tasks like to-do items, milestones, and issues. The Abstract Document pattern could be used to handle general attributes like task name and assignee, while allowing for specific attributes like milestone date or issue priority.

- Documents have diverse and evolving attribute structures.

- Dynamically adding new properties is a common requirement.

- Decoupling data access from specific formats is crucial.

- Maintainability and flexibility are critical for the codebase.


The key idea behind the Abstract Document design pattern is to provide a flexible and extensible way to manage different types of documents or entities with shared and distinct attributes. By defining a common interface and implementing it across various document types, you can achieve a more organized and consistent approach to handling complex data structures.

## [Benefits and Trade-offs of Abstract Document Pattern](https://java-design-patterns.com/patterns/abstract-document/#benefits-and-trade-offs-of-abstract-document-pattern)

Benefits:

- Flexibility: Accommodates varied document structures and properties.

- Extensibility: Dynamically add new attributes without breaking existing code.

- Maintainability: Promotes clean and adaptable code due to separation of concerns.

- Reusability: Typed views enable code reuse for accessing specific attribute types.


Trade-offs:

- Complexity: Requires defining interfaces and views, adding implementation overhead.

- Performance: Might introduce slight performance overhead compared to direct data access.


## [References and Credits](https://java-design-patterns.com/patterns/abstract-document/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://amzn.to/49zRP4R)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Abstract Document Pattern (Wikipedia)](https://en.wikipedia.org/wiki/Abstract_Document_Pattern)
- [Dealing with Properties (Martin Fowler)](http://martinfowler.com/apsupp/properties.pdf)

---

## [structural/adapter] Adapter 适配器
> 官方文档: https://java-design-patterns.com/patterns/adapter/

StructuralCompatibilityDecouplingGang of FourInterfaceObject compositionWrappingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/adapter/#also-known-as)

- Wrapper

## [Intent of Adapter Design Pattern](https://java-design-patterns.com/patterns/adapter/#intent-of-adapter-design-pattern)

The Adapter Design Pattern in Java converts the interface of a class into another interface that clients expect, enabling compatibility.

## [Detailed Explanation of Adapter Pattern with Real-World Examples](https://java-design-patterns.com/patterns/adapter/#detailed-explanation-of-adapter-pattern-with-real-world-examples)

Real-world example

> Consider that you have some pictures on your memory card and you need to transfer them to your computer. To transfer them, you need some kind of adapter that is compatible with your computer ports so that you can attach a memory card to your computer. In this case card reader is an adapter. Another example would be the famous power adapter; a three-legged plug can't be connected to a two-pronged outlet, it needs to use a power adapter that makes it compatible with the two-pronged outlets. Yet another example would be a translator translating words spoken by one person to another

In plain words

> Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.

Wikipedia says

> In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.

Sequence diagram

![Adapter sequence diagram](https://java-design-patterns.com/assets/img/adapter-sequence-diagram.6b7d7a73.png)

## [Programmatic Example of Adapter Pattern in Java](https://java-design-patterns.com/patterns/adapter/#programmatic-example-of-adapter-pattern-in-java)

The Adapter Pattern example in Java shows how a class with an incompatible interface can be adapted to work with another class.

Consider a wannabe captain that can only use rowing boats but can't sail at all.

First, we have interfaces `RowingBoat` and `FishingBoat`

```java
public interface RowingBoat {
    void row();
}

@Slf4j
public class FishingBoat {
    public void sail() {
        LOGGER.info("The fishing boat is sailing");
    }
}
```

The captain expects an implementation of `RowingBoat` interface to be able to move.

```java
public class Captain {

    private final RowingBoat rowingBoat;

    // default constructor and setter for rowingBoat
    public Captain(RowingBoat rowingBoat) {
        this.rowingBoat = rowingBoat;
    }

    public void row() {
        rowingBoat.row();
    }
}
```

Now, let's say the pirates are coming and our captain needs to escape but there is only a fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills.

```java
@Slf4j
public class FishingBoatAdapter implements RowingBoat {

    private final FishingBoat boat;

    public FishingBoatAdapter() {
        boat = new FishingBoat();
    }

    @Override
    public void row() {
        boat.sail();
    }
}
```

Now the `Captain` can use the `FishingBoat` to escape the pirates.

```java
  public static void main(final String[] args) {
    // The captain can only operate rowing boats but with adapter he is able to
    // use fishing boats as well
    var captain = new Captain(new FishingBoatAdapter());
    captain.row();
}
```

The program outputs:

```
10:25:08.074 [main] INFO com.iluwatar.adapter.FishingBoat -- The fishing boat is sailing
```

## [When to Use the Adapter Pattern in Java](https://java-design-patterns.com/patterns/adapter/#when-to-use-the-adapter-pattern-in-java)

Use the Adapter pattern in Java when

- You want to use an existing class, and its interface does not match the one you need
- You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces
- You need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. An object adapter can adapt the interface of its parent class.
- Most of the applications using third-party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.

## [Adapter Pattern Java Tutorials](https://java-design-patterns.com/patterns/adapter/#adapter-pattern-java-tutorials)

- [Using the Adapter Design Pattern in Java (Dzone)](https://dzone.com/articles/adapter-design-pattern-in-java)
- [Adapter in Java (Refactoring Guru)](https://refactoring.guru/design-patterns/adapter/java/example)
- [The Adapter Pattern in Java (Baeldung)](https://www.baeldung.com/java-adapter-pattern)
- [Adapter Design Pattern (GeeksForGeeks)](https://www.geeksforgeeks.org/adapter-pattern/)

## [Benefits and Trade-offs of Adapter Pattern](https://java-design-patterns.com/patterns/adapter/#benefits-and-trade-offs-of-adapter-pattern)

Class and object adapters offer different benefits and drawbacks. A class adapter adapts the Adaptee to the Target by binding to a specific Adaptee class, which means it cannot adapt a class and all its subclasses. This type of adapter allows the Adapter to override some of the Adaptee’s behavior because the Adapter is a subclass of the Adaptee. Additionally, it introduces only one object without needing extra pointer indirection to reach the Adaptee.

On the other hand, an object adapter allows a single Adapter to work with multiple Adaptees, including the Adaptee and all its subclasses. This type of adapter can add functionality to all Adaptees simultaneously. However, it makes overriding the Adaptee’s behavior more difficult, as it requires subclassing the Adaptee and having the Adapter refer to this subclass instead of the Adaptee itself.

## [Real-World Applications of Adapter Pattern in Java](https://java-design-patterns.com/patterns/adapter/#real-world-applications-of-adapter-pattern-in-java)

- `java.io.InputStreamReader` and `java.io.OutputStreamWriter` in the Java IO library.
- GUI component libraries that allow for plug-ins or adapters to convert between different GUI component interfaces.
- [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29)
- [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-)
- [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-)
- [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-)

## [References and Credits](https://java-design-patterns.com/patterns/adapter/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [structural/bridge] Bridge 桥接
> 官方文档: https://java-design-patterns.com/patterns/bridge/

StructuralAbstractionDecouplingExtensibilityGang of FourObject compositionAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/bridge/#also-known-as)

- Handle/Body

## [Intent of Bridge Design Pattern](https://java-design-patterns.com/patterns/bridge/#intent-of-bridge-design-pattern)

The Bridge design pattern is a structural pattern in Java that decouples an abstraction from its implementation, allowing both to vary independently. This pattern is essential for developing flexible and extensible software systems.

## [Detailed Explanation of Bridge Pattern with Real-World Examples](https://java-design-patterns.com/patterns/bridge/#detailed-explanation-of-bridge-pattern-with-real-world-examples)

Real-world example

> In Java, the Bridge pattern is commonly used in GUI frameworks, database drivers, and device drivers. For instance, a universal remote control (abstraction) can operate various TV brands (implementations) through a consistent interface.
>
> Imagine a universal remote control (abstraction) that can operate different brands and types of televisions (implementations). The remote control provides a consistent interface for operations like turning on/off, changing channels, and adjusting the volume. Each television brand or type has its own specific implementation of these operations. By using the Bridge pattern, the remote control interface is decoupled from the television implementations, allowing the remote control to work with any television regardless of its brand or internal workings. This separation allows new television models to be added without changing the remote control's code, and different remote controls can be developed to work with the same set of televisions.

In Plain Words

> Bridge pattern is about preferring composition to inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.

Wikipedia says

> The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently"

Sequence diagram

![Bridge sequence diagram](https://java-design-patterns.com/assets/img/bridge-sequence-diagram.400ecb3b.png)

## [Programmatic Example of Bridge Pattern in Java](https://java-design-patterns.com/patterns/bridge/#programmatic-example-of-bridge-pattern-in-java)

Imagine you have a weapon that can have various enchantments, and you need to combine different weapons with different enchantments. How would you handle this? Would you create multiple copies of each weapon, each with a different enchantment, or would you create separate enchantments and apply them to the weapon as needed? The Bridge pattern enables you to do the latter.

Here we have the `Weapon` hierarchy:

```java
public interface Weapon {
    void wield();

    void swing();

    void unwield();

    Enchantment getEnchantment();
}

public class Sword implements Weapon {

    private final Enchantment enchantment;

    public Sword(Enchantment enchantment) {
        this.enchantment = enchantment;
    }

    @Override
    public void wield() {
        LOGGER.info("The sword is wielded.");
        enchantment.onActivate();
    }

    @Override
    public void swing() {
        LOGGER.info("The sword is swung.");
        enchantment.apply();
    }

    @Override
    public void unwield() {
        LOGGER.info("The sword is unwielded.");
        enchantment.onDeactivate();
    }

    @Override
    public Enchantment getEnchantment() {
        return enchantment;
    }
}

public class Hammer implements Weapon {

    private final Enchantment enchantment;

    public Hammer(Enchantment enchantment) {
        this.enchantment = enchantment;
    }

    @Override
    public void wield() {
        LOGGER.info("The hammer is wielded.");
        enchantment.onActivate();
    }

    @Override
    public void swing() {
        LOGGER.info("The hammer is swung.");
        enchantment.apply();
    }

    @Override
    public void unwield() {
        LOGGER.info("The hammer is unwielded.");
        enchantment.onDeactivate();
    }

    @Override
    public Enchantment getEnchantment() {
        return enchantment;
    }
}
```

Here's the separate `Enchantment` hierarchy:

```java
public interface Enchantment {
    void onActivate();

    void apply();

    void onDeactivate();
}

public class FlyingEnchantment implements Enchantment {

    @Override
    public void onActivate() {
        LOGGER.info("The item begins to glow faintly.");
    }

    @Override
    public void apply() {
        LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand.");
    }

    @Override
    public void onDeactivate() {
        LOGGER.info("The item's glow fades.");
    }
}

public class SoulEatingEnchantment implements Enchantment {

    @Override
    public void onActivate() {
        LOGGER.info("The item spreads bloodlust.");
    }

    @Override
    public void apply() {
        LOGGER.info("The item eats the soul of enemies.");
    }

    @Override
    public void onDeactivate() {
        LOGGER.info("Bloodlust slowly disappears.");
    }
}
```

Here are both hierarchies in action:

```java
public static void main(String[] args) {
    LOGGER.info("The knight receives an enchanted sword.");
    var enchantedSword = new Sword(new SoulEatingEnchantment());
    enchantedSword.wield();
    enchantedSword.swing();
    enchantedSword.unwield();

    LOGGER.info("The valkyrie receives an enchanted hammer.");
    var hammer = new Hammer(new FlyingEnchantment());
    hammer.wield();
    hammer.swing();
    hammer.unwield();
}
```

Here's the console output.

```
The knight receives an enchanted sword.
The sword is wielded.
The item spreads bloodlust.
The sword is swung.
The item eats the soul of enemies.
The sword is unwielded.
Bloodlust slowly disappears.
The valkyrie receives an enchanted hammer.
The hammer is wielded.
The item begins to glow faintly.
The hammer is swung.
The item flies and strikes the enemies finally returning to owner's hand.
The hammer is unwielded.
The item's glow fades.
```

## [When to Use the Bridge Pattern in Java](https://java-design-patterns.com/patterns/bridge/#when-to-use-the-bridge-pattern-in-java)

Consider using the Bridge pattern when:

- You need to avoid a permanent binding between an abstraction and its implementation, such as when the implementation must be chosen or switched at runtime.
- Both the abstractions and their implementations should be extendable via subclassing, allowing independent extension of each component.
- Changes to the implementation of an abstraction should not affect clients, meaning their code should not require recompilation.
- You encounter a large number of classes in your hierarchy, indicating the need to split an object into two parts, a concept referred to as "nested generalizations" by Rumbaugh.
- You want to share an implementation among multiple objects, potentially using reference counting, while keeping this detail hidden from the client, as exemplified by Coplien's String class, where multiple objects can share the same string representation.

## [Bridge Pattern Java Tutorials](https://java-design-patterns.com/patterns/bridge/#bridge-pattern-java-tutorials)

- [Bridge Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/bridge-design-pattern-java)

## [Real-World Applications of Bridge Pattern in Java](https://java-design-patterns.com/patterns/bridge/#real-world-applications-of-bridge-pattern-in-java)

- GUI Frameworks where the abstraction is the window, and the implementation could be the underlying OS windowing system.
- Database Drivers where the abstraction is a generic database interface, and the implementations are database-specific drivers.
- Device Drivers where the abstraction is the device-independent code, and the implementation is the device-dependent code.

## [Benefits and Trade-offs of Bridge Pattern](https://java-design-patterns.com/patterns/bridge/#benefits-and-trade-offs-of-bridge-pattern)

Benefits:

- Decoupling Interface and Implementation: The Bridge pattern enhances modularity by separating the interface (the high-level operations) from the implementation (the low-level operations).
- Improved Extensibility: You can extend the abstraction and implementation hierarchies independently.
- Hiding Implementation Details: Clients only see the abstraction's interface, not its implementation.

Trade-offs:

- Increased Complexity: The pattern can complicate the system architecture and code, especially for clients unfamiliar with the pattern.
- Runtime Overhead: The extra layer of abstraction can introduce a performance penalty, although it is often negligible in practice.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/bridge/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): The Abstract Factory pattern can be used along with the Bridge pattern to create platforms that are independent of the concrete classes used to create their objects.
- [Adapter](https://java-design-patterns.com/patterns/adapter/): The Adapter pattern is used to provide a different interface to an object, while the Bridge pattern is used to separate an object's interface from its implementation.
- [Composite](https://java-design-patterns.com/patterns/composite/): The Bridge pattern is often used with the Composite pattern to model the implementation details of a component.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): The Strategy pattern is like the Bridge pattern, but with a different intent. Both patterns are based on composition: Strategy uses composition to change the behavior of a class, while Bridge uses composition to separate an abstraction from its implementation.

## [References and Credits](https://java-design-patterns.com/patterns/bridge/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3TEnhtl)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [structural/business-delegate] Business Delegate
> 官方文档: https://java-design-patterns.com/patterns/business-delegate/

StructuralBusinessDecouplingDelegationEnterprise patternsLayered architectureAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/business-delegate/#also-known-as)

- Service Representative

## [Intent of Business Delegate Design Pattern](https://java-design-patterns.com/patterns/business-delegate/#intent-of-business-delegate-design-pattern)

The Business Delegate pattern is a structural design pattern in Java that adds an abstraction layer between the presentation and business tiers. By using the pattern we gain loose coupling between the tiers and encapsulate knowledge about how to locate, connect to, and interact with the business objects that make up the application.

## [Detailed Explanation of Business Delegate Pattern with Real-World Examples](https://java-design-patterns.com/patterns/business-delegate/#detailed-explanation-of-business-delegate-pattern-with-real-world-examples)

Real-world example

> In an Enterprise application using Java EE, the Business Delegate pattern helps manage interactions between different business services.
>
> Imagine a restaurant where the waitstaff serves as intermediaries between the customers and the kitchen. When a customer places an order, the waiter takes the order to the kitchen, relays any specific requests, and later brings the prepared food back to the customer. The waitstaff abstracts the complexity of the kitchen operations from the customers, allowing the chefs to focus solely on cooking without needing to interact directly with customers. This setup allows both the customer service (presentation tier) and the kitchen (business service) to operate independently and efficiently. The waitstaff acts as the Business Delegate, managing communication and ensuring smooth interactions between the two distinct areas.

In Plain Words

> Business Delegate adds an abstraction layer between the presentation and business tiers.

Wikipedia says

> Business Delegate is a Java EE design pattern. This pattern is directing to reduce the coupling in between business services and the connected presentation tier, and to hide the implementation details of services (including lookup and accessibility of EJB architecture). Business Delegates acts as an adaptor to invoke business objects from the presentation tier.

Sequence diagram

![Business Delegate sequence diagram](https://java-design-patterns.com/assets/img/business-delegate-sequence-diagram.124f8ba7.png)

## [Programmatic Example of Business Delegate Pattern in Java](https://java-design-patterns.com/patterns/business-delegate/#programmatic-example-of-business-delegate-pattern-in-java)

The following Java code demonstrates how to implement the Business Delegate pattern. This pattern is particularly useful in applications requiring loose coupling and efficient service interaction.

A mobile phone application promises to stream any movie in existence to your device. It captures the user's search string and passes this on to the Business Delegate. The Business Delegate selects the most suitable video streaming service and plays the video from there.

First, we have an abstraction for video streaming services and a couple of implementations.

```java
public interface VideoStreamingService {
    void doProcessing();
}

@Slf4j
public class NetflixService implements VideoStreamingService {
    @Override
    public void doProcessing() {
        LOGGER.info("NetflixService is now processing");
    }
}

@Slf4j
public class YouTubeService implements VideoStreamingService {
    @Override
    public void doProcessing() {
        LOGGER.info("YouTubeService is now processing");
    }
}
```

Then, we have a lookup service that decides which video streaming service to use.

```java

@Setter
public class BusinessLookup {

    private NetflixService netflixService;
    private YouTubeService youTubeService;

    public VideoStreamingService getBusinessService(String movie) {
        if (movie.toLowerCase(Locale.ROOT).contains("die hard")) {
            return netflixService;
        } else {
            return youTubeService;
        }
    }
}
```

The Business Delegate uses a business lookup to route movie playback requests to a suitable video streaming service.

```java

@Setter
public class BusinessDelegate {

    private BusinessLookup lookupService;

    public void playbackMovie(String movie) {
        VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie);
        videoStreamingService.doProcessing();
    }
}
```

The mobile client utilizes Business Delegate to call the business tier.

```java
public class MobileClient {

    private final BusinessDelegate businessDelegate;

    public MobileClient(BusinessDelegate businessDelegate) {
        this.businessDelegate = businessDelegate;
    }

    public void playbackMovie(String movie) {
        businessDelegate.playbackMovie(movie);
    }
}
```

Finally, we can demonstrate the complete example in action.

```java
public static void main(String[] args) {

    // prepare the objects
    var businessDelegate = new BusinessDelegate();
    var businessLookup = new BusinessLookup();
    businessLookup.setNetflixService(new NetflixService());
    businessLookup.setYouTubeService(new YouTubeService());
    businessDelegate.setLookupService(businessLookup);

    // create the client and use the business delegate
    var client = new MobileClient(businessDelegate);
    client.playbackMovie("Die Hard 2");
    client.playbackMovie("Maradona: The Greatest Ever");
}
```

Here is the console output.

```
21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing
21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing
```

## [When to Use the Business Delegate Pattern in Java](https://java-design-patterns.com/patterns/business-delegate/#when-to-use-the-business-delegate-pattern-in-java)

Use the Business Delegate pattern when

- You need loose coupling between presentation and business tiers or need to abstract service lookups.
- You want to orchestrate calls to multiple business services
- You want to encapsulate service lookups and service calls
- There is a need to abstract and encapsulate the communication between the client tier and business services

## [Business Delegate Pattern Java Tutorials](https://java-design-patterns.com/patterns/business-delegate/#business-delegate-pattern-java-tutorials)

- [Design Patterns - Business Delegate Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm)

## [Real-World Applications of Business Delegate Pattern in Java](https://java-design-patterns.com/patterns/business-delegate/#real-world-applications-of-business-delegate-pattern-in-java)

- Enterprise applications using Java EE (Java Platform, Enterprise Edition)
- Applications requiring remote access to business services

## [Benefits and Trade-offs of Business Delegate Pattern](https://java-design-patterns.com/patterns/business-delegate/#benefits-and-trade-offs-of-business-delegate-pattern)

Benefits:

- Decoupling of Presentation and Business Tiers: Allows the client tier and business services to evolve independently.
- Location Transparency: Clients remain unaffected by changes in the location or the instantiation of business services.
- Reuse and Scalability: Business Delegate objects can be reused by multiple clients, and the pattern supports load balancing and scalability.

Trade-offs:

- Complexity: Introduces additional layers and abstractions, which may increase complexity.
- Performance Overhead: The additional indirection may incur a slight performance penalty.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/business-delegate/#related-java-design-patterns)

- [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Business Delegate uses Service Locator to locate business services.
- [Session Facade](https://java-design-patterns.com/patterns/session-facade/): Business Delegate may use Session Facade to provide a unified interface to a set of business services.
- [Composite Entity](https://java-design-patterns.com/patterns/composite-entity/): Business Delegate may use Composite Entity to manage the state of business services.

## [References and Credits](https://java-design-patterns.com/patterns/business-delegate/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [structural/component] Component
> 官方文档: https://java-design-patterns.com/patterns/component/

StructuralGame programmingDecouplingModularityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/component/#also-known-as)

- Entity-Component-System (ECS)
- Component-Entity-System (CES)
- Component-Based Architecture (CBA)

## [Intent of Component Design Pattern](https://java-design-patterns.com/patterns/component/#intent-of-component-design-pattern)

The Component design pattern organizes code into reusable, interchangeable components, promoting flexibility, modularity, and ease of maintenance. This pattern is especially useful in game development, enabling entities to be configured with diverse behaviors dynamically.

## [Detailed Explanation of Component Pattern with Real-World Examples](https://java-design-patterns.com/patterns/component/#detailed-explanation-of-component-pattern-with-real-world-examples)

Real-world example

> Consider a video game with a graphics component and a sound component. Including both in a single Java class can create maintenance challenges due to lengthy code and potential conflicts from different teams working on the same class. The Component design pattern resolves this by creating individual component classes for graphics and sound, allowing flexible and independent development. This modular approach enhances maintainability and scalability.

In plain words

> The component design pattern provides a single attribute to be accessible by numerous objects without requiring the existence of a relationship between the objects themselves.

Architecture diagram

![Component architecture diagram](https://java-design-patterns.com/assets/img/component-architecture-diagram.d800f07b.png)

## [Programmatic Example of Component Pattern in Java](https://java-design-patterns.com/patterns/component/#programmatic-example-of-component-pattern-in-java)

The `App` class creates a demonstration of the use of the component pattern by creating two different objects which inherit a small collection of individual components that are modifiable.

```java
public final class App {

    public static void main(String[] args) {
        final var player = GameObject.createPlayer();
        final var npc = GameObject.createNpc();

        LOGGER.info("Player Update:");
        player.update(KeyEvent.KEY_LOCATION_LEFT);
        LOGGER.info("NPC Update:");
        npc.demoUpdate();
    }
}
```

Much of the program exists within the `GameObject` class, within this class, the player and NPC object create methods are set up. Additionally, this class also consists of the method calls used to update/alter information of the object's components.

```java
public class GameObject {
    private final InputComponent inputComponent;
    private final PhysicComponent physicComponent;
    private final GraphicComponent graphicComponent;

    public String name;
    public int velocity = 0;
    public int coordinate = 0;

    public static GameObject createPlayer() {
        return new GameObject(new PlayerInputComponent(),
                new ObjectPhysicComponent(),
                new ObjectGraphicComponent(),
                "player");
    }

    public static GameObject createNpc() {
        return new GameObject(
                new DemoInputComponent(),
                new ObjectPhysicComponent(),
                new ObjectGraphicComponent(),
                "npc");
    }

    public void demoUpdate() {
        inputComponent.update(this);
        physicComponent.update(this);
        graphicComponent.update(this);
    }

    public void update(int e) {
        inputComponent.update(this, e);
        physicComponent.update(this);
        graphicComponent.update(this);
    }

    public void updateVelocity(int acceleration) {
        this.velocity += acceleration;
    }

    public void updateCoordinate() {
        this.coordinate += this.velocity;
    }
}
```

Upon opening the component package, the collection of components are revealed. These components provide the interface for objects to inherit these domains. The `PlayerInputComponent` class shown below updates the object's velocity characteristic based on user's key event input.

```java
public class PlayerInputComponent implements InputComponent {
    private static final int walkAcceleration = 1;

    @Override
    public void update(GameObject gameObject, int e) {
        switch (e) {
            case KeyEvent.KEY_LOCATION_LEFT -> {
                gameObject.updateVelocity(-WALK_ACCELERATION);
                LOGGER.info(gameObject.getName() + " has moved left.");
            }
            case KeyEvent.KEY_LOCATION_RIGHT -> {
                gameObject.updateVelocity(WALK_ACCELERATION);
                LOGGER.info(gameObject.getName() + " has moved right.");
            }
            default -> {
                LOGGER.info(gameObject.getName() + "'s velocity is unchanged due to the invalid input");
                gameObject.updateVelocity(0);
            } // incorrect input
        }
    }
}
```

## [When to Use the Component Pattern in Java](https://java-design-patterns.com/patterns/component/#when-to-use-the-component-pattern-in-java)

- Used in game development and simulations where game entities (e.g., characters, items) can have a dynamic set of abilities or states.
- Suitable for systems requiring high modularity and systems where entities might need to change behavior at runtime without inheritance hierarchies.

## [Real-World Applications of Component Pattern in Java](https://java-design-patterns.com/patterns/component/#real-world-applications-of-component-pattern-in-java)

The Component pattern is ideal for game development and simulations where entities like characters and items have dynamic abilities or states. It suits systems requiring high modularity and scenarios where entities need to change behavior at runtime without relying on inheritance hierarchies, enhancing flexibility and maintainability.

## [Benefits and Trade-offs of Component Pattern](https://java-design-patterns.com/patterns/component/#benefits-and-trade-offs-of-component-pattern)

Benefits:

- Flexibility and Reusability: Components can be reused across different entities, making it easier to add new features or modify existing ones.
- Decoupling: Reduces dependencies between game entity states and behaviors, facilitating easier changes and maintenance.
- Dynamic Composition: Entities can alter their behavior at runtime by adding or removing components, providing significant flexibility in game design.

Trade-offs:

- Complexity: Can introduce additional complexity in system architecture, particularly in managing dependencies and communications between components.
- Performance Considerations: Depending on implementation, may incur a performance overhead due to indirection and dynamic behavior, especially critical in high-performance game loops.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/component/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar concept of adding responsibilities dynamically, but without the focus on game entities.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with the Component pattern to share component instances among many entities to save memory.
- [Observer](https://java-design-patterns.com/patterns/observer/): Often used in Component systems to communicate state changes between components.

## [References and Credits](https://java-design-patterns.com/patterns/component/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/4cDRWhV)
- [Procedural Content Generation for Unity Game Development](https://amzn.to/3vBKCTp)
- [Unity in Action: Multiplatform Game Development in C#](https://amzn.to/3THO6vw)
- [Component (Game Programming Patterns)](https://gameprogrammingpatterns.com/component.html)
- [Component pattern - game programming series (Tutemic)](https://www.youtube.com/watch?v=n92GBp2WMkg&ab_channel=Tutemic)

---

## [structural/composite] Composite 组合
> 官方文档: https://java-design-patterns.com/patterns/composite/

StructuralDecouplingGang of FourObject compositionRecursionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/composite/#also-known-as)

- Object Tree
- Composite Structure

## [Intent of Composite Design Pattern](https://java-design-patterns.com/patterns/composite/#intent-of-composite-design-pattern)

Compose objects into tree structures to represent part-whole hierarchies. The Composite Design Pattern lets clients treat individual objects and compositions of objects uniformly.

## [Detailed Explanation of Composite Pattern with Real-World Examples](https://java-design-patterns.com/patterns/composite/#detailed-explanation-of-composite-pattern-with-real-world-examples)

Real-world example

> In a real-world example, consider a company with a complex organizational structure. The company consists of various departments, each of which can contain sub-departments, and ultimately individual employees. The Composite Design Pattern can be used to represent this structure. Each department and employee are treated as a node in a tree structure, where departments can contain other departments or employees, but employees are leaf nodes with no children. This allows the company to perform operations uniformly, such as calculating total salaries or printing the organizational chart, by treating individual employees and entire departments in the same way.

In plain words

> The Composite Design Pattern lets clients uniformly treat individual objects and compositions of objects.

Wikipedia says

> In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Flowchart

![Composite flowchart](https://java-design-patterns.com/assets/img/composite-flowchart.26643a3f.png)

## [Programmatic Example of Composite Pattern in Java](https://java-design-patterns.com/patterns/composite/#programmatic-example-of-composite-pattern-in-java)

Every sentence is composed of words which are in turn composed of characters. Each of these objects are printable, and they can have something printed before or after them like sentence always ends with full stop and word always has space before it.

Here we have the base class `LetterComposite` and the different printable types `Letter`, `Word` and `Sentence`.

```java
public abstract class LetterComposite {

    private final List<LetterComposite> children = new ArrayList<>();

    public void add(LetterComposite letter) {
        children.add(letter);
    }

    public int count() {
        return children.size();
    }

    protected void printThisBefore() {
    }

    protected void printThisAfter() {
    }

    public void print() {
        printThisBefore();
        children.forEach(LetterComposite::print);
        printThisAfter();
    }
}

public class Letter extends LetterComposite {

    private final char character;

    public Letter(char c) {
        this.character = c;
    }

    @Override
    protected void printThisBefore() {
        System.out.print(character);
    }
}

public class Word extends LetterComposite {

    public Word(List<Letter> letters) {
        letters.forEach(this::add);
    }

    public Word(char... letters) {
        for (char letter : letters) {
            this.add(new Letter(letter));
        }
    }

    @Override
    protected void printThisBefore() {
        System.out.print(" ");
    }
}

public class Sentence extends LetterComposite {

    public Sentence(List<Word> words) {
        words.forEach(this::add);
    }

    @Override
    protected void printThisAfter() {
        System.out.print(".");
    }
}
```

Then we have a messenger to carry messages:

```java
public class Messenger {

    LetterComposite messageFromOrcs() {

        var words = List.of(
                new Word('W', 'h', 'e', 'r', 'e'),
                new Word('t', 'h', 'e', 'r', 'e'),
                new Word('i', 's'),
                new Word('a'),
                new Word('w', 'h', 'i', 'p'),
                new Word('t', 'h', 'e', 'r', 'e'),
                new Word('i', 's'),
                new Word('a'),
                new Word('w', 'a', 'y')
        );

        return new Sentence(words);

    }

    LetterComposite messageFromElves() {

        var words = List.of(
                new Word('M', 'u', 'c', 'h'),
                new Word('w', 'i', 'n', 'd'),
                new Word('p', 'o', 'u', 'r', 's'),
                new Word('f', 'r', 'o', 'm'),
                new Word('y', 'o', 'u', 'r'),
                new Word('m', 'o', 'u', 't', 'h')
        );

        return new Sentence(words);

    }

}
```

And then it can be used as:

```java
  public static void main(String[] args) {

    var messenger = new Messenger();

    LOGGER.info("Message from the orcs: ");
    messenger.messageFromOrcs().print();

    LOGGER.info("Message from the elves: ");
    messenger.messageFromElves().print();
}
```

The console output:

```
20:43:54.801 [main] INFO com.iluwatar.composite.App -- Message from the orcs:
 Where there is a whip there is a way.
20:43:54.803 [main] INFO com.iluwatar.composite.App -- Message from the elves:
 Much wind pours from your mouth.
```

## [When to Use the Composite Pattern in Java](https://java-design-patterns.com/patterns/composite/#when-to-use-the-composite-pattern-in-java)

Use the Composite pattern when

- You want to represent part-whole hierarchies of objects.
- You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

## [Real-World Applications of Composite Pattern in Java](https://java-design-patterns.com/patterns/composite/#real-world-applications-of-composite-pattern-in-java)

- Graphical user interfaces where components can contain other components (e.g., panels containing buttons, labels, other panels).
- File system representations where directories can contain files and other directories.
- Organizational structures where a department can contain sub-departments and employees.
- [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) and [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html)
- [Apache Wicket](https://github.com/apache/wicket) component tree, see [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) and [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java)

## [Benefits and Trade-offs of Composite Pattern](https://java-design-patterns.com/patterns/composite/#benefits-and-trade-offs-of-composite-pattern)

Benefits:

- Simplifies client code, as it can treat composite structures and individual objects uniformly.
- Makes it easier to add new kinds of components, as existing code doesn't need to be changed.

Trade-offs:

- Can make the design overly general. It might be difficult to restrict the components of a composite.
- Can make it harder to restrict the types of components in a composite.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/composite/#related-java-design-patterns)

- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Composite can use Flyweight to share component instances among several composites.
- [Iterator](https://java-design-patterns.com/patterns/iterator/): Can be used to traverse Composite structures.
- [Visitor](https://java-design-patterns.com/patterns/visitor/): Can apply an operation over a Composite structure.

## [References and Credits](https://java-design-patterns.com/patterns/composite/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)
- [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3xoLAmi)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3vBKXWb)

---

## [structural/composite-entity] Composite Entity
> 官方文档: https://java-design-patterns.com/patterns/composite-entity/

StructuralClient-serverData accessDecouplingEnterprise patternsObject compositionPersistenceResource managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/composite-entity/#also-known-as)

- Coarse-Grained Entity

## [Intent of Composite Entity Design Pattern](https://java-design-patterns.com/patterns/composite-entity/#intent-of-composite-entity-design-pattern)

The Composite Entity design pattern in Java is aimed at managing a set of interrelated persistent objects as if they were a single entity. It is commonly used in enterprise applications, particularly within the context of Enterprise JavaBeans (EJB) and similar enterprise frameworks, to represent graph-based data structures within business models. This pattern enables clients to treat these complex structures as a single unit, simplifying operations and interactions.

## [Detailed Explanation of Composite Entity Pattern with Real-World Examples](https://java-design-patterns.com/patterns/composite-entity/#detailed-explanation-of-composite-entity-pattern-with-real-world-examples)

Real-world example

> Consider a university registration system where a "Student" entity is a composite entity. Each "Student" object includes several dependent objects: personal details, course enrollments, grades, and payment information. Instead of managing each of these aspects separately, the Composite Entity design pattern allows the university system to treat the "Student" as a single entity. This simplifies operations such as enrolling a student in a new course, updating grades, and processing payments, since all related actions can be managed through the composite "Student" object.

In plain words

> The Composite Entity pattern in Java allows a set of related persistent objects to be represented and managed by a unified object, simplifying enterprise application design.

Wikipedia says

> Composite entity is a Java EE Software design pattern and it is used to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans, and also a composite entity bean represents a graph of objects.

Flowchart

![Composite Entity flowchart](https://java-design-patterns.com/assets/img/composite-entity-flowchart.9c0444e8.png)

## [Programmatic Example of Composite Entity in Java](https://java-design-patterns.com/patterns/composite-entity/#programmatic-example-of-composite-entity-in-java)

For a console, there may be many interfaces that need to be managed and controlled. Using the composite entity pattern, dependent objects such as messages and signals can be combined and controlled using a single object.

We need a generic solution for the problem. To achieve this, let's introduce a generic Composite Entity Pattern.

```java
public abstract class DependentObject<T> {

    T data;

    public void setData(T message) {
        this.data = message;
    }

    public T getData() {
        return data;
    }
}

public abstract class CoarseGrainedObject<T> {

    DependentObject<T>[] dependentObjects;

    public void setData(T... data) {
        IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i]));
    }

    public T[] getData() {
        return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray();
    }
}
```

The specialized composite entity `console` inherit from this base class as follows.

```java
public class MessageDependentObject extends DependentObject<String> {

}

public class SignalDependentObject extends DependentObject<String> {

}

public class ConsoleCoarseGrainedObject extends CoarseGrainedObject<String> {

    @Override
    public String[] getData() {
        super.getData();
        return new String[] {
                dependentObjects[0].getData(), dependentObjects[1].getData()
        };
    }

    public void init() {
        dependentObjects = new DependentObject[] {
                new MessageDependentObject(), new SignalDependentObject()};
    }
}

public class CompositeEntity {

    private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject();

    public void setData(String message, String signal) {
        console.setData(message, signal);
    }

    public String[] getData() {
        return console.getData();
    }
}
```

Now managing the assignment of message and signal objects with the composite entity `console`.

```java
public App(String message, String signal) {
    var console = new CompositeEntity();
    console.init();
    console.setData(message, signal);
    Arrays.stream(console.getData()).forEach(LOGGER::info);
    console.setData("Danger", "Red Light");
    Arrays.stream(console.getData()).forEach(LOGGER::info);
}
```

## [When to Use the Composite Entity Pattern in Java](https://java-design-patterns.com/patterns/composite-entity/#when-to-use-the-composite-entity-pattern-in-java)

- Useful in Java enterprise applications where business objects are complex and involve various interdependent persistent objects.
- Ideal for scenarios where clients need to work with a unified interface to a set of objects rather than individual entities.
- Applicable in systems that require a simplified view of a complex data model for external clients or services.

## [Real-World Applications of Composite Entity Pattern in Java](https://java-design-patterns.com/patterns/composite-entity/#real-world-applications-of-composite-entity-pattern-in-java)

- Enterprise applications with complex business models, particularly those using EJB or similar enterprise frameworks.
- Systems requiring abstraction over complex database schemas to simplify client interactions.
- Applications that need to enforce consistency or transactions across multiple persistent objects in a business entity.

## [Benefits and Trade-offs of Composite Entity Pattern](https://java-design-patterns.com/patterns/composite-entity/#benefits-and-trade-offs-of-composite-entity-pattern)

Benefits:

- Simplifies client interactions with complex entity models by providing a unified interface.
- Enhances reusability and maintainability of the business layer by decoupling client code from the complex internals of business entities.
- Facilitates easier transaction management and consistency enforcement across a set of related persistent objects.

Trade-offs:

- May introduce a level of indirection that could impact performance.
- Can lead to overly coarse-grained interfaces that might not be as flexible for all client needs.
- Requires careful design to avoid bloated composite entities that are difficult to manage.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/composite-entity/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): For dynamically adding behavior to individual objects within the composite entity without affecting the structure.
- [Facade](https://java-design-patterns.com/patterns/facade/): Provides a simplified interface to a complex subsystem, similar to how a composite entity simplifies access to a set of objects.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for managing shared objects within a composite entity to reduce memory footprint.

## [References and Credits](https://java-design-patterns.com/patterns/composite-entity/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML](https://amzn.to/49mslqS)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3xjKdpe)
- [Composite Entity Pattern (Wikipedia)](https://en.wikipedia.org/wiki/Composite_entity_pattern)

---

## [structural/composite-view] Composite View
> 官方文档: https://java-design-patterns.com/patterns/composite-view/

StructuralAbstractionEnterprise patternsObject compositionPresentationAbout 5 min

* * *

## [Intent of Composite View Design Pattern](https://java-design-patterns.com/patterns/composite-view/#intent-of-composite-view-design-pattern)

The primary goal of the Composite View design pattern is to compose objects into tree structures to represent part-whole hierarchies. This allows clients to treat individual objects and compositions of objects uniformly, simplifying the management of complex hierarchical views.

## [Detailed Explanation of Composite View Pattern with Real-World Examples](https://java-design-patterns.com/patterns/composite-view/#detailed-explanation-of-composite-view-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Composite View design pattern is the layout of a dashboard in a web application. Consider a financial dashboard that displays various widgets such as stock charts, recent transactions, account balances, and news feeds. Each of these widgets is a separate view component that can be independently updated and managed. By using the Composite View pattern, these individual widgets are composed into a single unified dashboard view. This approach allows for easy reorganization of the dashboard, the addition of new widgets without disrupting existing ones, and consistent management of the overall layout. This hierarchical composition of views mirrors how different sections of the dashboard are treated both as individual entities and as part of a larger whole.

In plain words

> Composite View Pattern is having a main view being composed of smaller subviews. The layout of this composite view is based on a template. A View-manager then decides which subviews to include in this template.

Wikipedia says

> Composite views that are composed of multiple atomic subviews. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content. This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design.

Flowchart

![Composite View flowchart](https://java-design-patterns.com/assets/img/composite-view-flowchart.a5b82644.png)

## [Programmatic Example of Composite View Pattern in Java](https://java-design-patterns.com/patterns/composite-view/#programmatic-example-of-composite-view-pattern-in-java)

A news site wants to display the current date and news to different users based on that user's preferences. The news site will substitute in different news feed components depending on the user's interest, defaulting to local news.

Since this is a web development pattern, a server is required to demonstrate it. This example uses Tomcat 10.0.13 to run the servlet, and this programmatic example will only work with Tomcat 10+.

Firstly, there is `AppServlet` which is an `HttpServlet` that runs on Tomcat 10+.

```java
public class AppServlet extends HttpServlet {
    private String msgPartOne = "<h1>This Server Doesn't Support";
    private String msgPartTwo = "Requests</h1>\n"
            + "<h2>Use a GET request with boolean values for the following parameters<h2>\n"
            + "<h3>'name'</h3>\n<h3>'bus'</h3>\n<h3>'sports'</h3>\n<h3>'sci'</h3>\n<h3>'world'</h3>";

    private String destination = "newsDisplay.jsp";

    public AppServlet() {

    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination);
        ClientPropertiesBean reqParams = new ClientPropertiesBean(req);
        req.setAttribute("properties", reqParams);
        requestDispatcher.forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println(msgPartOne + " Post " + msgPartTwo);

    }

    @Override
    public void doDelete(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println(msgPartOne + " Delete " + msgPartTwo);

    }

    @Override
    public void doPut(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println(msgPartOne + " Put " + msgPartTwo);

    }
}
```

This servlet is not part of the pattern, and simply forwards GET requests to the correct JSP. PUT, POST, and DELETE requests are not supported and will simply show an error message.

The view management in this example is done via a javabean class: `ClientPropertiesBean`, which stores user preferences.

```java
public class ClientPropertiesBean implements Serializable {

    private static final String WORLD_PARAM = "world";
    private static final String SCIENCE_PARAM = "sci";
    private static final String SPORTS_PARAM = "sport";
    private static final String BUSINESS_PARAM = "bus";
    private static final String NAME_PARAM = "name";

    private static final String DEFAULT_NAME = "DEFAULT_NAME";
    private boolean worldNewsInterest;
    private boolean sportsInterest;
    private boolean businessInterest;
    private boolean scienceNewsInterest;
    private String name;

    public ClientPropertiesBean() {
        worldNewsInterest = true;
        sportsInterest = true;
        businessInterest = true;
        scienceNewsInterest = true;
        name = DEFAULT_NAME;

    }

    public ClientPropertiesBean(HttpServletRequest req) {
        worldNewsInterest = Boolean.parseBoolean(req.getParameter(WORLD_PARAM));
        sportsInterest = Boolean.parseBoolean(req.getParameter(SPORTS_PARAM));
        businessInterest = Boolean.parseBoolean(req.getParameter(BUSINESS_PARAM));
        scienceNewsInterest = Boolean.parseBoolean(req.getParameter(SCIENCE_PARAM));
        String tempName = req.getParameter(NAME_PARAM);
        if (tempName == null || tempName == "") {
            tempName = DEFAULT_NAME;
        }
        name = tempName;
    }
    // getters and setters generated by Lombok
}
```

This javabean has a default constructor, and another that takes an `HttpServletRequest`.

This second constructor takes the request object, parses out the request parameters which contain the user preferences for different types of news.

The template for the news page is in `newsDisplay.jsp`

```html

<html>
<head>
    <style>
        h1 {
            text-align: center;
        }

        h2 {
            text-align: center;
        }

        h3 {
            text-align: center;
        }

        .centerTable {
            margin-left: auto;
            margin-right: auto;
        }

        table {
            border: 1px solid black;
        }

        tr {
            text-align: center;
        }

        td {
            text-align: center;
        }
    </style>
</head>
<body>
<%ClientPropertiesBean propertiesBean = (ClientPropertiesBean) request.getAttribute("properties");%>
<h1>Welcome <%= propertiesBean.getName()%></h1>
<jsp:include page="header.jsp"></jsp:include>
<table class="centerTable">

    <tr>
        <td></td>
        <% if(propertiesBean.isWorldNewsInterest()) { %>
        <td><%@include file="worldNews.jsp"%></td>
        <% } else { %>
        <td><%@include file="localNews.jsp"%></td>
        <% } %>
        <td></td>
    </tr>
    <tr>
        <% if(propertiesBean.isBusinessInterest()) { %>
        <td><%@include file="businessNews.jsp"%></td>
        <% } else { %>
        <td><%@include file="localNews.jsp"%></td>
        <% } %>
        <td></td>
        <% if(propertiesBean.isSportsInterest()) { %>
        <td><%@include file="sportsNews.jsp"%></td>
        <% } else { %>
        <td><%@include file="localNews.jsp"%></td>
        <% } %>
    </tr>
    <tr>
        <td></td>
        <% if(propertiesBean.isScienceNewsInterest()) { %>
        <td><%@include file="scienceNews.jsp"%></td>
        <% } else { %>
        <td><%@include file="localNews.jsp"%></td>
        <% } %>
        <td></td>
    </tr>
</table>
</body>
</html>
```

This JSP page is the template. It declares a table with three rows, with one component in the first row, two components in the second row, and one component in the third row.

The scriplets in the file are part of the view management strategy that include different atomic subviews based on the user preferences in the Javabean.

Here are two examples of the mock atomic subviews used in the composite: `businessNews.jsp`

```html

<html>
<head>
    <style>
        h2 {
            text-align: center;
        }

        table {
            border: 1px solid black;
        }

        tr {
            text-align: center;
        }

        td {
            text-align: center;
        }
    </style>
</head>
<body>
<h2>
    Generic Business News
</h2>
<table style="margin-right: auto; margin-left: auto">
    <tr>
        <td>Stock prices up across the world</td>
        <td>New tech companies to invest in</td>
    </tr>
    <tr>
        <td>Industry leaders unveil new project</td>
        <td>Price fluctuations and what they mean</td>
    </tr>
</table>
</body>
</html>
```

`localNews.jsp`

```html

<html>
<body>
<div style="text-align: center">
    <h3>
        Generic Local News
    </h3>
    <ul style="list-style-type: none">
        <li>
            Mayoral elections coming up in 2 weeks
        </li>
        <li>
            New parking meter rates downtown coming tomorrow
        </li>
        <li>
            Park renovations to finish by the next year
        </li>
        <li>
            Annual marathon sign ups available online
        </li>
    </ul>
</div>
</body>
</html>
```

The different subviews such as `worldNews.jsp`, `businessNews.jsp`, etc. are included conditionally based on the request parameters.

**How To Use**

To try this example, make sure you have Tomcat 10+ installed. Set up your IDE to build a WAR file from the module and deploy that file to the server

IntelliJ:

Under `Run` and `edit configurations` Make sure Tomcat server is one of the run configurations. Go to the deployment tab, and make sure there is one artifact being built called `composite-view:war exploded`. If not present, add one.

Ensure that the artifact is being built from the content of the `web` directory and the compilation results of the module. Point the output of the artifact to a convenient place. Run the configuration and view the landing page, follow instructions on that page to continue.

## [When to Use the Composite View Pattern in Java](https://java-design-patterns.com/patterns/composite-view/#when-to-use-the-composite-view-pattern-in-java)

Use the Composite View design pattern when:

- You want to represent part-whole hierarchies of objects.
- You expect that the composite structures might include any new components in the future.
- You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

## [Composite View Pattern Java Tutorials](https://java-design-patterns.com/patterns/composite-view/#composite-view-pattern-java-tutorials)

- [Composite View Design Pattern – Core J2EE Patterns (Dinesh on Java)](https://www.dineshonjava.com/composite-view-design-pattern/)

## [Real-World Applications of Composite View Pattern in Java](https://java-design-patterns.com/patterns/composite-view/#real-world-applications-of-composite-view-pattern-in-java)

- Graphical User Interfaces (GUIs) where widgets can contain other widgets (e.g., a window containing panels, buttons, and text fields).
- Document structures, such as the representation of tables containing rows, which in turn contain cells, all of which can be treated as elements in a unified hierarchy.

## [Benefits and Trade-offs of Composite View Pattern](https://java-design-patterns.com/patterns/composite-view/#benefits-and-trade-offs-of-composite-view-pattern)

Benefits:

- High flexibility in adding new components: Since composites and leaf nodes are treated uniformly, it's easier to add new kinds of components.
- Simplified client code: Clients can treat composite structures and individual elements uniformly, reducing the complexity in client code.

Trade-offs:

- Overgeneralization: Designing the system might become more complex if you make everything composite, especially if your application doesn't require it.
- Difficulty in constraint enforcement: It can be harder to restrict the components of a composite to only certain types.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/composite-view/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): General structural pattern that is the foundation for Composite View, used for treating individual objects and compositions uniformly.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Enhances the behavior of individual views without modifying the underlying view.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used to manage memory consumption of large numbers of similar view objects.
- View Helper: Separates the view logic from business logic, aiding in the clean organization and management of view components.

## [References and Credits](https://java-design-patterns.com/patterns/composite-view/#references-and-credits)

- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3xfntGJ)
- [Patterns of Enterprise Application Architecture](https://amzn.to/49jpQG3)
- [Core J2EE Patterns - Composite View (Oracle)](https://www.oracle.com/java/technologies/composite-view.html)

---

## [structural/converter] Converter
> 官方文档: https://java-design-patterns.com/patterns/converter/

StructuralCompatibilityData transformationDecouplingInterfaceObject mappingWrappingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/converter/#also-known-as)

- Mapper
- Translator

## [Intent of Converter Design Pattern](https://java-design-patterns.com/patterns/converter/#intent-of-converter-design-pattern)

The purpose of the Converter Pattern is to provide a generic, systematic way of bidirectional conversion between corresponding data types. This allows for a clean, decoupled implementation where types are unaware of each other. Additionally, the Converter pattern supports bidirectional collection mapping, minimizing boilerplate code.

## [Detailed Explanation of Converter Pattern with Real-World Examples](https://java-design-patterns.com/patterns/converter/#detailed-explanation-of-converter-pattern-with-real-world-examples)

Real-world example

> In a real-world scenario, consider a library system that interacts with a third-party book database. The library uses an internal book format, while the third-party database uses a different format. By employing the Converter Pattern, a converter class can transform the third-party book data into the library's format and vice versa. This ensures seamless integration without altering the internal structures of either system.

In plain words

> The Converter Pattern simplifies mapping instances of one class to instances of another class, ensuring consistent and clean data transformation.

Sequence diagram

![Converter sequence diagram](https://java-design-patterns.com/assets/img/converter-sequence-diagram.9376d20c.png)

## [Programmatic Example of Converter Pattern in Java](https://java-design-patterns.com/patterns/converter/#programmatic-example-of-converter-pattern-in-java)

In applications, it's common for the database layer to have entities that need mapping to DTOs (Data Transfer Objects) for business logic. This mapping often involves many classes, necessitating a generic solution.

We introduce a generic `Converter` class:

```java
public class Converter<T, U> {

    private final Function<T, U> fromDto;
    private final Function<U, T> fromEntity;

    public Converter(final Function<T, U> fromDto, final Function<U, T> fromEntity) {
        this.fromDto = fromDto;
        this.fromEntity = fromEntity;
    }

    public final U convertFromDto(final T dto) {
        return fromDto.apply(dto);
    }

    public final T convertFromEntity(final U entity) {
        return fromEntity.apply(entity);
    }

    public final List<U> createFromDtos(final Collection<T> dtos) {
        return dtos.stream().map(this::convertFromDto).collect(Collectors.toList());
    }

    public final List<T> createFromEntities(final Collection<U> entities) {
        return entities.stream().map(this::convertFromEntity).collect(Collectors.toList());
    }
}
```

Specialized converters inherit from this base class:

```java
public class UserConverter extends Converter<UserDto, User> {

    public UserConverter() {
        super(UserConverter::convertToEntity, UserConverter::convertToDto);
    }

    private static UserDto convertToDto(User user) {
        return new UserDto(user.firstName(), user.lastName(), user.active(), user.userId());
    }

    private static User convertToEntity(UserDto dto) {
        return new User(dto.firstName(), dto.lastName(), dto.active(), dto.email());
    }
}
```

Mapping between `User` and `UserDto` becomes straightforward:

```java
  public static void main(String[] args) {
    Converter<UserDto, User> userConverter = new UserConverter();

    UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
    User user = userConverter.convertFromDto(dtoUser);
    LOGGER.info("Entity converted from DTO: {}", user);

    var users = List.of(
            new User("Camile", "Tough", false, "124sad"),
            new User("Marti", "Luther", true, "42309fd"),
            new User("Kate", "Smith", true, "if0243")
    );
    LOGGER.info("Domain entities:");
    users.stream().map(User::toString).forEach(LOGGER::info);

    LOGGER.info("DTO entities converted from domain:");
    List<UserDto> dtoEntities = userConverter.createFromEntities(users);
    dtoEntities.stream().map(UserDto::toString).forEach(LOGGER::info);
}
```

Program output:

```
08:28:27.019 [main] INFO com.iluwatar.converter.App -- Entity converted from DTO: User[firstName=John, lastName=Doe, active=true, userId=whatever[at]wherever.com]
08:28:27.035 [main] INFO com.iluwatar.converter.App -- Domain entities:
08:28:27.035 [main] INFO com.iluwatar.converter.App -- User[firstName=Camile, lastName=Tough, active=false, userId=124sad]
08:28:27.035 [main] INFO com.iluwatar.converter.App -- User[firstName=Marti, lastName=Luther, active=true, userId=42309fd]
08:28:27.035 [main] INFO com.iluwatar.converter.App -- User[firstName=Kate, lastName=Smith, active=true, userId=if0243]
08:28:27.036 [main] INFO com.iluwatar.converter.App -- DTO entities converted from domain:
08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Camile, lastName=Tough, active=false, email=124sad]
08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Marti, lastName=Luther, active=true, email=42309fd]
08:28:27.037 [main] INFO com.iluwatar.converter.App -- UserDto[firstName=Kate, lastName=Smith, active=true, email=if0243]
```

## [When to Use the Converter Pattern in Java](https://java-design-patterns.com/patterns/converter/#when-to-use-the-converter-pattern-in-java)

Use the Converter Pattern in the following situations:

- When there are types that logically correspond with each other, and there is a need to convert between them.
- In applications that interact with external systems or services that require data in a specific format.
- For legacy systems integration where data models differ significantly from newer systems.
- When aiming to encapsulate conversion logic to promote single responsibility and cleaner code.

## [Converter Pattern Java Tutorials](https://java-design-patterns.com/patterns/converter/#converter-pattern-java-tutorials)

- [Converter Pattern in Java 8 (Boldare)](http://www.xsolve.pl/blog/converter-pattern-in-java-8/)

## [Real-World Applications of Converter Pattern in Java](https://java-design-patterns.com/patterns/converter/#real-world-applications-of-converter-pattern-in-java)

- Data Transfer Objects (DTOs) conversions in multi-layered applications.
- Adapting third-party data structures or API responses to internal models.
- ORM (Object-Relational Mapping) frameworks for mapping between database records and domain objects.
- Microservices architecture for data exchange between different services.

## [Benefits and Trade-offs of Converter Pattern](https://java-design-patterns.com/patterns/converter/#benefits-and-trade-offs-of-converter-pattern)

Benefits:

- Separation of Concerns: Encapsulates conversion logic in a single component, keeping the rest of the application unaware of the conversion details.
- Reusability: Converter components can be reused across the application or even in different applications.
- Flexibility: Makes it easy to add new conversions without impacting existing code, adhering to the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle).
- Interoperability: Facilitates communication between different systems or application layers by translating data formats.

Trade-offs:

- Overhead: Introducing converters can add complexity and potential performance overhead, especially in systems with numerous data formats.
- Duplication: There's a risk of duplicating model definitions if not carefully managed, leading to increased maintenance.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/converter/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Similar in intent to adapting interfaces, but Converter focuses on data models.
- [Facade](https://java-design-patterns.com/patterns/facade/): Provides a simplified interface to a complex system, which might involve data conversion.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Converters can use different strategies for conversion, especially when multiple formats are involved.

## [References and Credits](https://java-design-patterns.com/patterns/converter/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)

---

## [structural/curiously-recurring-template-pattern] Curiously Recurring Template
> 官方文档: https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/

StructuralCode simplificationExtensibilityGenericIdiomInstantiationPolymorphismRecursionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#also-known-as)

- CRTP
- Mixin Inheritance
- Recursive Type Bound
- Recursive Generic
- Static Polymorphism

## [Intent of Curiously Recurring Template Pattern](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#intent-of-curiously-recurring-template-pattern)

The Curiously Recurring Template Pattern (CRTP) is a powerful design pattern in Java used to achieve static polymorphism. By having a class template derive from a template instantiation of its own class, CRTP enables method overriding and compile-time polymorphic behavior, enhancing efficiency and performance in your Java applications.

## [Detailed Explanation of Curiously Recurring Template Pattern with Real-World Examples](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#detailed-explanation-of-curiously-recurring-template-pattern-with-real-world-examples)

Real-world example

> Consider a scenario where a library system manages various types of media: books, DVDs, and magazines. Each media type has specific attributes and behaviors, but they all share common functionality like borrowing and returning. By applying the Curiously Recurring Template Pattern (CRTP) in Java, you can create a base template class `MediaItem` encompassing these common methods. Each specific media type (e.g., `Book`, `DVD`, `Magazine`) would inherit from `MediaItem` using itself as a template parameter. This approach allows each media type to customize shared functionality efficiently, avoiding the overhead of virtual methods.

In plain words

> The CRTP in Java ensures that certain methods within a type can accept arguments specific to its subtypes, enabling more efficient and type-safe polymorphic behavior at compile time.

Wikipedia says

> The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument.

Flowchart

![Curiously Recurring Template Pattern flowchart](https://java-design-patterns.com/assets/img/crtp-flowchart.7b46473e.png)

## [Programmatic example of CRTP in Java](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#programmatic-example-of-crtp-in-java)

For a mixed martial arts promotion that is planning an event, ensuring that the fights are organized between athletes of the same weight class is crucial. This prevents mismatches between fighters of significantly different sizes, such as a heavyweight facing off against a bantamweight.

Let's define the generic interface `Fighter`.

```java
public interface Fighter<T> {

    void fight(T t);

}
```

The `MMAFighter` class is used to instantiate fighters distinguished by their weight class.

```java
@Slf4j
@Data
public class MmaFighter<T extends MmaFighter<T>> implements Fighter<T> {

    private final String name;
    private final String surname;
    private final String nickName;
    private final String speciality;

    @Override
    public void fight(T opponent) {
        LOGGER.info("{} is going to fight against {}", this, opponent);
    }
}
```

The followings are some subtypes of `MmaFighter`.

```java
class MmaBantamweightFighter extends MmaFighter<MmaBantamweightFighter> {

    public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) {
        super(name, surname, nickName, speciality);
    }
}

public class MmaHeavyweightFighter extends MmaFighter<MmaHeavyweightFighter> {

    public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) {
        super(name, surname, nickName, speciality);
    }
}
```

A fighter is allowed to fight an opponent of the same weight classes. If the opponent is of a different weight class, an error is raised.

```java
public static void main(String[] args) {

    MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai");
    MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo");
    fighter1.fight(fighter2);

    MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing");
    MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu");
    fighter3.fight(fighter4);
}
```

Program output:

```
08:42:34.048 [main] INFO crtp.MmaFighter -- MmaFighter(name=Joe, surname=Johnson, nickName=The Geek, speciality=Muay Thai) is going to fight against MmaFighter(name=Ed, surname=Edwards, nickName=The Problem Solver, speciality=Judo)
08:42:34.054 [main] INFO crtp.MmaFighter -- MmaFighter(name=Dave, surname=Davidson, nickName=The Bug Smasher, speciality=Kickboxing) is going to fight against MmaFighter(name=Jack, surname=Jackson, nickName=The Pragmatic, speciality=Brazilian Jiu-Jitsu)
```

## [When to Use the Curiously Recurring Template Pattern in Java](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#when-to-use-the-curiously-recurring-template-pattern-in-java)

- When you need to extend the functionality of a class through inheritance but prefer compile-time polymorphism to runtime polymorphism for efficiency reasons.
- When you want to avoid the overhead of virtual functions but still achieve polymorphic behavior.
- In template metaprogramming to provide implementations of functions or policies that can be selected at compile time.
- You have type conflicts when chaining methods in an object hierarchy.
- You want to use a parameterized class method that can accept subclasses of the class as arguments, allowing it to be applied to objects that inherit from the class.
- You want certain methods to work only with instances of the same type, such as for achieving mutual comparability.

## [Curiously Recurring Template Pattern Java Tutorials](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#curiously-recurring-template-pattern-java-tutorials)

- [Curiously Recurring Template Pattern in Java (The NuaH Blog)](https://nuah.livejournal.com/328187.html)

## [Real-World Applications of Curiously Recurring Template Pattern in Java](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#real-world-applications-of-curiously-recurring-template-pattern-in-java)

- Implementing compile-time polymorphic interfaces in template libraries.
- Enhancing code reuse in libraries where performance is critical, like in mathematical computations, embedded systems, and real-time processing applications.
- Implementation of the `Cloneable` interface in various Java libraries.

## [Benefits and Trade-offs of Curiously Recurring Template Pattern](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#benefits-and-trade-offs-of-curiously-recurring-template-pattern)

Benefits:

- Elimination of virtual function call overhead, enhancing performance.
- Safe reuse of the base class code without the risks associated with multiple inheritances.
- Greater flexibility and extensibility in compile-time polymorphism scenarios.

Trade-offs:

- Increased complexity in understanding and debugging due to the interplay of templates and inheritance.
- Can lead to code bloat because each instantiation of a template results in a new class.
- Less flexibility compared to runtime polymorphism as the behavior must be determined entirely at compile time.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Can be used in conjunction with CRTP to instantiate derived classes without knowing their specific types.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): CRTP can implement compile-time strategy selection.
- [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in structure but differs in that CRTP achieves behavior variation through compile-time polymorphism.

## [References and Credits](https://java-design-patterns.com/patterns/curiously-recurring-template-pattern/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)

---

## [structural/dao-factory] Dao Factory
> 官方文档: https://java-design-patterns.com/patterns/dao-factory/

StructuralAbstractionData accessLayer architecturePersistenceAbout 7 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/dao-factory/#also-known-as)

- DAO Factory
- Factory for Data Access Object strategy using Abstract Factory

## [Intent of Data Access Object Factory Design Pattern](https://java-design-patterns.com/patterns/dao-factory/#intent-of-data-access-object-factory-design-pattern)

The DAO Factory combines the Data Access Object and Abstract Factory patterns to seperate business logic from data access logic, while increasing flexibility when switching between different data sources.

## [Detailed Explanation of Data Access Object Factory Pattern with Real-World Examples](https://java-design-patterns.com/patterns/dao-factory/#detailed-explanation-of-data-access-object-factory-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the DAO Factory pattern is a multilingual customer service center. Imagine a bank that serves customers speaking different languages—English, French, and Spanish. When a customer calls, an automated system first detects the customer's preferred language, then routes the call to the appropriate support team that speaks that language. Each team follows the same company policies (standard procedures), but handles interactions in a language-specific way.
>
> In the same way, the DAO Factory pattern uses a factory to determine the correct set of DAO implementations based on the data source (e.g., MySQL, MongoDB). Each DAO factory returns a group of DAOs tailored to a specific data source, all conforming to the same interfaces. This allows the application to interact with any supported database in a consistent manner, without changing the business logic—just like how the customer service system handles multiple languages while following the same support protocols.

In plain words

> The DAO Factory pattern abstracts the creation of Data Access Objects (DAOs), allowing you to request a specific DAO from a central factory without worrying about its underlying implementation. This makes the code easier to maintain and flexible to change, especially when switching between databases or storage mechanisms.

Wikipedia says

> The Data Access Object (DAO) design pattern is a structural pattern that provides an abstract interface to some type of database or other persistence mechanism. By mapping application calls to the persistence layer, the DAO provides some specific data operations without exposing details of the database. The DAO Factory is an extension of this concept, responsible for generating the required DAO implementations.

Class diagram

![Data Access Object Factory class diagram](https://java-design-patterns.com/assets/img/dao-factory.4976461c.png)

## [Programmatic Example of Data Access Object Factory in Java](https://java-design-patterns.com/patterns/dao-factory/#programmatic-example-of-data-access-object-factory-in-java)

In this example, the persistence object represents a Customer.

We are considering a flexible storage strategy where the application should be able to work with three different types of data sources: an H2 in-memory relational database (RDBMS), a MongoDB (object-oriented database), and a JSON flat file (flat file storage).

```java
public enum DataSourceType {
H2,
Mongo,
FlatFile
}
```

First, we define a Customer class that will be persisted in different storage systems. The ID field is generic to maintain compatibility with both relational and object-oriented databases.

```java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Customer<T> implements Serializable {
private T id;
private String name;
}
```

Next, we define a CustomerDAO interface that outlines the standard CRUD operations on the Customer model. This interface will have three concrete implementations, each corresponding to a specific data source: H2 in-memory database, MongoDB, and JSON file.

```java
public interface CustomerDAO<T> {

  void save(Customer<T> customer);

  void update(Customer<T> customer);

  void delete(T id);

  List<Customer<T>> findAll();

  Optional<Customer<T>> findById(T id);
}
```

Here is the implementations

```java
@Slf4j
@RequiredArgsConstructor
public class H2CustomerDAO implements CustomerDAO<Long> {
private final DataSource dataSource;
private final String INSERT_CUSTOMER = "INSERT INTO customer(id, name) VALUES (?, ?)";
private final String UPDATE_CUSTOMER = "UPDATE customer SET name = ? WHERE id = ?";
private final String DELETE_CUSTOMER = "DELETE FROM customer WHERE id = ?";
private final String SELECT_CUSTOMER_BY_ID = "SELECT * FROM customer WHERE id= ?";
private final String SELECT_ALL_CUSTOMERS = "SELECT * FROM customer";
private final String CREATE_SCHEMA =
"CREATE TABLE IF NOT EXISTS customer (id BIGINT PRIMARY KEY, name VARCHAR(255))";
private final String DROP_SCHEMA = "DROP TABLE IF EXISTS customer";

  @Override
  public void save(Customer<Long> customer) {
    // Implement operation save for H2
  }

  @Override
  public void update(Customer<Long> customer) {
    // Implement operation save for H2
  }

  @Override
  public void delete(Long id) {
    // Implement operation delete for H2
  }

  @Override
  public List<Customer<Long>> findAll() {
    // Implement operation find all for H2
  }

  @Override
  public Optional<Customer<Long>> findById(Long id) {
    // Implement operation find by id for H2
  }
}
```

```java
@Slf4j
@RequiredArgsConstructor
public class MongoCustomerDAO implements CustomerDAO<ObjectId> {
private final MongoCollection<Document> customerCollection;

  // Implement CRUD operation with MongoDB data source
}
```

```java
@Slf4j
@RequiredArgsConstructor
public class FlatFileCustomerDAO implements CustomerDAO<Long> {
  private final Path filePath;
  private final Gson gson;
  Type customerListType = new TypeToken<List<Customer<Long>>>() {
  }.getType();

  // Implement CRUD operation with Flat file data source
}
```

After that, we create an abstract class DAOFactory that defines two key methods: a static method getDataSource() and an abstract method createCustomerDAO().

- The getDataSource() method is a factory selector—it returns a concrete DAOFactory instance based on the type of data source requested.

- Each subclass of DAOFactory will implement the createCustomerDAO() method to provide the corresponding CustomerDAO implementation.


```java
public abstract class DAOFactory {
  public static DAOFactory getDataSource(DataSourceType dataSourceType) {
    return switch (dataSourceType) {
      case H2 -> new H2DataSourceFactory();
      case Mongo -> new MongoDataSourceFactory();
      case FlatFile -> new FlatFileDataSourceFactory();
    };
  }

  public abstract CustomerDAO createCustomerDAO();
}
```

We then implement three specific factory classes:

H2DataSourceFactory for H2 in-memory RDBMS

```java
public class H2DataSourceFactory extends DAOFactory {
  private final String DB_URL = "jdbc:h2:~/test";
  private final String USER = "sa";
  private final String PASS = "";

  @Override
  public CustomerDAO createCustomerDAO() {
    return new H2CustomerDAO(createDataSource());
  }

  private DataSource createDataSource() {
    var dataSource = new JdbcDataSource();
    dataSource.setURL(DB_URL);
    dataSource.setUser(USER);
    dataSource.setPassword(PASS);
    return dataSource;
  }
}
```

MongoDataSourceFactory for MongoDB

```java
public class MongoDataSourceFactory extends DAOFactory {
  private final String CONN_STR = "mongodb://localhost:27017/";
  private final String DB_NAME = "dao_factory";
  private final String COLLECTION_NAME = "customer";

  @Override
  public CustomerDAO createCustomerDAO() {
    try {
      MongoClient mongoClient = MongoClients.create(CONN_STR);
      MongoDatabase database = mongoClient.getDatabase(DB_NAME);
      MongoCollection<Document> customerCollection = database.getCollection(COLLECTION_NAME);
      return new MongoCustomerDAO(customerCollection);
    } catch (RuntimeException e) {
      throw new RuntimeException("Error: " + e);
    }
  }
}
```

FlatFileDataSourceFactory for flat file storage using JSON

```java
public class FlatFileDataSourceFactory extends DAOFactory {
  private final String FILE_PATH = System.getProperty("user.home") + "/Desktop/customer.json";
  @Override
  public CustomerDAO createCustomerDAO() {
    Path filePath = Paths.get(FILE_PATH);
    Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .serializeNulls()
        .create();
    return new FlatFileCustomerDAO(filePath, gson);
  }
}
```

Finally, in the main function of client code, we will demonstrate CRUD operations on the Customer using three data source type.

```java
    // Perform CRUD H2 Database
    LOGGER.debug("H2 - Create customer");
    performCreateCustomer(customerDAO,
        List.of(customerInmemory1, customerInmemory2, customerInmemory3));
    LOGGER.debug("H2 - Update customer");
    performUpdateCustomer(customerDAO, customerUpdateInmemory);
    LOGGER.debug("H2 - Delete customer");
    performDeleteCustomer(customerDAO, 3L);
    deleteSchema(customerDAO);

    // Perform CRUD MongoDb
    daoFactory = DAOFactory.getDataSource(DataSourceType.Mongo);
    customerDAO = daoFactory.createCustomerDAO();
    LOGGER.debug("Mongo - Create customer");
    performCreateCustomer(customerDAO, List.of(customer4, customer5));
    LOGGER.debug("Mongo - Update customer");
    performUpdateCustomer(customerDAO, customerUpdateMongo);
    LOGGER.debug("Mongo - Delete customer");
    performDeleteCustomer(customerDAO, idCustomerMongo2);
    deleteSchema(customerDAO);

    // Perform CRUD Flat file
    daoFactory = DAOFactory.getDataSource(DataSourceType.FlatFile);
    customerDAO = daoFactory.createCustomerDAO();
    LOGGER.debug("Flat file - Create customer");
    performCreateCustomer(customerDAO,
        List.of(customerFlatFile1, customerFlatFile2, customerFlatFile3));
    LOGGER.debug("Flat file - Update customer");
    performUpdateCustomer(customerDAO, customerUpdateFlatFile);
    LOGGER.debug("Flat file - Delete customer");
    performDeleteCustomer(customerDAO, 3L);
    deleteSchema(customerDAO);
```

The program output

```java
17:17:24.368 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - H2 - Create customer
17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Green)
17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Red)
17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Blue)
17:17:24.514 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - H2 - Update customer
17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Yellow)
17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Red)
17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Blue)
17:17:24.573 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - H2 - Delete customer
17:17:24.632 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Yellow)
17:17:24.632 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Red)
17:17:24.747 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Mongo - Create customer
17:17:24.834 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c1, name=Masca)
17:17:24.834 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c2, name=Elliot)
17:17:24.834 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Mongo - Update customer
17:17:24.845 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c1, name=Masca)
17:17:24.845 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c2, name=Henry)
17:17:24.845 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Mongo - Delete customer
17:17:24.850 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=68173eb4c840286dbc2bc5c1, name=Masca)
17:17:24.876 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Flat file - Create customer
17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Duc)
17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Quang)
17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Nhat)
17:17:24.895 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Flat file - Update customer
17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Thanh)
17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Quang)
17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=3, name=Nhat)
17:17:24.897 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Flat file - Delete customer
17:17:24.898 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=1, name=Thanh)
17:17:24.898 [main] DEBUG c.i.d.App com.iluwatar.daofactory.App - Customer(id=2, name=Quang)
```

## [When to Use the Data Access Object Factory Pattern in Java](https://java-design-patterns.com/patterns/dao-factory/#when-to-use-the-data-access-object-factory-pattern-in-java)

Use the DAO Factory Pattern when:

- The application needs to support multiple types of storage (RDBMS, NoSQL, file system, etc.) with minimal changes to business logic.
- You want to abstract and isolate persistence logic from the core application logic.
- You aim to make your data access layer pluggable and easy to extend with new storage technologies.
- You want to enable easier unit testing and dependency injection by providing mock implementations of DAOs.
- Runtime configuration (e.g., via environment variables or application settings) determines which data source to use.

## [Data Access Object Factory Pattern Java Tutorials](https://java-design-patterns.com/patterns/dao-factory/#data-access-object-factory-pattern-java-tutorials)

- [Core J2EE Patterns - Data Access Object (Oracle)](https://www.oracle.com/java/technologies/dataaccessobject.html)
- [DAO Factories: Java Design Patterns (Youtube)](https://www.youtube.com/watch?v=5HGe9s9qM-o)
- [Java Design Patterns and Architecture (CaveofProgramming)](https://caveofprogramming.teachable.com/courses/2084/lectures/39549)

## [Real-World Applications of Data Access Object Factory Pattern in Java](https://java-design-patterns.com/patterns/dao-factory/#real-world-applications-of-data-access-object-factory-pattern-in-java)

- Enterprise Java Applications: Where switching between test, dev, and production databases is common (e.g., MySQL ↔ MongoDB ↔ In-Memory).
- Spring Data JPA & Repository Abstraction: Though Spring provides its own abstraction, the concept is similar to DAO factory for modular and pluggable persistence.
- Microservices with Varying Storage Backends: Different microservices might store data in SQL, NoSQL, or even flat files; using a DAO Factory per service ensures consistency.
- Data Integration Tools: Tools that support importing/exporting from various formats (CSV, JSON, databases) often use DAO factories behind the scenes.
- Framework-Level Implementations: Custom internal frameworks where persistence layers need to support multiple database types.

## [Benefits and Trade-offs of Data Access Object Factory Pattern](https://java-design-patterns.com/patterns/dao-factory/#benefits-and-trade-offs-of-data-access-object-factory-pattern)

Benefits:

- Abstraction of Data Source Logic: Client code interacts only with DAO interfaces, completely decoupled from how and where the data is stored.
- Flexibility in Persistence Strategy: Easily switch between databases (e.g., H2, MongoDB, flat files) by changing the factory configuration.
- Improved Maintainability: Storage logic for each data source is encapsulated within its own DAO implementation and factory, making it easier to update or extend.
- Code Reusability: Common data access logic (e.g., CRUD operations) can be reused across different implementations and projects.
- Testability: DAOs and factories can be mocked or stubbed easily, which supports unit testing and dependency injection.

Trade-offs:

- Increased Complexity: Introducing abstract DAOs and multiple factory classes adds structural complexity to the codebase.
- Boilerplate Code: Requires defining many interfaces and implementations, even for simple data access needs.
- Less Transparent Behavior: Since clients access DAOs indirectly via factories, understanding the concrete data source behavior may require deeper inspection.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/dao-factory/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): DAO Factory is a concrete application of the Factory Pattern, used to create DAO objects in a flexible way.
- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): When supporting multiple data sources (e.g., MySQLDAO, OracleDAO), DAO Factory can act as an Abstract Factory.
- [Data Access Object (DAO)](https://java-design-patterns.com/patterns/data-access-object/): The core pattern managed by DAO Factory, it separates data access logic from business logic.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): DAO Factory is often implemented as a Singleton to ensure only one instance manages DAO creation.
- [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Can be used alongside DAO Factory to retrieve DAO services efficiently.
- [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): In frameworks like Spring, DAOs are typically injected into the service layer instead of being retrieved from a factory.

## [References and Credits](https://java-design-patterns.com/patterns/dao-factory/#references-and-credits)

- [DAO Factory - J2EE Design Patterns Book](https://www.oreilly.com/library/view/j2ee-design-patterns/0596004273/re15.html)
- [DAO Factory patterns with Hibernate](http://www.giuseppeurso.eu/en/dao-factory-patterns-with-hibernate/)
- [Design Patterns - Java Means DURGA SOFT](https://www.scribd.com/document/407219980/2-DAO-Factory-Design-Pattern)
- [Generic DAO pattern - Hibernate](https://in.relation.to/2005/09/09/generic-dao-pattern-with-jdk-50/)

---

## [structural/data-access-object] Data Access Object
> 官方文档: https://java-design-patterns.com/patterns/data-access-object/

StructuralAbstractionData accessData processingDecouplingLayered architecturePersistenceAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/data-access-object/#also-known-as)

- Data Access Layer
- DAO

## [Intent of Data Access Object Design Pattern](https://java-design-patterns.com/patterns/data-access-object/#intent-of-data-access-object-design-pattern)

The Data Access Object (DAO) design pattern aims to separate the application's business logic from the persistence layer, typically a database or any other storage mechanism. By using DAOs, the application can access and manipulate data without being dependent on the specific database implementation details.

## [Detailed Explanation of Data Access Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/data-access-object/#detailed-explanation-of-data-access-object-pattern-with-real-world-examples)

Real-world example

> Imagine a library system where the main application manages book loans, user accounts, and inventory. The Data Access Object (DAO) pattern in this context would be used to separate the database operations (such as fetching book details, updating user records, and checking inventory) from the business logic of managing loans and accounts. For instance, there would be a `BookDAO` class responsible for all database interactions related to books, such as retrieving a book by its ISBN or updating its availability status. This abstraction allows the library system's main application code to focus on business rules and workflows, while the `BookDAO` handles the complex SQL queries and data management. This separation makes the system easier to maintain and test, as changes to the data source or business logic can be managed independently.

In plain words

> DAO is an interface we provide over the base persistence mechanism.

Wikipedia says

> In computer software, a data access object (DAO) is a pattern that provides an abstract interface to some type of database or other persistence mechanism.

Sequence diagram

![Data Access Object sequence diagram](https://java-design-patterns.com/assets/img/dao-sequence-diagram.7aa889df.png)

## [Programmatic Example of DAO Pattern in Java](https://java-design-patterns.com/patterns/data-access-object/#programmatic-example-of-dao-pattern-in-java)

There's a set of customers that need to be persisted to database. Additionally, we need the whole set of CRUD (create/read/update/delete) operations, so we can operate on customers easily.

Walking through our customers example, here's the basic `Customer` entity.

```java
@Setter
@Getter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@AllArgsConstructor
public class Customer {

    @EqualsAndHashCode.Include
    private int id;
    private String firstName;
    private String lastName;
}
```

Here's the `CustomerDao` interface and two different implementations for it. `InMemoryCustomerDao` keeps a simple map of customers in memory while `DBCustomerDao` is the real RDBMS implementation.

```java
public interface CustomerDao {

    Stream<Customer> getAll() throws Exception;

    Optional<Customer> getById(int id) throws Exception;

    boolean add(Customer customer) throws Exception;

    boolean update(Customer customer) throws Exception;

    boolean delete(Customer customer) throws Exception;
}

public class InMemoryCustomerDao implements CustomerDao {

    private final Map<Integer, Customer> idToCustomer = new HashMap<>();

    // implement the interface using the map
}

@Slf4j
@RequiredArgsConstructor
public class DbCustomerDao implements CustomerDao {

  private final DataSource dataSource;

  // implement the interface using the data source
}
```

Finally, here's how we use our DAO to manage customers.

```java

@Slf4j
public class App {
    private static final String DB_URL = "jdbc:h2:mem:dao;DB_CLOSE_DELAY=-1";
    private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): ";

    public static void main(final String[] args) throws Exception {
        final var inMemoryDao = new InMemoryCustomerDao();
        performOperationsUsing(inMemoryDao);

        final var dataSource = createDataSource();
        createSchema(dataSource);
        final var dbDao = new DbCustomerDao(dataSource);
        performOperationsUsing(dbDao);
        deleteSchema(dataSource);
    }

    private static void deleteSchema(DataSource dataSource) throws SQLException {
        try (var connection = dataSource.getConnection();
             var statement = connection.createStatement()) {
            statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL);
        }
    }

    private static void createSchema(DataSource dataSource) throws SQLException {
        try (var connection = dataSource.getConnection();
             var statement = connection.createStatement()) {
            statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL);
        }
    }

    private static DataSource createDataSource() {
        var dataSource = new JdbcDataSource();
        dataSource.setURL(DB_URL);
        return dataSource;
    }

    private static void performOperationsUsing(final CustomerDao customerDao) throws Exception {
        addCustomers(customerDao);
        LOGGER.info(ALL_CUSTOMERS);
        try (var customerStream = customerDao.getAll()) {
            customerStream.forEach(customer -> LOGGER.info(customer.toString()));
        }
        LOGGER.info("customerDao.getCustomerById(2): " + customerDao.getById(2));
        final var customer = new Customer(4, "Dan", "Danson");
        customerDao.add(customer);
        LOGGER.info(ALL_CUSTOMERS + customerDao.getAll());
        customer.setFirstName("Daniel");
        customer.setLastName("Danielson");
        customerDao.update(customer);
        LOGGER.info(ALL_CUSTOMERS);
        try (var customerStream = customerDao.getAll()) {
            customerStream.forEach(cust -> LOGGER.info(cust.toString()));
        }
        customerDao.delete(customer);
        LOGGER.info(ALL_CUSTOMERS + customerDao.getAll());
    }

    private static void addCustomers(CustomerDao customerDao) throws Exception {
        for (var customer : generateSampleCustomers()) {
            customerDao.add(customer);
        }
    }

    public static List<Customer> generateSampleCustomers() {
        final var customer1 = new Customer(1, "Adam", "Adamson");
        final var customer2 = new Customer(2, "Bob", "Bobson");
        final var customer3 = new Customer(3, "Carl", "Carlson");
        return List.of(customer1, customer2, customer3);
    }
}
```

The program output:

```
10:02:09.788 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers():
10:02:09.793 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson)
10:02:09.793 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson)
10:02:09.793 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson)
10:02:09.794 [main] INFO com.iluwatar.dao.App -- customerDao.getCustomerById(2): Optional[Customer(id=2, firstName=Bob, lastName=Bobson)]
10:02:09.794 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@4c3e4790
10:02:09.794 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers():
10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson)
10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson)
10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson)
10:02:09.795 [main] INFO com.iluwatar.dao.App -- Customer(id=4, firstName=Daniel, lastName=Danielson)
10:02:09.795 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@5679c6c6
10:02:09.894 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers():
10:02:09.895 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson)
10:02:09.895 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson)
10:02:09.895 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson)
10:02:09.895 [main] INFO com.iluwatar.dao.App -- customerDao.getCustomerById(2): Optional[Customer(id=2, firstName=Bob, lastName=Bobson)]
10:02:09.896 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@23282c25
10:02:09.897 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers():
10:02:09.897 [main] INFO com.iluwatar.dao.App -- Customer(id=1, firstName=Adam, lastName=Adamson)
10:02:09.897 [main] INFO com.iluwatar.dao.App -- Customer(id=2, firstName=Bob, lastName=Bobson)
10:02:09.898 [main] INFO com.iluwatar.dao.App -- Customer(id=3, firstName=Carl, lastName=Carlson)
10:02:09.898 [main] INFO com.iluwatar.dao.App -- Customer(id=4, firstName=Daniel, lastName=Danielson)
10:02:09.898 [main] INFO com.iluwatar.dao.App -- customerDao.getAllCustomers(): java.util.stream.ReferencePipeline$Head@f2f2cc1
```

## [When to Use the Data Access Object Pattern in Java](https://java-design-patterns.com/patterns/data-access-object/#when-to-use-the-data-access-object-pattern-in-java)

Use the Data Access Object in any of the following situations:

- There is a need to abstract and encapsulate all access to the data source.
- The application needs to support multiple types of databases or storage mechanisms without significant code changes.
- You want to keep the database access clean and simple, and separate from business logic.

## [Data Access Object Pattern Java Tutorials](https://java-design-patterns.com/patterns/data-access-object/#data-access-object-pattern-java-tutorials)

- [The DAO Pattern in Java(Baeldung)](https://www.baeldung.com/java-dao-pattern)
- [Data Access Object Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm)

## [Real-World Applications of DAO Pattern in Java](https://java-design-patterns.com/patterns/data-access-object/#real-world-applications-of-dao-pattern-in-java)

- Enterprise applications that require database interaction.
- Applications requiring data access to be adaptable to multiple storage types (relational databases, XML files, flat files, etc.).
- Frameworks providing generic data access functionalities.

## [Benefits and Trade-offs of Data Access Object Pattern](https://java-design-patterns.com/patterns/data-access-object/#benefits-and-trade-offs-of-data-access-object-pattern)

Benefits:

- Decoupling: Separates the data access logic from the business logic, enhancing modularity and clarity.
- Reusability: DAOs can be reused across different parts of the application or even in different projects.
- Testability: Simplifies testing by allowing business logic to be tested separately from the data access logic.
- Flexibility: Makes it easier to switch underlying storage mechanisms with minimal impact on the application code.

Trade-offs:

- Layer Complexity: Introduces additional layers to the application, which can increase complexity and development time.
- Overhead: For simple applications, the DAO pattern might introduce more overhead than necessary.
- Learning Curve: Developers might need time to understand and implement the pattern effectively, especially in complex projects.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/data-access-object/#related-java-design-patterns)

- [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Helps in abstracting the creation of DAOs, especially when supporting multiple databases or storage mechanisms.
- [Factory](https://java-design-patterns.com/patterns/factory/): Can be used to instantiate DAOs dynamically, providing flexibility in the choice of implementation.
- [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often used in conjunction with the DAO pattern to define application's boundaries and its set of available operations.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Might be employed to change the data access strategy at runtime, depending on the context.

## [References and Credits](https://java-design-patterns.com/patterns/data-access-object/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/49u3r91)
- [Expert One-on-One J2EE Design and Development](https://amzn.to/3vK3pfq)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3U5cxEI)
- [Professional Java Development with the Spring Framework](https://amzn.to/49tANF0)

---

## [structural/data-transfer-object] Data Transfer Object
> 官方文档: https://java-design-patterns.com/patterns/data-transfer-object/

StructuralClient-serverData transferDecouplingLayered architectureOptimizationAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/data-transfer-object/#also-known-as)

- Transfer Object
- Value Object

## [Intent of Data Transfer Object Design Pattern](https://java-design-patterns.com/patterns/data-transfer-object/#intent-of-data-transfer-object-design-pattern)

The Data Transfer Object (DTO) pattern is used to transfer data between software application subsystems or layers, particularly in the context of network calls or database retrieval in Java applications. It reduces the number of method calls by aggregating the data in a single transfer.

## [Detailed Explanation of Data Transfer Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/data-transfer-object/#detailed-explanation-of-data-transfer-object-pattern-with-real-world-examples)

Real-world example

> Imagine a large company with several departments (e.g., Sales, HR, and IT) needing to share employee information efficiently. Instead of each department querying and retrieving data like name, address, and role individually, they use a courier service to bundle this data into a single package. This package, representing a Data Transfer Object (DTO), allows the departments to easily receive and process comprehensive employee data without making multiple requests. This simplifies data handling, reduces communication overhead, and ensures a standardized format across the company.

In plain words

> Using DTO, relevant information can be fetched with a single backend query.

Wikipedia says

> In the field of programming a data transfer object (DTO) is an object that carries data between processes. The motivation for its use is that communication between processes is usually done resorting to remote interfaces (e.g. web services), where each call is an expensive operation. Because the majority of the cost of each call is related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been transferred by the several calls, but that is served by one call only.

Sequence diagram

![Data Transfer Object sequence diagram](https://java-design-patterns.com/assets/img/dto-sequence-diagram.2e0b0e02.png)

## [Programmatic Example of DTO Pattern in Java](https://java-design-patterns.com/patterns/data-transfer-object/#programmatic-example-of-dto-pattern-in-java)

Let's first introduce our simple `CustomerDTO` record.

```java
public record CustomerDto(String id, String firstName, String lastName) {}
```

`CustomerResource` record acts as the server for customer information.

```java
public record CustomerResource(List<CustomerDto> customers) {

    public void save(CustomerDto customer) {
        customers.add(customer);
    }

    public void delete(String customerId) {
        customers.removeIf(customer -> customer.id().equals(customerId));
    }
}
```

Now fetching customer information is easy since we have the DTOs. The 2nd example uses `ProductDTO` similarly.

```java
public class App {

  public static void main(String[] args) {

    // Example 1: Customer DTO
    var customerOne = new CustomerDto("1", "Kelly", "Brown");
    var customerTwo = new CustomerDto("2", "Alfonso", "Bass");
    var customers = new ArrayList<>(List.of(customerOne, customerTwo));

    var customerResource = new CustomerResource(customers);

    LOGGER.info("All customers:");
    var allCustomers = customerResource.customers();
    printCustomerDetails(allCustomers);

    LOGGER.info("----------------------------------------------------------");

    LOGGER.info("Deleting customer with id {1}");
    customerResource.delete(customerOne.id());
    allCustomers = customerResource.customers();
    printCustomerDetails(allCustomers);

    LOGGER.info("----------------------------------------------------------");

    LOGGER.info("Adding customer three}");
    var customerThree = new CustomerDto("3", "Lynda", "Blair");
    customerResource.save(customerThree);
    allCustomers = customerResource.customers();
    printCustomerDetails(allCustomers);

    // Example 2: Product DTO

    Product tv = Product.builder().id(1L).name("TV").supplier("Sony").price(1000D).cost(1090D).build();
    Product microwave =
        Product.builder()
            .id(2L)
            .name("microwave")
            .supplier("Delonghi")
            .price(1000D)
            .cost(1090D).build();
    Product refrigerator =
        Product.builder()
            .id(3L)
            .name("refrigerator")
            .supplier("Botsch")
            .price(1000D)
            .cost(1090D).build();
    Product airConditioner =
        Product.builder()
            .id(4L)
            .name("airConditioner")
            .supplier("LG")
            .price(1000D)
            .cost(1090D).build();
    List<Product> products =
        new ArrayList<>(Arrays.asList(tv, microwave, refrigerator, airConditioner));
    ProductResource productResource = new ProductResource(products);

    LOGGER.info(
        "####### List of products including sensitive data just for admins: \n {}",
        Arrays.toString(productResource.getAllProductsForAdmin().toArray()));
    LOGGER.info(
        "####### List of products for customers: \n {}",
        Arrays.toString(productResource.getAllProductsForCustomer().toArray()));

    LOGGER.info("####### Going to save Sony PS5 ...");
    ProductDto.Request.Create createProductRequestDto =
        new ProductDto.Request.Create()
            .setName("PS5")
            .setCost(1000D)
            .setPrice(1220D)
            .setSupplier("Sony");
    productResource.save(createProductRequestDto);
    LOGGER.info(
        "####### List of products after adding PS5: {}",
        Arrays.toString(productResource.products().toArray()));
  }

  private static void printCustomerDetails(List<CustomerDto> allCustomers) {
    allCustomers.forEach(customer -> LOGGER.info(customer.firstName()));
  }
}
```

The console output:

```
11:10:51.838 [main] INFO com.iluwatar.datatransfer.App -- All customers:
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Kelly
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- ----------------------------------------------------------
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Deleting customer with id {1}
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- ----------------------------------------------------------
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Adding customer three}
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Alfonso
11:10:51.840 [main] INFO com.iluwatar.datatransfer.App -- Lynda
11:10:51.848 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products including sensitive data just for admins:
 [Private{id=1, name='TV', price=1000.0, cost=1090.0}, Private{id=2, name='microwave', price=1000.0, cost=1090.0}, Private{id=3, name='refrigerator', price=1000.0, cost=1090.0}, Private{id=4, name='airConditioner', price=1000.0, cost=1090.0}]
11:10:51.852 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products for customers:
 [Public{id=1, name='TV', price=1000.0}, Public{id=2, name='microwave', price=1000.0}, Public{id=3, name='refrigerator', price=1000.0}, Public{id=4, name='airConditioner', price=1000.0}]
11:10:51.852 [main] INFO com.iluwatar.datatransfer.App -- ####### Going to save Sony PS5 ...
11:10:51.856 [main] INFO com.iluwatar.datatransfer.App -- ####### List of products after adding PS5: [Product{id=1, name='TV', price=1000.0, cost=1090.0, supplier='Sony'}, Product{id=2, name='microwave', price=1000.0, cost=1090.0, supplier='Delonghi'}, Product{id=3, name='refrigerator', price=1000.0, cost=1090.0, supplier='Botsch'}, Product{id=4, name='airConditioner', price=1000.0, cost=1090.0, supplier='LG'}, Product{id=5, name='PS5', price=1220.0, cost=1000.0, supplier='Sony'}]
```

## [When to Use the Data Transfer Object Pattern in Java](https://java-design-patterns.com/patterns/data-transfer-object/#when-to-use-the-data-transfer-object-pattern-in-java)

Use the Data Transfer Object pattern when:

- When you need to optimize network traffic by reducing the number of calls, especially in a client-server architecture.
- In scenarios where batch processing of data is preferred over individual processing.
- When working with remote interfaces, to encapsulate the data transfer in a serializable object that can be easily transmitted.

## [Data Transfer Object Pattern Java Tutorials](https://java-design-patterns.com/patterns/data-transfer-object/#data-transfer-object-pattern-java-tutorials)

- [Data Transfer Object Pattern in Java - Implementation and Mapping (StackAbuse)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/)
- [Design Pattern - Transfer Object Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/transfer_object_pattern.htm)
- [The DTO Pattern (Baeldung)](https://www.baeldung.com/java-dto-pattern)

## [Real-World Applications of DTO Pattern in Java](https://java-design-patterns.com/patterns/data-transfer-object/#real-world-applications-of-dto-pattern-in-java)

- Remote Method Invocation (RMI) in Java, where DTOs are used to pass data across network.
- Enterprise JavaBeans (EJB), particularly when data needs to be transferred from EJBs to clients.
- Various web service frameworks where DTOs encapsulate request and response data.

## [Benefits and Trade-offs of Data Transfer Object Pattern](https://java-design-patterns.com/patterns/data-transfer-object/#benefits-and-trade-offs-of-data-transfer-object-pattern)

Benefits:

- Reduces network calls, thereby improving application performance.
- Decouples the client from the server, leading to more modular and maintainable code.
- Simplifies data transmission over the network by aggregating data into single objects.

Trade-offs:

- Introduces additional classes into the application, which may increase complexity.
- Can lead to redundant data structures that mirror domain models, potentially causing synchronization issues.
- May encourage design that leads to an anemic domain model, where business logic is separated from data.

## [Related Patterns](https://java-design-patterns.com/patterns/data-transfer-object/#related-patterns)

- [Composite Entity](https://java-design-patterns.com/patterns/composite-entity/): DTOs may be used to represent composite entities, particularly in persistence mechanisms.
- [Facade](https://java-design-patterns.com/patterns/facade/): Similar to DTO, a Facade may aggregate multiple calls into one, improving efficiency.
- [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often involves using DTOs to transfer data across the boundary between the service layer and its clients.

## [References and Credits](https://java-design-patterns.com/patterns/data-transfer-object/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cKndQp)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Data Transfer Object (Microsoft)](https://msdn.microsoft.com/en-us/library/ff649585.aspx)

---

## [structural/decorator] Decorator 装饰器
> 官方文档: https://java-design-patterns.com/patterns/decorator/

StructuralEnhancementExtensibilityGang of FourObject compositionWrappingAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/decorator/#also-known-as)

- Smart Proxy
- Wrapper

## [Intent of Decorator Design Pattern](https://java-design-patterns.com/patterns/decorator/#intent-of-decorator-design-pattern)

The Decorator pattern allows for the dynamic addition of responsibilities to objects without modifying their existing code. It achieves this by providing a way to "wrap" objects within objects of similar interface, enhancing Java design patterns flexibility.

## [Detailed Explanation of Decorator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/decorator/#detailed-explanation-of-decorator-pattern-with-real-world-examples)

Real-world example

> Imagine a coffee shop where you can customize your coffee order. You start with a basic coffee, and you can add different ingredients like milk, sugar, whipped cream, and so on. Each addition is like a decorator in the Decorator design pattern. The base coffee object can be decorated with additional functionality (flavors, toppings) dynamically. For example, you can start with a plain coffee object, then wrap it with a milk decorator, followed by a sugar decorator, and finally a whipped cream decorator. Each decorator adds new features or modifies the behavior of the coffee object, similar to how the Decorator pattern works in software design.

In plain words

> Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.

Wikipedia says

> In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified.

Sequence diagram

![Decorator sequence diagram](https://java-design-patterns.com/assets/img/decorator-sequence-diagram.dd3d2eef.png)

## [Programmatic Example of Decorator Pattern in Java](https://java-design-patterns.com/patterns/decorator/#programmatic-example-of-decorator-pattern-in-java)

There is an angry troll living in the nearby hills. Usually, it goes bare-handed, but sometimes it has a weapon. To arm the troll it's not necessary to create a new troll but to decorate it dynamically with a suitable weapon.

First, we have a `SimpleTroll` implementing the `Troll` interface:

```java
public interface Troll {
    void attack();

    int getAttackPower();

    void fleeBattle();
}

@Slf4j
public class SimpleTroll implements Troll {

    @Override
    public void attack() {
        LOGGER.info("The troll tries to grab you!");
    }

    @Override
    public int getAttackPower() {
        return 10;
    }

    @Override
    public void fleeBattle() {
        LOGGER.info("The troll shrieks in horror and runs away!");
    }
}
```

Next, we want to add a club for the troll. We can do it dynamically by using a decorator:

```java
@Slf4j
@RequiredArgsConstructor
public class ClubbedTroll implements Troll {

    private final Troll decorated;

    @Override
    public void attack() {
        decorated.attack();
        LOGGER.info("The troll swings at you with a club!");
    }

    @Override
    public int getAttackPower() {
        return decorated.getAttackPower() + 10;
    }

    @Override
    public void fleeBattle() {
        decorated.fleeBattle();
    }
}
```

Here's the troll in action:

```java
  public static void main(String[] args) {

    // simple troll
    LOGGER.info("A simple looking troll approaches.");
    var troll = new SimpleTroll();
    troll.attack();
    troll.fleeBattle();
    LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower());

    // change the behavior of the simple troll by adding a decorator
    LOGGER.info("A troll with huge club surprises you.");
    var clubbedTroll = new ClubbedTroll(troll);
    clubbedTroll.attack();
    clubbedTroll.fleeBattle();
    LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower());
}
```

Program output:

```
11:34:18.098 [main] INFO com.iluwatar.decorator.App -- A simple looking troll approaches.
11:34:18.100 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll tries to grab you!
11:34:18.100 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll shrieks in horror and runs away!
11:34:18.100 [main] INFO com.iluwatar.decorator.App -- Simple troll power: 10.

11:34:18.100 [main] INFO com.iluwatar.decorator.App -- A troll with huge club surprises you.
11:34:18.101 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll tries to grab you!
11:34:18.101 [main] INFO com.iluwatar.decorator.ClubbedTroll -- The troll swings at you with a club!
11:34:18.101 [main] INFO com.iluwatar.decorator.SimpleTroll -- The troll shrieks in horror and runs away!
11:34:18.101 [main] INFO com.iluwatar.decorator.App -- Clubbed troll power: 20.
```

## [When to Use the Decorator Pattern in Java](https://java-design-patterns.com/patterns/decorator/#when-to-use-the-decorator-pattern-in-java)

Decorator is used to:

- Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects, a key feature of Java design patterns.
- For responsibilities that can be withdrawn.
- When extending a class is impractical due to the proliferation of subclasses that could result.
- For when a class definition might be hidden or otherwise unavailable for subclassing.

## [Decorator Pattern Java Tutorials](https://java-design-patterns.com/patterns/decorator/#decorator-pattern-java-tutorials)

- [Decorator Design Pattern in Java Example (DigitalOcean)](https://www.digitalocean.com/community/tutorials/decorator-design-pattern-in-java-example)

## [Real-World Applications of Decorator Pattern in Java](https://java-design-patterns.com/patterns/decorator/#real-world-applications-of-decorator-pattern-in-java)

- GUI toolkits often use decorators to dynamically add behaviors like scrolling, borders, or layout management to components.
- The [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html), [java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html) classes in Java are well-known examples utilizing the Decorator pattern.
- [java.util.Collections#synchronizedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-)
- [java.util.Collections#unmodifiableXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableCollection-java.util.Collection-)
- [java.util.Collections#checkedXXX()](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#checkedCollection-java.util.Collection-java.lang.Class-)

## [Benefits and Trade-offs of Decorator Pattern](https://java-design-patterns.com/patterns/decorator/#benefits-and-trade-offs-of-decorator-pattern)

Benefits:

- Greater flexibility than static inheritance.
- Avoids feature-laden classes high up in the hierarchy, showcasing the power of Java design patterns.
- A decorator and its component aren't identical.
- Responsibilities can be added or removed at runtime.

Trade-offs:

- A decorator and its component aren't identical, so tests for object type will fail.
- Decorators can lead to a system with lots of small objects that look alike to the programmer, making the desired configuration hard to achieve.
- Overuse can complicate the code structure due to the introduction of numerous small classes.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/decorator/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): A decorator changes an object's responsibilities, while an adapter changes an object's interface.
- [Composite](https://java-design-patterns.com/patterns/composite/): Decorators can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities—it isn't intended for object aggregation.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Decorator lets you change the skin of an object, while Strategy lets you change the guts.

## [References and Credits](https://java-design-patterns.com/patterns/decorator/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Functional Programming in Java](https://amzn.to/3JUIc5Q)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/4aKFTgS)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [structural/domain-model] Domain Model
> 官方文档: https://java-design-patterns.com/patterns/domain-model/

StructuralAbstractionBusinessData processingDomainEncapsulationLayered architecturePersistencePolymorphismAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/domain-model/#also-known-as)

- Conceptual Model
- Domain Object Model

## [Intent of Domain Model Design Pattern](https://java-design-patterns.com/patterns/domain-model/#intent-of-domain-model-design-pattern)

The Domain Model pattern aims to create a conceptual model in your software that matches the real-world system it's designed to represent. It involves using rich domain objects that encapsulate both data and behavior relevant to the application domain, ensuring business logic is centralized.

## [Detailed Explanation of Domain Model Pattern with Real-World Examples](https://java-design-patterns.com/patterns/domain-model/#detailed-explanation-of-domain-model-pattern-with-real-world-examples)

Real-world example

> Consider an online bookstore system that uses the Domain Model design pattern. In this system, various domain objects such as `Book`, `Author`, `Customer`, and `Order` encapsulate the core business logic and rules. For instance, the `Book` object contains attributes like title, author, price, and stock quantity, along with methods to manage these attributes. The `Order` object manages order details, calculates the total price, and verifies stock availability. This approach ensures that the business logic is centralized within the domain objects, making the system more modular, easier to maintain, and scalable as new features are added.

In plain words

> The Domain Model is an object model of the domain that incorporates both behavior and data.

Mind map

![Domain Model mind map](https://java-design-patterns.com/assets/img/domain-model-mind-map.8a4687bf.png)

## [Programmatic Example of Domain Model Pattern in Java](https://java-design-patterns.com/patterns/domain-model/#programmatic-example-of-domain-model-pattern-in-java)

Let's assume that we need to build an e-commerce web application. While analyzing requirements you will notice that there are few nouns you talk about repeatedly. It’s your Customer, and a Product the customer looks for. These two are your domain-specific classes and each of that classes will include some business logic specific to its domain.

In the example of the e-commerce app, we need to deal with the domain logic of customers who want to buy products and return them if they want. We can use the domain model pattern and create classes `Customer` and `Product` where every single instance of that class incorporates both behavior and data and represents only one record in the underlying table.

```java
public class Customer {
    // Customer properties and methods
}

public class Product {
    // Product properties and methods
}
```

Data Access Objects (DAOs): These objects provide an abstract interface to the database. They are used to retrieve domain entities and save changes back to the database. In the provided code, `CustomerDaoImpl` and `ProductDaoImpl` are the DAOs.

```java
public class CustomerDaoImpl implements CustomerDao {
    // Implementation of the methods defined in the CustomerDao interface
}

public class ProductDaoImpl implements ProductDao {
    // Implementation of the methods defined in the ProductDao interface
}
```

Domain Logic: This is encapsulated within the domain entities. For example, the `Customer` class has methods like `buyProduct` and `returnProduct` which represent the actions a customer can perform.

```java
public class Customer {

    // Other properties and methods...

    public void buyProduct(Product product) {
        // Implementation of buying a product
    }

    public void returnProduct(Product product) {
        // Implementation of returning a product
    }
}
```

Application: The `App` class uses the domain entities and their methods to implement the business logic of the application.

```java
public class App {

    public static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";

    public static final String CREATE_SCHEMA_SQL =
            "CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);"
                    + "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);"
                    + "CREATE TABLE PURCHASES ("
                    + "product_name varchar references PRODUCTS(name),"
                    + "customer_name varchar references CUSTOMERS(name));";

    public static final String DELETE_SCHEMA_SQL =
            "DROP TABLE PURCHASES IF EXISTS;"
                    + "DROP TABLE CUSTOMERS IF EXISTS;"
                    + "DROP TABLE PRODUCTS IF EXISTS;";

    public static void main(String[] args) throws Exception {

        // Create data source and create the customers, products and purchases tables
        final var dataSource = createDataSource();
        deleteSchema(dataSource);
        createSchema(dataSource);

        // create customer
        var customerDao = new CustomerDaoImpl(dataSource);

        var tom =
                Customer.builder()
                        .name("Tom")
                        .money(Money.of(USD, 30))
                        .customerDao(customerDao)
                        .build();

        tom.save();

        // create products
        var productDao = new ProductDaoImpl(dataSource);

        var eggs =
                Product.builder()
                        .name("Eggs")
                        .price(Money.of(USD, 10.0))
                        .expirationDate(LocalDate.now().plusDays(7))
                        .productDao(productDao)
                        .build();

        var butter =
                Product.builder()
                        .name("Butter")
                        .price(Money.of(USD, 20.00))
                        .expirationDate(LocalDate.now().plusDays(9))
                        .productDao(productDao)
                        .build();

        var cheese =
                Product.builder()
                        .name("Cheese")
                        .price(Money.of(USD, 25.0))
                        .expirationDate(LocalDate.now().plusDays(2))
                        .productDao(productDao)
                        .build();

        eggs.save();
        butter.save();
        cheese.save();

        // show money balance of customer after each purchase
        tom.showBalance();
        tom.showPurchases();

        // buy eggs
        tom.buyProduct(eggs);
        tom.showBalance();

        // buy butter
        tom.buyProduct(butter);
        tom.showBalance();

        // trying to buy cheese, but receive a refusal
        // because he didn't have enough money
        tom.buyProduct(cheese);
        tom.showBalance();

        // return butter and get money back
        tom.returnProduct(butter);
        tom.showBalance();

        // Tom can buy cheese now because he has enough money
        // and there is a discount on cheese because it expires in 2 days
        tom.buyProduct(cheese);

        tom.save();

        // show money balance and purchases after shopping
        tom.showBalance();
        tom.showPurchases();
    }

    private static DataSource createDataSource() {
        var dataSource = new JdbcDataSource();
        dataSource.setUrl(H2_DB_URL);
        return dataSource;
    }

    private static void deleteSchema(DataSource dataSource) throws SQLException {
        try (var connection = dataSource.getConnection();
             var statement = connection.createStatement()) {
            statement.execute(DELETE_SCHEMA_SQL);
        }
    }

    private static void createSchema(DataSource dataSource) throws SQLException {
        try (var connection = dataSource.getConnection();
             var statement = connection.createStatement()) {
            statement.execute(CREATE_SCHEMA_SQL);
        }
    }
}
```

The program output:

```java
12:17:23.834 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 30.00
12:17:23.836 [main] INFO com.iluwatar.domainmodel.Customer -- Tom didn't bought anything
12:17:23.841 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Eggs($10,00)...
12:17:23.842 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought Eggs!
12:17:23.842 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 20.00
12:17:23.842 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Butter($20,00)...
12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought Butter!
12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 0.00
12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Cheese($20,00)...
12:17:23.843 [main] ERROR com.iluwatar.domainmodel.Customer -- Not enough money!
12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 0.00
12:17:23.843 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to return Butter($20,00)...
12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom returned Butter!
12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 20.00
12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom want to buy Cheese($20,00)...
12:17:23.844 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought Cheese!
12:17:23.846 [main] INFO com.iluwatar.domainmodel.Customer -- Tom balance: USD 0.00
12:17:23.846 [main] INFO com.iluwatar.domainmodel.Customer -- Tom bought: Eggs - $10.00, Cheese - $20.00
```

## [When to Use the Domain Model Pattern in Java](https://java-design-patterns.com/patterns/domain-model/#when-to-use-the-domain-model-pattern-in-java)

- Appropriate in complex applications with rich business logic.
- When the business logic or domain complexity is high and requires a model that closely represents real-world entities and their relationships.
- Suitable for applications where domain experts are involved in the development process to ensure the model accurately reflects domain concepts.

## [Domain Model Pattern Java Tutorials](https://java-design-patterns.com/patterns/domain-model/#domain-model-pattern-java-tutorials)

- [Architecture patterns: domain model and friends (Inviqa)](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends)

## [Real-World Applications of Domain Model Pattern in Java](https://java-design-patterns.com/patterns/domain-model/#real-world-applications-of-domain-model-pattern-in-java)

- Enterprise applications (ERP, CRM systems)
- Financial systems (banking, trading platforms)
- Healthcare applications (patient records management)
- E-commerce platforms (product catalogs, shopping carts)

## [Benefits and Trade-offs of Domain Model Pattern](https://java-design-patterns.com/patterns/domain-model/#benefits-and-trade-offs-of-domain-model-pattern)

Benefits:

- Improved Communication: Provides a common language for developers and domain experts, enhancing understanding and collaboration.
- Flexibility: Encapsulates business logic within domain entities, making it easier to modify and extend without affecting other system parts.
- Maintainability: A well-structured domain model can simplify maintenance and evolution of the application over time.
- Reusability: Domain classes can often be reused across different projects within the same domain.

Trade-offs:

- Complexity: Can introduce complexity, especially in simple applications where a domain model might be overkill.
- Performance Concerns: Rich domain objects with complex behaviors might lead to performance bottlenecks, requiring careful optimization.
- Learning Curve: Requires a good understanding of the domain and may involve a steep learning curve for developers unfamiliar with the domain concepts.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/domain-model/#related-java-design-patterns)

- [Data Access Object (DAO)](https://java-design-patterns.com/patterns/dao/): For abstracting and encapsulating all access to the data source.
- [Repository](https://java-design-patterns.com/patterns/repository/): Mediates between the domain and data mapping layers, acting like an in-memory domain object collection.
- [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation.
- [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Maintains a list of objects affected by a business transaction and coordinates the writing out of changes.

## [References and Credits](https://java-design-patterns.com/patterns/domain-model/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3vMCjnP)
- [Implementing Domain-Driven Design](https://amzn.to/4cUX4OL)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Domain Model (Martin Fowler)](https://martinfowler.com/eaaCatalog/domainModel.html)

---

## [structural/dynamic-proxy] Dynamic Proxy
> 官方文档: https://java-design-patterns.com/patterns/dynamic-proxy/

StructuralDecouplingDynamic typingEnhancementExtensibilityProxyRuntimeAbout 12 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/dynamic-proxy/#also-known-as)

- Runtime Proxy

## [Intent of Dynamic Proxy Design Pattern](https://java-design-patterns.com/patterns/dynamic-proxy/#intent-of-dynamic-proxy-design-pattern)

To provide a flexible proxy mechanism capable of dynamically creating proxies for various interfaces at runtime, allowing for controlled access or functionality enhancement of objects.

## [Detailed Explanation of Dynamic Proxy Pattern with Real-World Examples](https://java-design-patterns.com/patterns/dynamic-proxy/#detailed-explanation-of-dynamic-proxy-pattern-with-real-world-examples)

Real-world example

> Mockito, a popular Java mocking framework, employs dynamic proxy to create mock objects for testing. Mock objects mimic the behavior of real objects, allowing developers to isolate components and verify interactions in unit tests. Consider a scenario where a service class depends on an external component, such as a database access object (DAO). Instead of interacting with a real DAO in a test, Mockito can dynamically generate a proxy, intercepting method invocations and returning predefined values. This enables focused unit testing without the need for a real database connection.

In plain words

> The Dynamic Proxy Pattern in Java is a specialized form of proxy, serving as a flexible and dynamic method to intercept and manipulate method calls. By utilizing dynamic proxies, developers can implement additional functionalities without modifying the original class code. This is particularly useful in scenarios requiring enhancement of existing functionalities.

Wikipedia says

> A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a _java.lang.reflect.Method_ object identifying the method that was invoked and an array of type _Object_ containing the arguments.

Sequence diagram

![Dynamic Proxy sequence diagram](https://java-design-patterns.com/assets/img/dynamic-proxy-sequence-diagram.0cc06470.png)

## [Programmatic Example of Dynamic Proxy Pattern in Java](https://java-design-patterns.com/patterns/dynamic-proxy/#programmatic-example-of-dynamic-proxy-pattern-in-java)

This example demonstrates using the Dynamic Proxy pattern in Java to hit the public fake API [JSONPlaceholder](https://jsonplaceholder.typicode.com/) for the resource `Album` through an interface.

In this demo, the Dynamic Proxy pattern helps us run business logic through an interface without explicitly implementing that interface, leveraging Java Reflection.

The `App` class sets up the dynamic proxy for the `AlbumService` interface and demonstrates how to use the proxy to make API calls.

```java
@Slf4j
public class App {

    static final String REST_API_URL = "https://jsonplaceholder.typicode.com";
    private AlbumService albumServiceProxy;

    public static void main(String[] args) {
        App app = new App();
        app.createDynamicProxy();
        app.callMethods();
    }

    public void createDynamicProxy() {
        AlbumInvocationHandler handler = new AlbumInvocationHandler(REST_API_URL, HttpClient.newHttpClient());
        albumServiceProxy = (AlbumService) Proxy.newProxyInstance(
                App.class.getClassLoader(), new Class<?>[]{AlbumService.class}, handler);
    }

    public void callMethods() {
        var albums = albumServiceProxy.readAlbums();
        albums.forEach(album -> LOGGER.info("{}", album));

        var album = albumServiceProxy.readAlbum(17);
        LOGGER.info("{}", album);

        var newAlbum = albumServiceProxy.createAlbum(Album.builder().title("Big World").userId(3).build());
        LOGGER.info("{}", newAlbum);

        var editAlbum = albumServiceProxy.updateAlbum(17, Album.builder().title("Green Valley").userId(3).build());
        LOGGER.info("{}", editAlbum);

        var removedAlbum = albumServiceProxy.deleteAlbum(17);
        LOGGER.info("{}", removedAlbum);
    }
}
```

- The `createDynamicProxy` method uses `Proxy.newProxyInstance` to create a new dynamic proxy for the `AlbumService` interface.
- The `callMethods` method demonstrates using the dynamic proxy to make various API calls.

The `AlbumService` interface defines the API operations that can be dynamically proxied. It uses custom annotations to specify HTTP methods and paths.

```java
public interface AlbumService {
    @Get("/albums")
    List<Album> readAlbums();

    @Get("/albums/{albumId}")
    Album readAlbum(@Path("albumId") Integer albumId);

    @Post("/albums")
    Album createAlbum(@Body Album album);

    @Put("/albums/{albumId}")
    Album updateAlbum(@Path("albumId") Integer albumId, @Body Album album);

    @Delete("/albums/{albumId}")
    Album deleteAlbum(@Path("albumId") Integer albumId);
}
```

- Annotations like `@Get` and `@Post` indicate the HTTP method and the path for each method.
- These annotations are used by the `TinyRestClient` to construct appropriate HTTP requests.

The `AlbumInvocationHandler` class is where method calls on the proxy are intercepted and delegated to the `TinyRestClient`.

```java
@Slf4j
public class AlbumInvocationHandler implements InvocationHandler {

    private TinyRestClient restClient;

    public AlbumInvocationHandler(String baseUrl, HttpClient httpClient) {
        this.restClient = new TinyRestClient(baseUrl, httpClient);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        LOGGER.info("===== Calling the method {}.{}()",
                method.getDeclaringClass().getSimpleName(), method.getName());
        return restClient.send(method, args);
    }
}
```

- Implements `InvocationHandler`, which requires defining the `invoke` method.
- The `invoke` method is called every time a method on the proxy is invoked. It delegates the call to the `TinyRestClient`, passing along the method and its arguments.

The `TinyRestClient` handles the construction and sending of HTTP requests based on the annotations and method details.

```java
@Slf4j
public class TinyRestClient {
    private String baseUrl;
    private HttpClient httpClient;

    public TinyRestClient(String baseUrl, HttpClient httpClient) {
        this.baseUrl = baseUrl;
        this.httpClient = httpClient;
    }

    public Object send(Method method, Object[] args) throws IOException, InterruptedException {
        var url = baseUrl + buildUrl(method, args);
        var httpRequest = HttpRequest.newBuilder().uri(URI.create(url)).build();
        var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        return getResponse(method, httpResponse);
    }

    private String buildUrl(Method method, Object[] args) {
        // Simplified URL building logic
        return "/albums";
    }

    private Object getResponse(Method method, HttpResponse<String> httpResponse) {
        // Simplified response handling logic
        return httpResponse.body();
    }
}
```

- This class uses Java's `HttpClient` to send HTTP requests.
- The `send` method constructs a `HttpRequest` using details from the method's annotations, although simplified here to focus on the dynamic proxy mechanism.
- The response is returned as a simple string, demonstrating basic interaction with an API.

Running the example produces the following console output showcasing the API calls and responses. See the `App` class and `main` method above.

```
16:05:41.964 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.readAlbums()
16:05:42.409 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=1, title=quidem molestiae enim, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=2, title=sunt qui excepturi placeat culpa, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=3, title=omnis laborum odio, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=4, title=non esse culpa molestiae omnis sed optio, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=5, title=eaque aut omnis a, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=6, title=natus impedit quibusdam illo est, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=7, title=quibusdam autem aliquid et et quia, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=8, title=qui fuga est a eum, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=9, title=saepe unde necessitatibus rem, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=10, title=distinctio laborum qui, userId=1)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=11, title=quam nostrum impedit mollitia quod et dolor, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=12, title=consequatur autem doloribus natus consectetur, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=13, title=ab rerum non rerum consequatur ut ea unde, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=14, title=ducimus molestias eos animi atque nihil, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=15, title=ut pariatur rerum ipsum natus repellendus praesentium, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=16, title=voluptatem aut maxime inventore autem magnam atque repellat, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=17, title=aut minima voluptatem ut velit, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=18, title=nesciunt quia et doloremque, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=19, title=velit pariatur quaerat similique libero omnis quia, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=20, title=voluptas rerum iure ut enim, userId=2)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=21, title=repudiandae voluptatem optio est consequatur rem in temporibus et, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=22, title=et rem non provident vel ut, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=23, title=incidunt quisquam hic adipisci sequi, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=24, title=dolores ut et facere placeat, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=25, title=vero maxime id possimus sunt neque et consequatur, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=26, title=quibusdam saepe ipsa vel harum, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=27, title=id non nostrum expedita, userId=3)
16:05:42.410 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=28, title=omnis neque exercitationem sed dolor atque maxime aut cum, userId=3)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=29, title=inventore ut quasi magnam itaque est fugit, userId=3)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=30, title=tempora assumenda et similique odit distinctio error, userId=3)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=31, title=adipisci laborum fuga laboriosam, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=32, title=reiciendis dolores a ut qui debitis non quo labore, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=33, title=iste eos nostrum, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=34, title=cumque voluptatibus rerum architecto blanditiis, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=35, title=et impedit nisi quae magni necessitatibus sed aut pariatur, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=36, title=nihil cupiditate voluptate neque, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=37, title=est placeat dicta ut nisi rerum iste, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=38, title=unde a sequi id, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=39, title=ratione porro illum labore eum aperiam sed, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=40, title=voluptas neque et sint aut quo odit, userId=4)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=41, title=ea voluptates maiores eos accusantium officiis tempore mollitia consequatur, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=42, title=tenetur explicabo ea, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=43, title=aperiam doloremque nihil, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=44, title=sapiente cum numquam officia consequatur vel natus quos suscipit, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=45, title=tenetur quos ea unde est enim corrupti qui, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=46, title=molestiae voluptate non, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=47, title=temporibus molestiae aut, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=48, title=modi consequatur culpa aut quam soluta alias perspiciatis laudantium, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=49, title=ut aut vero repudiandae voluptas ullam voluptas at consequatur, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=50, title=sed qui sed quas sit ducimus dolor, userId=5)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=51, title=odit laboriosam sint quia cupiditate animi quis, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=52, title=necessitatibus quas et sunt at voluptatem, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=53, title=est vel sequi voluptatem nemo quam molestiae modi enim, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=54, title=aut non illo amet perferendis, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=55, title=qui culpa itaque omnis in nesciunt architecto error, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=56, title=omnis qui maiores tempora officiis omnis rerum sed repellat, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=57, title=libero excepturi voluptatem est architecto quae voluptatum officia tempora, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=58, title=nulla illo consequatur aspernatur veritatis aut error delectus et, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=59, title=eligendi similique provident nihil, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=60, title=omnis mollitia sunt aliquid eum consequatur fugit minus laudantium, userId=6)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=61, title=delectus iusto et, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=62, title=eos ea non recusandae iste ut quasi, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=63, title=velit est quam, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=64, title=autem voluptatem amet iure quae, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=65, title=voluptates delectus iure iste qui, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=66, title=velit sed quia dolor dolores delectus, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=67, title=ad voluptas nostrum et nihil, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=68, title=qui quasi nihil aut voluptatum sit dolore minima, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=69, title=qui aut est, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=70, title=et deleniti unde, userId=7)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=71, title=et vel corporis, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=72, title=unde exercitationem ut, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=73, title=quos omnis officia, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=74, title=quia est eius vitae dolor, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=75, title=aut quia expedita non, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=76, title=dolorem magnam facere itaque ut reprehenderit tenetur corrupti, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=77, title=cupiditate sapiente maiores iusto ducimus cum excepturi veritatis quia, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=78, title=est minima eius possimus ea ratione velit et, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=79, title=ipsa quae voluptas natus ut suscipit soluta quia quidem, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=80, title=id nihil reprehenderit, userId=8)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=81, title=quibusdam sapiente et, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=82, title=recusandae consequatur vel amet unde, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=83, title=aperiam odio fugiat, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=84, title=est et at eos expedita, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=85, title=qui voluptatem consequatur aut ab quis temporibus praesentium, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=86, title=eligendi mollitia alias aspernatur vel ut iusto, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=87, title=aut aut architecto, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=88, title=quas perspiciatis optio, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=89, title=sit optio id voluptatem est eum et, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=90, title=est vel dignissimos, userId=9)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=91, title=repellendus praesentium debitis officiis, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=92, title=incidunt et et eligendi assumenda soluta quia recusandae, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=93, title=nisi qui dolores perspiciatis, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=94, title=quisquam a dolores et earum vitae, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=95, title=consectetur vel rerum qui aperiam modi eos aspernatur ipsa, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=96, title=unde et ut molestiae est molestias voluptatem sint, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=97, title=est quod aut, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=98, title=omnis quia possimus nesciunt deleniti assumenda sed autem, userId=10)
16:05:42.411 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=99, title=consectetur ut id impedit dolores sit ad ex aut, userId=10)
16:05:42.412 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=100, title=enim repellat iste, userId=10)
16:05:42.412 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.readAlbum()
16:05:42.741 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=17, title=aut minima voluptatem ut velit, userId=2)
16:05:42.741 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.createAlbum()
16:05:43.073 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=101, title=Big World, userId=3)
16:05:43.073 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.updateAlbum()
16:05:43.220 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=17, title=Green Valley, userId=3)
16:05:43.220 [main] INFO com.iluwatar.dynamicproxy.AlbumInvocationHandler -- ===== Calling the method AlbumService.deleteAlbum()
16:05:43.357 [main] INFO com.iluwatar.dynamicproxy.App -- Album(id=null, title=null, userId=null)
```

## [When to Use the Dynamic Proxy Pattern in Java](https://java-design-patterns.com/patterns/dynamic-proxy/#when-to-use-the-dynamic-proxy-pattern-in-java)

Dynamic proxy should be used when you need to augment or enhance your current functionality without modifying your current code. Some examples of that usage could be:

- You want to intercept calls to methods of an object at runtime for handling purposes such as logging, transaction management, or security checks.
- You need to create a proxy object for one or more interfaces dynamically at runtime without coding it explicitly for each interface.
- You aim to simplify complex systems by decoupling the client and the real object through a flexible proxy mechanism.

## [Dynamic Proxy Pattern Java Tutorials](https://java-design-patterns.com/patterns/dynamic-proxy/#dynamic-proxy-pattern-java-tutorials)

- [Dynamic Proxies in Java (CodeGym)](https://codegym.cc/groups/posts/208-dynamic-proxies)
- [Introduction To Java Dynamic Proxy (Xperti)](https://xperti.io/blogs/java-dynamic-proxies-introduction/)
- [Dynamic Proxies in Java (Baeldung)](https://www.baeldung.com/java-dynamic-proxies)
- [Intro To Java Dynamic Proxies (KapreSoft)](https://www.kapresoft.com/java/2023/12/27/intro-to-java-proxies.html)
- [Exploring the Depths of Dynamic Proxy in Java: A Comprehensive Guide (Medium)](https://naveen-metta.medium.com/exploring-the-depths-of-dynamic-proxy-in-java-a-comprehensive-guide-f34fb45b38a3)

## [Real-World Applications of Dynamic Proxy Pattern in Java](https://java-design-patterns.com/patterns/dynamic-proxy/#real-world-applications-of-dynamic-proxy-pattern-in-java)

Many frameworks and libraries use dynamic proxy to implement their functionalities:

- Java's `java.lang.reflect.Proxy` class is a built-in dynamic proxy mechanism.
- [Spring Framework](https://docs.spring.io/spring-framework/reference/core/aop.html), for aspect oriented programming.
- [Hibernate](https://hibernate.org/orm/), for data lazy loading.
- [Mockito](https://site.mockito.org/), for mocking objects in testing.
- [Cleverclient](https://github.com/sashirestela/cleverclient), for calling http endpoints through annotated interfaces.
- Java Reflection API: Java's built-in support for dynamic proxies with the use of java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler.
- Frameworks: Extensively used in Java frameworks like Spring for AOP (Aspect-Oriented Programming) to handle transactions, security, logging, etc.
- Middleware: In middleware services for transparently adding services like load balancing and access control.

## [Benefits and Trade-offs of Dynamic Proxy Pattern](https://java-design-patterns.com/patterns/dynamic-proxy/#benefits-and-trade-offs-of-dynamic-proxy-pattern)

Benefits:

- Increased flexibility in code: Dynamic proxies in Java offer a high degree of flexibility, allowing developers to create versatile and adaptable applications. By using dynamic proxies, software engineers can modify the behavior of methods at runtime, which is particularly useful in scenarios where the behavior of classes needs to be augmented or manipulated without altering their source code. This flexibility is crucial in developing applications that require dynamic response to varying conditions or need to integrate with systems where interfaces may change over time.
- Simplifying complex operations: Dynamic proxies excel in simplifying complex operations, particularly in the areas of cross-cutting concerns such as logging, transaction management, and security. By intercepting method calls, dynamic proxies can uniformly apply certain operations across various methods and classes, thereby reducing the need for repetitive code. This capability is particularly beneficial in large-scale applications where such cross-cutting concerns are prevalent. For example, adding logging or authorization checks across multiple methods becomes a matter of implementing these features once in an invocation handler, rather than modifying each method individually.
- Enhancing code maintainability: Maintainability is a key advantage of using dynamic proxies. They promote cleaner and more organized code by separating the core business logic from cross-cutting concerns. This separation of concerns not only makes the codebase more understandable but also easier to test and debug. When the business logic is decoupled from aspects like logging or transaction handling, any changes in these areas do not impact the core functionality of the application. As a result, applications become more robust and easier to maintain and update, which is crucial in the fast-paced environment of software development where requirements and technologies are constantly evolving.
- Separation of Concerns: Promotes separation of concerns by decoupling the client code from the actual handling of method calls.

Trade-offs:

- Performance overhead: The use of reflection and method invocation through proxies can introduce latency, especially in performance-critical applications. This overhead might be negligible in most cases, but it becomes significant in scenarios with high-frequency method calls.
- Complexity of debugging: Since dynamic proxies introduce an additional layer of abstraction, tracing and debugging issues can be more challenging. It can be difficult to trace the flow of execution through proxies, especially when multiple proxies are involved.
- Limited to interface-based programming: They can only proxy interfaces, not classes. This limitation requires careful design considerations, particularly in situations where class-based proxies would be more appropriate.
- Higher level of expertise: Developers are normally not a fan of “magic code” — code that works in a non-transparent or overly complex manner. Those unfamiliar with the proxy pattern or reflection might find the codebase more complex to understand and maintain, potentially leading to errors or misuse of the feature. This complexity can be perceived as a form of “magic” that obscures the underlying process, making the code less intuitive and more challenging to debug or extend. Therefore, while dynamic proxies are powerful, their use should be approached with caution and a thorough understanding of their inner workings.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/dynamic-proxy/#related-java-design-patterns)

- [Proxy](https://java-design-patterns.com/patterns/proxy): Static counterpart of the Dynamic Proxy, where proxies are explicitly coded.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in structure by providing additional functionality, but without the dynamic proxy's capability to handle any interface.
- [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies the interface to complex systems, not through dynamic proxies but through a single simplified interface.

## [References and Credits](https://java-design-patterns.com/patterns/dynamic-proxy/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3U0d8Gm)
- [Java Reflection in Action](https://amzn.to/3TVpe3t)
- [Pro Spring 6: An In-Depth Guide to the Spring Framework](https://amzn.to/43Zs2Bx)
- [Dynamic Proxy Classes - Oracle](https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html)

---

## [structural/extension-objects] Extension Objects
> 官方文档: https://java-design-patterns.com/patterns/extension-objects/

StructuralEncapsulationExtensibilityObject compositionPolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/extension-objects/#also-known-as)

- Interface Extensions

## [Intent of Extension Objects Design Pattern](https://java-design-patterns.com/patterns/extension-objects/#intent-of-extension-objects-design-pattern)

The Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure, by attaching additional objects that can dynamically add new functionality.

## [Detailed Explanation of Extension Objects Pattern with Real-World Examples](https://java-design-patterns.com/patterns/extension-objects/#detailed-explanation-of-extension-objects-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Extension Objects design pattern can be found in modular kitchen appliances. Consider a base blender unit to which different attachments can be added, such as a food processor, juicer, or grinder. Each attachment adds new functionality to the blender without altering the base unit itself. Users can dynamically switch between different functionalities based on their current needs, making the blender highly versatile and adaptable to various tasks. This mirrors the Extension Objects pattern in software, where new functionalities are added to an object dynamically and contextually, enhancing flexibility and reuse.

In plain words

> The Extension Objects pattern is used to dynamically add functionality to objects without modifying their core classes. It is a behavioural design pattern used for adding new functionality to existing classes and objects within a program. This pattern provides programmers with the ability to extend/modify class functionality without having to refactor existing source code.

Wikipedia says

> In object-oriented computer programming, an extension objects pattern is a design pattern added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension object patterns are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.

Sequence diagram

![Extension Objects sequence diagram](https://java-design-patterns.com/assets/img/extension-objects-sequence-diagram.b30c68f1.png)

## [Programmatic Example of Extension Objects Pattern in Java](https://java-design-patterns.com/patterns/extension-objects/#programmatic-example-of-extension-objects-pattern-in-java)

The Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure, by attaching additional objects that can dynamically add new functionality.

In this Java implementation, we have three types of units: `SoldierUnit`, `SergeantUnit`, and `CommanderUnit`. Each unit can have extensions that provide additional functionality. The extensions are `SoldierExtension`, `SergeantExtension`, and `CommanderExtension`.

The `Unit` class is the base class for all units. It has a method `getUnitExtension` that returns an extension object based on the extension name.

```java
public abstract class Unit {
  private String name;

  protected Unit(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public abstract UnitExtension getUnitExtension(String extensionName);
}
```

The `UnitExtension` interface is the base interface for all extensions. Each specific extension will implement this interface.

```java
public interface UnitExtension {
  String getName();
}
```

The `SoldierUnit` class is a specific type of unit. It overrides the `getUnitExtension` method to return a `SoldierExtension` object.

```java
public class SoldierUnit extends Unit {
  public SoldierUnit(String name) {
    super(name);
  }

  @Override
  public UnitExtension getUnitExtension(String extensionName) {
    if ("SoldierExtension".equals(extensionName)) {
      return new SoldierExtension(this);
    }
    return null;
  }
}
```

The `SoldierExtension` class is a specific type of extension. It implements the `UnitExtension` interface and provides additional functionality for the `SoldierUnit`.

```java
public class SoldierExtension implements UnitExtension {
  private SoldierUnit unit;

  public SoldierExtension(SoldierUnit unit) {
    this.unit = unit;
  }

  @Override
  public String getName() {
    return "SoldierExtension";
  }

  public void soldierReady() {
    // additional functionality for SoldierUnit
  }
}
```

In the `main` application, we create different types of units and check for each unit to have an extension. If the extension exists, we call the specific method on the extension object.

```java
public class App {
  public static void main(String[] args) {
    var soldierUnit = new SoldierUnit("SoldierUnit1");
    var sergeantUnit = new SergeantUnit("SergeantUnit1");
    var commanderUnit = new CommanderUnit("CommanderUnit1");

    checkExtensionsForUnit(soldierUnit);
    checkExtensionsForUnit(sergeantUnit);
    checkExtensionsForUnit(commanderUnit);
  }

  private static void checkExtensionsForUnit(Unit unit) {
    var extension = "SoldierExtension";
    Optional.ofNullable(unit.getUnitExtension(extension))
        .map(e -> (SoldierExtension) e)
        .ifPresentOrElse(SoldierExtension::soldierReady, () -> System.out.println(unit.getName() + " without " + extension));
  }
}
```

This produces the following console output.

```
22:58:03.779 [main] INFO concreteextensions.Soldier -- [Soldier] SoldierUnit1 is ready!
22:58:03.781 [main] INFO App -- SoldierUnit1 without SergeantExtension
22:58:03.782 [main] INFO App -- SoldierUnit1 without CommanderExtension
22:58:03.782 [main] INFO App -- SergeantUnit1 without SoldierExtension
22:58:03.783 [main] INFO concreteextensions.Sergeant -- [Sergeant] SergeantUnit1 is ready!
22:58:03.783 [main] INFO App -- SergeantUnit1 without CommanderExtension
22:58:03.783 [main] INFO App -- CommanderUnit1 without SoldierExtension
22:58:03.783 [main] INFO App -- CommanderUnit1 without SergeantExtension
22:58:03.783 [main] INFO concreteextensions.Commander -- [Commander] CommanderUnit1 is ready!
```

This example demonstrates how the Extension Objects pattern allows for the flexible extension of an object's behavior without modifying its structure.

## [When to Use the Extension Objects Pattern in Java](https://java-design-patterns.com/patterns/extension-objects/#when-to-use-the-extension-objects-pattern-in-java)

This pattern is applicable in scenarios where an object's functionality needs to be extended at runtime, avoiding the complications of subclassing. It's particularly useful in systems where object capabilities need to be augmented post-deployment, or where the capabilities might vary significantly across instances.

## [Real-World Applications of Extension Objects Pattern in Java](https://java-design-patterns.com/patterns/extension-objects/#real-world-applications-of-extension-objects-pattern-in-java)

- Extending services in an application server without altering existing code.
- Plugins in IDEs like IntelliJ IDEA or Eclipse to add features to the base application.
- Enabling additional features in enterprise software based on license levels.
- [OpenDoc](https://en.wikipedia.org/wiki/OpenDoc)
- [Object Linking and Embedding](https://en.wikipedia.org/wiki/Object_Linking_and_Embedding)

## [Benefits and Trade-offs of Extension Objects Pattern](https://java-design-patterns.com/patterns/extension-objects/#benefits-and-trade-offs-of-extension-objects-pattern)

Benefits:

- Enhances flexibility by allowing dynamic extension of an object's capabilities.
- Promotes loose coupling between the base object and its extensions.
- Supports the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle) by keeping the object open for extension but closed for modification.

Trade-offs:

- Can increase complexity due to the management of extension objects.
- May introduce performance overhead if the interaction between objects and extensions is not efficiently designed.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/extension-objects/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in intent to add responsibilities dynamically, but uses a different structure.
- [Composite](https://java-design-patterns.com/patterns/composite/): Also manages a group of objects, which can be seen as a form of extension.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Offers an alternative way to change the behavior of an object dynamically.

## [References and Credits](https://java-design-patterns.com/patterns/extension-objects/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4aBMuuL)
- [Pattern-Oriented Software Architecture: A System of Patterns](https://amzn.to/3Q9YOtX)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3W6IZYQ)

---

## [structural/facade] Facade 外观
> 官方文档: https://java-design-patterns.com/patterns/facade/

StructuralAbstractionAPI designCode simplificationDecouplingEncapsulationGang of FourInterfaceObject compositionAbout 4 min

* * *

## [Intent of Facade Design Pattern](https://java-design-patterns.com/patterns/facade/#intent-of-facade-design-pattern)

The Facade Design Pattern provides a unified interface to a set of interfaces in a subsystem. This Java design pattern simplifies complex system interactions.

## [Detailed Explanation of Facade Pattern with Real-World Examples](https://java-design-patterns.com/patterns/facade/#detailed-explanation-of-facade-pattern-with-real-world-examples)

Real-world example

> Imagine a home theater system with multiple components: a DVD player, projector, surround sound system, and lights. Each component has a complex interface with numerous functions and settings. To simplify the use of the home theater system, a remote control (the Facade) is provided. The remote control offers a unified interface with simple buttons like "Play Movie," "Stop," "Pause," and "Volume Up/Down," which internally communicate with the various components, managing their interactions. This makes the system easier to use without needing to understand the detailed operations of each component.

In plain words

> Facade pattern provides a simplified interface to a complex subsystem.

Wikipedia says

> A facade is an object that provides a simplified interface to a larger body of code, such as a class library.

Sequence diagram

![Facade sequence diagram](https://java-design-patterns.com/assets/img/facade-sequence-diagram.331e642d.png)

## [Programmatic Example of Facade Pattern in Java](https://java-design-patterns.com/patterns/facade/#programmatic-example-of-facade-pattern-in-java)

Here's an example of the Facade Design Pattern in a goldmine scenario, demonstrating how a Java facade can streamline complex operations.

How does a goldmine work? "Well, the miners go down there and dig gold!" you say. That is what you believe because you are using a simple interface that goldmine provides on the outside, internally it has to do a lot of stuff to make it happen. This simple interface to the complex subsystem is a facade.

Here we have the dwarven mine worker hierarchy. First, there's a base class `DwarvenMineWorker`:

```java

@Slf4j
public abstract class DwarvenMineWorker {

    public void goToSleep() {
        LOGGER.info("{} goes to sleep.", name());
    }

    public void wakeUp() {
        LOGGER.info("{} wakes up.", name());
    }

    public void goHome() {
        LOGGER.info("{} goes home.", name());
    }

    public void goToMine() {
        LOGGER.info("{} goes to the mine.", name());
    }

    private void action(Action action) {
        switch (action) {
            case GO_TO_SLEEP -> goToSleep();
            case WAKE_UP -> wakeUp();
            case GO_HOME -> goHome();
            case GO_TO_MINE -> goToMine();
            case WORK -> work();
            default -> LOGGER.info("Undefined action");
        }
    }

    public void action(Action... actions) {
        Arrays.stream(actions).forEach(this::action);
    }

    public abstract void work();

    public abstract String name();

    enum Action {
        GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
    }
}
```

Then we have the concrete dwarf classes `DwarvenTunnelDigger`, `DwarvenGoldDigger` and `DwarvenCartOperator`:

```java

@Slf4j
public class DwarvenTunnelDigger extends DwarvenMineWorker {

    @Override
    public void work() {
        LOGGER.info("{} creates another promising tunnel.", name());
    }

    @Override
    public String name() {
        return "Dwarven tunnel digger";
    }
}

@Slf4j
public class DwarvenGoldDigger extends DwarvenMineWorker {

    @Override
    public void work() {
        LOGGER.info("{} digs for gold.", name());
    }

    @Override
    public String name() {
        return "Dwarf gold digger";
    }
}

@Slf4j
public class DwarvenCartOperator extends DwarvenMineWorker {

    @Override
    public void work() {
        LOGGER.info("{} moves gold chunks out of the mine.", name());
    }

    @Override
    public String name() {
        return "Dwarf cart operator";
    }
}
```

To operate all these goldmine workers we have the `DwarvenGoldmineFacade`:

```java
public class DwarvenGoldmineFacade {

    private final List<DwarvenMineWorker> workers;

    public DwarvenGoldmineFacade() {
        workers = List.of(
                new DwarvenGoldDigger(),
                new DwarvenCartOperator(),
                new DwarvenTunnelDigger());
    }

    public void startNewDay() {
        makeActions(workers, DwarvenMineWorker.Action.WAKE_UP, DwarvenMineWorker.Action.GO_TO_MINE);
    }

    public void digOutGold() {
        makeActions(workers, DwarvenMineWorker.Action.WORK);
    }

    public void endDay() {
        makeActions(workers, DwarvenMineWorker.Action.GO_HOME, DwarvenMineWorker.Action.GO_TO_SLEEP);
    }

    private static void makeActions(Collection<DwarvenMineWorker> workers,
                                    DwarvenMineWorker.Action... actions) {
        workers.forEach(worker -> worker.action(actions));
    }
}
```

Now let's use the facade:

```java
public static void main(String[] args) {
    var facade = new DwarvenGoldmineFacade();
    facade.startNewDay();
    facade.digOutGold();
    facade.endDay();
}
```

Program output:

```
06:07:20.676 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger wakes up.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger goes to the mine.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator wakes up.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator goes to the mine.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger wakes up.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes to the mine.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenGoldDigger -- Dwarf gold digger digs for gold.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenCartOperator -- Dwarf cart operator moves gold chunks out of the mine.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenTunnelDigger -- Dwarven tunnel digger creates another promising tunnel.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger goes home.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf gold digger goes to sleep.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator goes home.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarf cart operator goes to sleep.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes home.
06:07:20.678 [main] INFO com.iluwatar.facade.DwarvenMineWorker -- Dwarven tunnel digger goes to sleep.
```

## [When to Use the Facade Pattern in Java](https://java-design-patterns.com/patterns/facade/#when-to-use-the-facade-pattern-in-java)

Use the Facade pattern in Java when:

- You want to provide a simple interface to a complex subsystem.
- Subsystems are getting more complex and depend on multiple classes, but most clients only need a part of the functionality.
- There is a need to layer your subsystems. Use a facade to define an entry point to each subsystem level.
- You want to reduce dependencies and enhance code readability in Java development.

## [Facade Pattern Java Tutorials](https://java-design-patterns.com/patterns/facade/#facade-pattern-java-tutorials)

- [Facade Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/facade-design-pattern-in-java)
- [Facade (Refactoring Guru)](https://refactoring.guru/design-patterns/facade)
- [Facade Method Design Pattern (GeekforGeeks)](https://www.geeksforgeeks.org/facade-design-pattern-introduction/)
- [Design Patterns - Facade Pattern (TutorialsPoint)](https://www.tutorialspoint.com/design_pattern/facade_pattern.htm)

## [Real-World Applications of Facade Pattern in Java](https://java-design-patterns.com/patterns/facade/#real-world-applications-of-facade-pattern-in-java)

- Java libraries such as java.net.URL and javax.faces.context.FacesContext use Facade to simplify complex underlying classes.
- In many Java frameworks, facades are used to simplify the usage of APIs by providing a simpler interface to more complex underlying code structures.

## [Benefits and Trade-offs of Facade Pattern](https://java-design-patterns.com/patterns/facade/#benefits-and-trade-offs-of-facade-pattern)

Benefits:

Implementing the Facade Design Pattern in Java:

- Isolates clients from subsystem components, making it easier to use and reducing dependencies.
- Promotes weak coupling between the subsystem and its clients.
- Often simplifies the API of complex systems.

Trade-offs:

- A facade can become a god object coupled to all classes of an app if not implemented correctly.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/facade/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Facade provides a unified interface while Adapter makes two existing interfaces work together.
- [Mediator](https://java-design-patterns.com/patterns/mediator/): Facade defines a simpler interface to a subsystem while Mediator centralizes complex communications and control between objects.

## [References and Credits](https://java-design-patterns.com/patterns/facade/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3QbO7qN)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG)

---

## [structural/flyweight] Flyweight 享元
> 官方文档: https://java-design-patterns.com/patterns/flyweight/

StructuralGang of FourMemory managementObject compositionOptimizationPerformanceAbout 4 min

* * *

## [Intent of Flyweight Design Pattern](https://java-design-patterns.com/patterns/flyweight/#intent-of-flyweight-design-pattern)

The Flyweight design pattern in Java is crucial for optimizing memory usage and enhancing application performance. By minimizing the number of objects created, it significantly reduces the memory footprint. The primary goal of the Flyweight pattern is to share as much data as possible among similar objects, thereby improving efficiency and performance.

## [Detailed Explanation of Flyweight Pattern with Real-World Examples](https://java-design-patterns.com/patterns/flyweight/#detailed-explanation-of-flyweight-pattern-with-real-world-examples)

Real-world example

> A real-world application of the Flyweight pattern in Java can be seen in text editors like Microsoft Word or Google Docs. These applications use Flyweight to efficiently manage memory by sharing character objects, reducing the memory footprint significantly. In such applications, each character in a document could potentially be a separate object, which would be highly inefficient in terms of memory usage. Instead, the Flyweight pattern can be used to share character objects. For instance, all instances of the letter 'A' can share a single 'A' object with its intrinsic state (e.g., the shape of the character). The extrinsic state, such as the position, font, and color, can be stored separately and applied as needed. This way, the application efficiently manages memory by reusing existing objects for characters that appear multiple times.

In plain words

> It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects.

Wikipedia says

> In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

Sequence diagram

![Flyweight sequence diagram](https://java-design-patterns.com/assets/img/flyweight-sequence-diagram.12c65094.png)

## [Programmatic Example of Flyweight Pattern in Java](https://java-design-patterns.com/patterns/flyweight/#programmatic-example-of-flyweight-pattern-in-java)

Alchemist's shop has shelves full of magic potions. Many of the potions are the same so there is no need to create a new object for each of them. Instead, one object instance can represent multiple shelf items so the memory footprint remains small.

First of all, we have different `Potion` types:

```java
public interface Potion {
  void drink();
}
```

```java
@Slf4j
public class HealingPotion implements Potion {
  @Override
  public void drink() {
    LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this));
  }
}
```

```java
@Slf4j
public class HolyWaterPotion implements Potion {
  @Override
  public void drink() {
    LOGGER.info("You feel blessed. (Potion={})", System.identityHashCode(this));
  }
}
```

```java
@Slf4j
public class InvisibilityPotion implements Potion {
  @Override
  public void drink() {
    LOGGER.info("You become invisible. (Potion={})", System.identityHashCode(this));
  }
}
```

Then the actual Flyweight class `PotionFactory`, which is the factory for creating potions.

```java
public class PotionFactory {

  private final Map<PotionType, Potion> potions;

  public PotionFactory() {
    potions = new EnumMap<>(PotionType.class);
  }

  Potion createPotion(PotionType type) {
    var potion = potions.get(type);
    if (potion == null) {
      switch (type) {
        case HEALING -> potion = new HealingPotion();
        case HOLY_WATER -> potion = new HolyWaterPotion();
        case INVISIBILITY -> potion = new InvisibilityPotion();
        default -> {
        }
      }
      potions.put(type, potion);
    }
    return potion;
  }
}
```

`AlchemistShop` contains two shelves of magic potions. The potions are created using the aforementioned `PotionFactory`.

```java
@Slf4j
public class AlchemistShop {

  private final List<Potion> topShelf;
  private final List<Potion> bottomShelf;

  public AlchemistShop() {
    var factory = new PotionFactory();
    topShelf = List.of(
        factory.createPotion(PotionType.INVISIBILITY),
        factory.createPotion(PotionType.INVISIBILITY),
        factory.createPotion(PotionType.STRENGTH),
        factory.createPotion(PotionType.HEALING),
        factory.createPotion(PotionType.INVISIBILITY),
        factory.createPotion(PotionType.STRENGTH),
        factory.createPotion(PotionType.HEALING),
        factory.createPotion(PotionType.HEALING)
    );
    bottomShelf = List.of(
        factory.createPotion(PotionType.POISON),
        factory.createPotion(PotionType.POISON),
        factory.createPotion(PotionType.POISON),
        factory.createPotion(PotionType.HOLY_WATER),
        factory.createPotion(PotionType.HOLY_WATER)
    );
  }

  public final List<Potion> getTopShelf() {
    return List.copyOf(this.topShelf);
  }

  public final List<Potion> getBottomShelf() {
    return List.copyOf(this.bottomShelf);
  }

  public void drinkPotions() {
    LOGGER.info("Drinking top shelf potions\n");
    topShelf.forEach(Potion::drink);
    LOGGER.info("Drinking bottom shelf potions\n");
    bottomShelf.forEach(Potion::drink);
  }
}
```

In our scenario, a brave visitor enters the alchemist shop and drinks all the potions.

```java
public static void main(String[] args) {
    // create the alchemist shop with the potions
    var alchemistShop = new AlchemistShop();
    // a brave visitor enters the alchemist shop and drinks all the potions
    alchemistShop.drinkPotions();
}
```

Program output:

```
09:02:52.731 [main] INFO com.iluwatar.flyweight.AlchemistShop -- Drinking top shelf potions
09:02:52.733 [main] INFO com.iluwatar.flyweight.InvisibilityPotion -- You become invisible. (Potion=1395089624)
09:02:52.733 [main] INFO com.iluwatar.flyweight.InvisibilityPotion -- You become invisible. (Potion=1395089624)
09:02:52.733 [main] INFO com.iluwatar.flyweight.StrengthPotion -- You feel strong. (Potion=1450821318)
09:02:52.733 [main] INFO com.iluwatar.flyweight.HealingPotion -- You feel healed. (Potion=668849042)
09:02:52.733 [main] INFO com.iluwatar.flyweight.InvisibilityPotion -- You become invisible. (Potion=1395089624)
09:02:52.733 [main] INFO com.iluwatar.flyweight.StrengthPotion -- You feel strong. (Potion=1450821318)
09:02:52.733 [main] INFO com.iluwatar.flyweight.HealingPotion -- You feel healed. (Potion=668849042)
09:02:52.733 [main] INFO com.iluwatar.flyweight.HealingPotion -- You feel healed. (Potion=668849042)
09:02:52.733 [main] INFO com.iluwatar.flyweight.AlchemistShop -- Drinking bottom shelf potions
09:02:52.734 [main] INFO com.iluwatar.flyweight.PoisonPotion -- Urgh! This is poisonous. (Potion=2096057945)
09:02:52.734 [main] INFO com.iluwatar.flyweight.PoisonPotion -- Urgh! This is poisonous. (Potion=2096057945)
09:02:52.734 [main] INFO com.iluwatar.flyweight.PoisonPotion -- Urgh! This is poisonous. (Potion=2096057945)
09:02:52.734 [main] INFO com.iluwatar.flyweight.HolyWaterPotion -- You feel blessed. (Potion=1689843956)
09:02:52.734 [main] INFO com.iluwatar.flyweight.HolyWaterPotion -- You feel blessed. (Potion=1689843956)
```

## [When to Use the Flyweight Pattern in Java](https://java-design-patterns.com/patterns/flyweight/#when-to-use-the-flyweight-pattern-in-java)

The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all the following are true:

- The Flyweight pattern is particularly effective in Java applications that use a large number of objects.
- When storage costs are high due to the quantity of objects, Flyweight helps by sharing intrinsic data and managing extrinsic state separately.
- Most of the object state can be made extrinsic.
- Many groups of objects may be replaced by relatively few shared objects once the extrinsic state is removed.
- The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

## [Real-World Applications of Flyweight Pattern in Java](https://java-design-patterns.com/patterns/flyweight/#real-world-applications-of-flyweight-pattern-in-java)

- [java.lang.Integer#valueOf(int)](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf%28int%29) and similarly for Byte, Character and other wrapped types.
- Java’s String class utilizes the Flyweight pattern to manage string literals efficiently.
- GUI applications often use Flyweight for sharing objects like fonts or graphical components, thereby conserving memory and improving performance.

## [Benefits and Trade-offs of Flyweight Pattern](https://java-design-patterns.com/patterns/flyweight/#benefits-and-trade-offs-of-flyweight-pattern)

Benefits:

- Reduces the number of instances of an object, conserving memory.
- Centralizes state management, reducing the risk of inconsistent state.

Trade-offs:

- Increases complexity by adding the management layer for shared objects.
- Potential overhead in accessing shared objects if not well implemented.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/flyweight/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Often combined with Flyweight when the composites are shareable. Both are used to manage hierarchies and structures of objects.
- [State](https://java-design-patterns.com/patterns/state/): Can be used to manage state in a shared Flyweight object, distinguishing internal state (invariant) from external state (context-specific).

## [References and Credits](https://java-design-patterns.com/patterns/flyweight/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)

---

## [structural/marker-interface] Marker Interface
> 官方文档: https://java-design-patterns.com/patterns/marker-interface/

StructuralEncapsulationInterfacePolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/marker-interface/#also-known-as)

- Marker
- Tagging Interface

## [Intent of Marker Interface Design Pattern](https://java-design-patterns.com/patterns/marker-interface/#intent-of-marker-interface-design-pattern)

The Marker Interface pattern in Java is used to convey metadata about a class in a type-safe manner. Interfaces in Java that have no method declarations are known as marker interfaces. They are used to indicate that a class implementing such an interface possesses some special behavior or capability.

## [Detailed Explanation of Marker Interface Pattern with Real-World Examples](https://java-design-patterns.com/patterns/marker-interface/#detailed-explanation-of-marker-interface-pattern-with-real-world-examples)

Real-world example

> Consider a scenario in a Java library system where certain books are rare and need special handling procedures, such as restricted check-outs or specific storage conditions. Analogous to the Marker Interface pattern, we could have a marker interface called `RareBook`. Books in the library catalog that implement this interface are flagged as requiring special treatment but don't necessarily have different methods from other books.
>
> When a library staff member processes transactions or handles storage, the system checks if a book implements the `RareBook` interface. If it does, the system automatically enforces rules like "Do not allow check-outs for more than three days" or "Store in a temperature-controlled environment." This use of the marker interface effectively communicates special requirements without altering how books are generally managed, serving simply as a marker for special conditions.

In plain words

> The Marker Interface design pattern in Java uses empty interfaces to signal or define certain properties and behaviors of objects in a type-safe way, without requiring specific method implementations.

Wikipedia says

> The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.
>
> To use this pattern, a class implements a marker interface (also called tagging interface) which is an empty interface, and methods that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used.

Flowchart

![Marker Interface flowchart](https://java-design-patterns.com/assets/img/marker-interface-flowchart.68343009.png)

## [Programmatic Example of Marker Interface Pattern in Java](https://java-design-patterns.com/patterns/marker-interface/#programmatic-example-of-marker-interface-pattern-in-java)

The Marker Interface design pattern is a design pattern in computer science that is used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.

In the given Java code example, the Permission interface acts as a marker interface. Classes that implement this interface are marked as having special permissions. Let's break down the code to understand how this pattern is implemented.

First, we define the `Permission` interface. This interface doesn't have any methods, making it a marker interface.

```java
public interface Permission {
  // This is a marker interface and does not contain any methods
}
```

Next, we have two classes `Guard` and `Thief` that represent different types of characters in our application. The `Guard` class implements the `Permission` interface, indicating that objects of this class have special permissions.

```java
public class Guard implements Permission {
  public void enter() {
    // Implementation of enter method
  }
}
```

On the other hand, the `Thief` class does not implement the `Permission` interface, indicating that objects of this class do not have special permissions.

```java
public class Thief {
  public void steal() {
    // Implementation of steal method
  }

  public void doNothing() {
    // Implementation of doNothing method
  }
}
```

In the `main` method of the `App` class, we create instances of `Guard` and `Thief`. We then use the `instanceof` operator to check if these objects implement the `Permission` interface. If an object implements the `Permission` interface, it is allowed to perform certain actions. If not, it is restricted from performing those actions.

```java
public class App {
  public static void main(String[] args) {
    final var logger = LoggerFactory.getLogger(App.class);
    var guard = new Guard();
    var thief = new Thief();

    if (guard instanceof Permission) {
      guard.enter();
    } else {
      logger.info("You have no permission to enter, please leave this area");
    }

    if (thief instanceof Permission) {
      thief.steal();
    } else {
      thief.doNothing();
    }
  }
}
```

In this way, the Marker Interface pattern allows us to associate metadata (in this case, special permissions) with a class in a type-safe manner.

## [When to Use the Marker Interface Pattern in Java](https://java-design-patterns.com/patterns/marker-interface/#when-to-use-the-marker-interface-pattern-in-java)

Marker interfaces are applicable in scenarios where you want to impose a special behavior or capability on a class, but don't want to force the class to define specific methods. This pattern is commonly used to indicate that a class conforms to a particular contract without needing to implement methods.

## [Real-World Applications of Marker Interface Pattern in Java](https://java-design-patterns.com/patterns/marker-interface/#real-world-applications-of-marker-interface-pattern-in-java)

- java.io.Serializable: Classes that implement this interface are capable of being serialized by the Java runtime.
- java.lang.Cloneable: Classes that implement this interface can be cloned using the clone method in Java.

## [Benefits and Trade-offs of Marker Interface Pattern](https://java-design-patterns.com/patterns/marker-interface/#benefits-and-trade-offs-of-marker-interface-pattern)

Benefits:

- Enables type checking at compile time, allowing developers to use polymorphism to write cleaner and more flexible code.
- Allows the addition of metadata to classes without altering their actual behavior.

Trade-offs:

- Can lead to empty interfaces in the codebase, which some may consider as not clean or clear in purpose.
- Does not enforce any method implementations, which can lead to runtime errors if not properly handled.

## [References and Credits](https://java-design-patterns.com/patterns/marker-interface/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)

---

## [structural/money] Money
> 官方文档: https://java-design-patterns.com/patterns/money/

StructuralBusinessDomainEncapsulationImmutableAbout 2 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/money/#also-known-as)

- Monetary Value Object

## [Intent of Money Design Pattern](https://java-design-patterns.com/patterns/money/#intent-of-money-design-pattern)

Encapsulate monetary values and their associated currency in a domain-specific object.

## [Detailed Explanation of Money Pattern with Real-World Examples](https://java-design-patterns.com/patterns/money/#detailed-explanation-of-money-pattern-with-real-world-examples)

Real-world example

> Imagine an online gift card system, where each gift card holds a specific balance in a particular currency. Instead of just using a floating-point value for the balance, the system uses a Money object to precisely track the amount and currency. Whenever someone uses the gift card, it updates the balance with accurate calculations that avoid floating-point rounding errors, ensuring the domain logic stays consistent and accurate.

In plain words

> The Money pattern encapsulates both an amount and its currency, ensuring financial operations are precise, consistent, and maintainable.

Wikipedia says

> The Money design pattern encapsulates a monetary value and its currency, allowing for safe arithmetic operations and conversions while preserving accuracy and consistency in financial calculations.

Mind map

![Money Pattern Mind Map](https://java-design-patterns.com/assets/img/money-mind-map.094b705e.png)

Flowchart

![Money Pattern Flowchart](https://java-design-patterns.com/assets/img/money-flowchart.56f3d30e.png)

## [Programmatic Example of Money Pattern in Java](https://java-design-patterns.com/patterns/money/#programmatic-example-of-money-pattern-in-java)

In this example, we're creating a `Money` class to demonstrate how monetary values can be encapsulated along with their currency. This approach helps avoid floating-point inaccuracies, ensures arithmetic operations are handled consistently, and provides a clear domain-centric way of working with money.

```java
@AllArgsConstructor
@Getter
public class Money {
    private double amount;
    private String currency;

    public Money(double amnt, String curr) {
        this.amount = amnt;
        this.currency = curr;
    }

    private double roundToTwoDecimals(double value) {
        return Math.round(value * 100.0) / 100.0;
    }

    public void addMoney(Money moneyToBeAdded) throws CannotAddTwoCurrienciesException {
        if (!moneyToBeAdded.getCurrency().equals(this.currency)) {
            throw new CannotAddTwoCurrienciesException("You are trying to add two different currencies");
        }
        this.amount = roundToTwoDecimals(this.amount + moneyToBeAdded.getAmount());
    }

    public void subtractMoney(Money moneyToBeSubtracted) throws CannotSubtractException {
        if (!moneyToBeSubtracted.getCurrency().equals(this.currency)) {
            throw new CannotSubtractException("You are trying to subtract two different currencies");
        } else if (moneyToBeSubtracted.getAmount() > this.amount) {
            throw new CannotSubtractException("The amount you are trying to subtract is larger than the amount you have");
        }
        this.amount = roundToTwoDecimals(this.amount - moneyToBeSubtracted.getAmount());
    }

    public void multiply(int factor) {
        if (factor < 0) {
            throw new IllegalArgumentException("Factor must be non-negative");
        }
        this.amount = roundToTwoDecimals(this.amount * factor);
    }

    public void exchangeCurrency(String currencyToChangeTo, double exchangeRate) {
        if (exchangeRate < 0) {
            throw new IllegalArgumentException("Exchange rate must be non-negative");
        }
        this.amount = roundToTwoDecimals(this.amount * exchangeRate);
        this.currency = currencyToChangeTo;
    }
}
```

By encapsulating all money-related logic in a single class, we reduce the risk of mixing different currencies, improve clarity of the codebase, and facilitate future modifications such as adding new currencies or refining rounding rules. This pattern ultimately strengthens the domain model by treating money as a distinct concept rather than just another numeric value.

## [When to Use the Money Pattern](https://java-design-patterns.com/patterns/money/#when-to-use-the-money-pattern)

- When financial calculations or money manipulations are part of the business logic
- When precise handling of currency amounts is required to avoid floating-point inaccuracies
- When domain-driven design principles and strong typing are desired

## [Real-World Applications of Monad Pattern in Java](https://java-design-patterns.com/patterns/money/#real-world-applications-of-monad-pattern-in-java)

- JSR 354 (Java Money and Currency) library in Java
- Custom domain models in e-commerce and accounting systems

## [Benefits and Trade-offs of Money Pattern](https://java-design-patterns.com/patterns/money/#benefits-and-trade-offs-of-money-pattern)

Benefits

- Provides a single, type-safe representation of monetary amounts and currency
- Encourages encapsulation of related operations such as addition, subtraction, and formatting
- Avoids floating-point errors by using integers or specialized decimal libraries

Trade-offs

- Requires additional classes and infrastructure to handle currency conversions and formatting
- Might introduce performance overhead when performing large numbers of money operations

## [Related Design Patterns](https://java-design-patterns.com/patterns/money/#related-design-patterns)

- [Value Object](https://java-design-patterns.com/patterns/value-object/): Money is typically a prime example of a domain-driven design value object.

## [References and Credits](https://java-design-patterns.com/patterns/money/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [structural/parameter-object] Parameter Object
> 官方文档: https://java-design-patterns.com/patterns/parameter-object/

StructuralAbstractionCode simplificationDecouplingEncapsulationObject compositionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/parameter-object/#also-known-as)

- Argument Object

## [Intent of Parameter Object Design Pattern](https://java-design-patterns.com/patterns/parameter-object/#intent-of-parameter-object-design-pattern)

The Parameter Object pattern is a key Java design pattern aimed at improving code maintainability by reducing method complexity through encapsulation of parameters into a single object.

## [Detailed Explanation of Parameter Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/parameter-object/#detailed-explanation-of-parameter-object-pattern-with-real-world-examples)

Real-world example

> Imagine booking a travel package that includes a flight, hotel, and car rental. Instead of asking the customer to provide separate details for each component (flight details, hotel details, and car rental details) every time, a travel agent asks the customer to fill out a single comprehensive form that encapsulates all the necessary information:
>
> - Flight details: Departure city, destination city, departure date, return date.
> - Hotel details: Hotel name, check-in date, check-out date, room type.
> - Car rental details: Pickup location, drop-off location, rental dates, car type.
>
> In this analogy, the comprehensive form is the parameter object. It groups together all related details (parameters) into a single entity, making the booking process more streamlined and manageable. The travel agent (method) only needs to handle one form (parameter object) instead of juggling multiple pieces of information.

In plain words

> The Parameter Object pattern encapsulates multiple related parameters into a single object to simplify method signatures and enhance code maintainability.

[wiki.c2.com](http://wiki.c2.com/) says

> Replace the LongParameterList with a ParameterObject; an object or structure with data members representing the arguments to be passed in.

Mind map

![Parameter Object mind map](https://java-design-patterns.com/assets/img/parameter-object-mind-map.0fa5c501.png)

Flowchart

![Parameter Object flowchart](https://java-design-patterns.com/assets/img/parameter-object-flowchart.c936c6a1.png)

## [Programmatic Example of Parameter Object Pattern in Java](https://java-design-patterns.com/patterns/parameter-object/#programmatic-example-of-parameter-object-pattern-in-java)

The Parameter Object design pattern is a way to group multiple parameters into a single object. This simplifies method signatures and enhances code maintainability enabling Java developers to streamline complex method calls, focusing on cleaner and more maintainable Java code.

First, let's look at the `ParameterObject` class. This class encapsulates the parameters needed for the search operation. It uses [Builder pattern](https://java-design-patterns.com/patterns/builder/) to allow for easy creation of objects, even when there are many parameters.

```java
public class ParameterObject {

    private final String type;
    private final String sortBy;
    private final SortOrder sortOrder;

    private ParameterObject(Builder builder) {
        this.type = builder.type;
        this.sortBy = builder.sortBy;
        this.sortOrder = builder.sortOrder;
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    // getters and Builder class omitted for brevity
}
```

The `Builder` class inside `ParameterObject` provides a way to construct a `ParameterObject` instance. It has methods for setting each of the parameters, and a `build` method to create the `ParameterObject`.

```java
public static class Builder {

    private String type = "all";
    private String sortBy = "price";
    private SortOrder sortOrder = SortOrder.ASCENDING;

    public Builder withType(String type) {
        this.type = type;
        return this;
    }

    public Builder sortBy(String sortBy) {
        this.sortBy = sortBy;
        return this;
    }

    public Builder sortOrder(SortOrder sortOrder) {
        this.sortOrder = sortOrder;
        return this;
    }

    public ParameterObject build() {
        return new ParameterObject(this);
    }
}
```

The `SearchService` class has a `search()` method that takes a `ParameterObject` as a parameter. This method uses the parameters encapsulated in the `ParameterObject` to perform a search operation.

```java
public class SearchService {

    public String search(ParameterObject parameterObject) {
        return getQuerySummary(parameterObject.getType(), parameterObject.getSortBy(),
                parameterObject.getSortOrder());
    }

    // getQuerySummary method omitted for brevity
}
```

Finally, in the `App` class, we create a `ParameterObject` using its builder, and then pass it to the `search()` method of `SearchService`.

```java
public class App {

    public static void main(String[] args) {
        ParameterObject params = ParameterObject.newBuilder()
                .withType("sneakers")
                .sortBy("brand")
                .build();
        LOGGER.info(params.toString());
        LOGGER.info(new SearchService().search(params));
    }
}
```

This example demonstrates how the Parameter Object pattern can simplify method signatures and make the code more maintainable. It also shows how the pattern can be combined with the Builder pattern to make object creation more flexible and readable.

## [When to Use the Parameter Object Pattern in Java](https://java-design-patterns.com/patterns/parameter-object/#when-to-use-the-parameter-object-pattern-in-java)

- Methods require multiple parameters that logically belong together.
- There is a need to reduce the complexity of method signatures.
- The parameters may need to evolve over time, adding more properties without breaking existing method signatures.
- It’s beneficial to pass data through a method chain.

## [Parameter Object Pattern Java Tutorials](https://java-design-patterns.com/patterns/parameter-object/#parameter-object-pattern-java-tutorials)

- [Does Java have default parameters? (Daniel Olszewski)](http://dolszewski.com/java/java-default-parameters)

## [Real-World Applications of Parameter Object Pattern in Java](https://java-design-patterns.com/patterns/parameter-object/#real-world-applications-of-parameter-object-pattern-in-java)

- Java Libraries: Many Java frameworks and libraries use this pattern. For example, Java’s java.util.Calendar class has various methods where parameter objects are used to represent date and time components.
- Enterprise Applications: In large enterprise systems, parameter objects are used to encapsulate configuration data passed to services or API endpoints.

## [Benefits and Trade-offs of Parameter Object Pattern](https://java-design-patterns.com/patterns/parameter-object/#benefits-and-trade-offs-of-parameter-object-pattern)

Benefits:

- Encapsulation: Groups related parameters into a single object, promoting encapsulation.
- Maintainability: Reduces method signature changes when parameters need to be added or modified.
- Readability: Simplifies method signatures, making the code easier to read and understand.
- Reusability: Parameter objects can be reused across different methods, reducing redundancy.

Trade-offs:

- Overhead: Introducing parameter objects can add some overhead, especially for simple methods that do not benefit significantly from this abstraction.
- Complexity: The initial creation of parameter objects might add complexity, especially for beginners.

## [Related Patterns](https://java-design-patterns.com/patterns/parameter-object/#related-patterns)

- [Builder](https://java-design-patterns.com/patterns/builder/): Helps in creating complex objects step-by-step, often used in conjunction with parameter objects to manage the construction of these objects.
- [Composite](https://java-design-patterns.com/patterns/composite/): Sometimes used with parameter objects to handle hierarchical parameter data.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Can be used to create instances of parameter objects, particularly when different parameter combinations are needed.

## [References and Credits](https://java-design-patterns.com/patterns/parameter-object/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB)

---

## [structural/private-class-data] Private Class Data
> 官方文档: https://java-design-patterns.com/patterns/private-class-data/

StructuralAbstractionEncapsulationSecurityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/private-class-data/#also-known-as)

- Data Hiding
- Encapsulation

## [Intent of Private Class Data Design Pattern](https://java-design-patterns.com/patterns/private-class-data/#intent-of-private-class-data-design-pattern)

The Private Class Data design pattern in Java focuses on restricting access to the internal state of an object, enhancing security and reducing risks of data corruption through controlled method access.

## [Detailed Explanation of Private Class Data Pattern with Real-World Examples](https://java-design-patterns.com/patterns/private-class-data/#detailed-explanation-of-private-class-data-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Private Class Data pattern is the way a bank protects customer account information. Just like a class with private fields, a bank keeps sensitive data such as account balances, transaction history, and personal information private and only accessible through specific methods. Customers interact with their accounts through well-defined interfaces such as ATMs or online banking portals, which enforce security and validation rules, ensuring that unauthorized access or modifications are prevented. This controlled access mechanism ensures the integrity and security of the data, similar to how Private Class Data protects and manages access to class attributes in software design.

In plain words

> Private class data pattern prevents manipulation of data that is meant to be immutable by separating the data from the methods that use it into a class that maintains the data state.

Wikipedia says

> Private class data is a design pattern in computer programming used to encapsulate class attributes and their manipulation.

Mind map

![Private Class Data mind map](https://java-design-patterns.com/assets/img/private-class-data-mind-map.18d3218f.png)

Flowchart

![Private Class Data flowchart](https://java-design-patterns.com/assets/img/private-class-data-flowchart.f39b021f.png)

## [Programmatic Example of Private Class Data Pattern in Java](https://java-design-patterns.com/patterns/private-class-data/#programmatic-example-of-private-class-data-pattern-in-java)

Imagine you are cooking a stew for your family dinner. You want to stop your family members from tasting the stew while you're still preparing it. If they do, there might not be enough stew left for dinner.

First, we have a `Stew` class where its data is not protected by private class data, making the stew's ingredient mutable to class methods.

```java
@Slf4j
public class Stew {

  private int numPotatoes;
  private int numCarrots;
  private int numMeat;
  private int numPeppers;

  public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
    this.numPotatoes = numPotatoes;
    this.numCarrots = numCarrots;
    this.numMeat = numMeat;
    this.numPeppers = numPeppers;
  }

  public void mix() {
    LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
        numPotatoes, numCarrots, numMeat, numPeppers);
  }

  public void taste() {
    LOGGER.info("Tasting the stew");
    if (numPotatoes > 0) {
      numPotatoes--;
    }
    if (numCarrots > 0) {
      numCarrots--;
    }
    if (numMeat > 0) {
      numMeat--;
    }
    if (numPeppers > 0) {
      numPeppers--;
    }
  }
}
```

Now, we have `ImmutableStew` class, where its data is protected by `StewData` record. The methods in `ImmutableStew` are unable to manipulate the data of the `StewData` class.

```java
public record StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {}

@Slf4j
public class ImmutableStew {

  private final StewData data;

  public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
    data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers);
  }

  public void mix() {
    LOGGER
        .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
            data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers());
  }
}
```

Let's try creating an instance of each class and call their methods:

```java
public static void main(String[] args) {
    // stew is mutable
    var stew = new Stew(1, 2, 3, 4);
    stew.mix();
    stew.taste();
    stew.mix();

    // immutable stew protected with Private Class Data pattern
    var immutableStew = new ImmutableStew(2, 4, 3, 6);
    immutableStew.mix();
}
```

Program output:

```
08:00:08.210 [main] INFO com.iluwatar.privateclassdata.Stew -- Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers
08:00:08.212 [main] INFO com.iluwatar.privateclassdata.Stew -- Tasting the stew
08:00:08.212 [main] INFO com.iluwatar.privateclassdata.Stew -- Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers
08:00:08.213 [main] INFO com.iluwatar.privateclassdata.ImmutableStew -- Mixing the immutable stew we find: 2 potatoes, 4 carrots, 3 meat and 6 peppers
```

## [When to Use the Private Class Data Pattern in Java](https://java-design-patterns.com/patterns/private-class-data/#when-to-use-the-private-class-data-pattern-in-java)

Use the Private Class Data pattern when

- When you want to protect the integrity of an object’s state.
- When you need to limit the visibility of the internal data of an object to prevent unintended modification.
- In scenarios where multiple classes need to share access to some common data without exposing it directly.

## [Real-World Applications of Private Class Data Pattern in Java](https://java-design-patterns.com/patterns/private-class-data/#real-world-applications-of-private-class-data-pattern-in-java)

- Java Beans, where properties are accessed via getters and setters.
- In many Java libraries where the internal state is hidden from the user to ensure consistency and security.
- Enterprise applications where sensitive data needs to be protected from direct access.

## [Benefits and Trade-offs of Private Class Data Pattern](https://java-design-patterns.com/patterns/private-class-data/#benefits-and-trade-offs-of-private-class-data-pattern)

Benefits:

- Enhanced Security: Reduces the risk of unintended data corruption by encapsulating the data.
- Ease of Maintenance: Changes to the internal representation of data do not affect external code.
- Improved Abstraction: Users interact with a simplified interface without worrying about the complexities of data management.

Trade-offs:

- Performance Overhead: Additional method calls (getters/setters) can introduce slight performance overhead.
- Complexity: May increase the complexity of the class design due to the additional layer of methods for data access.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/private-class-data/#related-java-design-patterns)

- [Proxy](https://java-design-patterns.com/patterns/proxy/): Both patterns restrict access to the underlying object but Proxy controls access to the object itself, while Private Class Data controls access to the data.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensures that a class has only one instance and provides a global point of access to it; often used to manage shared data with controlled access.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Adds behavior to an object without altering its structure; can be combined with Private Class Data to manage additional state privately.

## [References and Credits](https://java-design-patterns.com/patterns/private-class-data/#references-and-credits)

- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3UJTZJk)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)

---

## [structural/proxy] Proxy 代理
> 官方文档: https://java-design-patterns.com/patterns/proxy/

StructuralDecouplingEncapsulationGang of FourLazy initializationProxySecurityWrappingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/proxy/#also-known-as)

- Surrogate

## [Intent of Proxy Design Pattern](https://java-design-patterns.com/patterns/proxy/#intent-of-proxy-design-pattern)

The Proxy pattern in Java provides a surrogate or placeholder to effectively control access to an object, enhancing security and resource management.

## [Detailed Explanation of Proxy Pattern with Real-World Examples](https://java-design-patterns.com/patterns/proxy/#detailed-explanation-of-proxy-pattern-with-real-world-examples)

Real-world example

> In a real-world scenario, consider a security guard at a gated community. The security guard acts as a proxy for the residents. When a visitor arrives, the guard checks the visitor's credentials and permissions before allowing them access to the community. If the visitor is authorized, the guard grants entry; if not, entry is denied. This ensures that only authorized individuals can access the community, much like a Proxy design pattern controls access to a specific object.

In plain words

> Utilizing the Java Proxy pattern, a class encapsulates the functionality of another, streamlining access control and operation efficiency.

Wikipedia says

> A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked.

Sequence diagram

![Proxy sequence diagram](https://java-design-patterns.com/assets/img/proxy-sequence-diagram.f44fe515.png)

## [Programmatic Example of Proxy Pattern in Java](https://java-design-patterns.com/patterns/proxy/#programmatic-example-of-proxy-pattern-in-java)

Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it.

First, we have the `WizardTower` interface and the `IvoryTower` class.

```java
public interface WizardTower {
  void enter(Wizard wizard);
}
```

```java
@Slf4j
public class IvoryTower implements WizardTower {
  public void enter(Wizard wizard) {
    LOGGER.info("{} enters the tower.", wizard);
  }
}
```

Then a simple `Wizard` class.

```java
public class Wizard {

  private final String name;

  public Wizard(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return name;
  }
}
```

Then we have the `WizardTowerProxy` to add access control to `WizardTower`.

```java
@Slf4j
public class WizardTowerProxy implements WizardTower {

  private static final int NUM_WIZARDS_ALLOWED = 3;
  private int numWizards;
  private final WizardTower tower;

  public WizardTowerProxy(WizardTower tower) {
    this.tower = tower;
  }

  @Override
  public void enter(Wizard wizard) {
    if (numWizards < NUM_WIZARDS_ALLOWED) {
      tower.enter(wizard);
      numWizards++;
    } else {
      LOGGER.info("{} is not allowed to enter!", wizard);
    }
  }
}
```

And here is the tower entering scenario.

```java
  public static void main(String[] args) {

    var proxy = new WizardTowerProxy(new IvoryTower());
    proxy.enter(new Wizard("Red wizard"));
    proxy.enter(new Wizard("White wizard"));
    proxy.enter(new Wizard("Black wizard"));
    proxy.enter(new Wizard("Green wizard"));
    proxy.enter(new Wizard("Brown wizard"));
}
```

Program output:

```
08:42:06.183 [main] INFO com.iluwatar.proxy.IvoryTower -- Red wizard enters the tower.
08:42:06.186 [main] INFO com.iluwatar.proxy.IvoryTower -- White wizard enters the tower.
08:42:06.186 [main] INFO com.iluwatar.proxy.IvoryTower -- Black wizard enters the tower.
08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Green wizard is not allowed to enter!
08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Brown wizard is not allowed to enter!
```

## [When to Use the Proxy Pattern in Java](https://java-design-patterns.com/patterns/proxy/#when-to-use-the-proxy-pattern-in-java)

Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable. Typically, the proxy pattern is used to

- Control access to another object
- Lazy initialization
- Implement logging
- Facilitate network connection
- Count references to an object
- Provide a local representation for an object that is in a different address space.

## [Real-World Applications of Proxy Pattern in Java](https://java-design-patterns.com/patterns/proxy/#real-world-applications-of-proxy-pattern-in-java)

- Virtual Proxies: In applications that need heavy resources like large images or complex calculations, virtual proxies can be used to instantiate objects only when needed.
- Remote Proxies: Used in remote method invocation (RMI) to manage interactions with remote objects.
- Protection Proxies: Control access to the original object to ensure proper authorization.
- [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html)
- [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/)
- Mocking frameworks [Mockito](https://site.mockito.org/), [Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/)
- [UIAppearance](https://developer.apple.com/documentation/uikit/uiappearance)

## [Benefits and Trade-offs of Proxy Pattern](https://java-design-patterns.com/patterns/proxy/#benefits-and-trade-offs-of-proxy-pattern)

Benefits:

- Controlled Access: Proxies control access to the real object, allowing for checks, logging, or other operations.
- Lazy Initialization: Proxies can delay the creation and initialization of resource-intensive objects until they are needed.
- Remote Proxy Handling: Simplifies interaction with remote objects by handling the network communication.

Trade-offs:

- Overhead: Adding a proxy introduces additional layers that might add overhead.
- Complexity: Increases the complexity of the system by adding more classes.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/proxy/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): The Adapter pattern changes the interface of an existing object, whereas Proxy provides the same interface as the original object.
- [Ambassador](https://java-design-patterns.com/patterns/ambassador/): Ambassador is similar to Proxy as it acts as an intermediary, especially in remote communications, enhancing access control and monitoring.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Both Decorator and Proxy patterns provide a level of indirection, but the Decorator pattern adds responsibilities to objects dynamically, while Proxy controls access.
- [Facade](https://java-design-patterns.com/patterns/facade/): Facade provides a simplified interface to a complex subsystem, while Proxy controls access to a particular object.

## [References and Credits](https://java-design-patterns.com/patterns/proxy/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)

---

## [structural/role-object] Role Object
> 官方文档: https://java-design-patterns.com/patterns/role-object/

StructuralAbstractionDecouplingExtensibilityInterfaceObject compositionPolymorphismRuntimeAbout 4 min

* * *

## [Intent of Role Object Design Pattern](https://java-design-patterns.com/patterns/role-object/#intent-of-role-object-design-pattern)

Efficiently assign dynamic roles to Java objects, enabling them to adapt behaviors and responsibilities on-the-fly, optimizing runtime flexibility.

## [Detailed Explanation of Role Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/role-object/#detailed-explanation-of-role-object-pattern-with-real-world-examples)

Real-world example

> Imagine a restaurant where staff members can take on different roles based on the needs of the moment. For example, an employee could be a server, a cashier, or a kitchen helper depending on the situation. When the restaurant is busy, a server might also take on the role of a cashier to help process payments quickly. Later, the same employee might assist in the kitchen during a rush. This flexibility allows the restaurant to dynamically allocate responsibilities to meet real-time demands, enhancing efficiency and customer satisfaction. The Role Object pattern in software mimics this by allowing objects to assume different roles and behaviors at runtime, providing similar flexibility and adaptability.

In plain words

> The Role Object pattern in Java models context-specific views through separate, dynamically managed role objects, enhancing modular design and runtime adaptability.

[wiki.c2.com](http://wiki.c2.com/) says

> Adapt an object to different client’s needs through transparently attached role objects, each one representing a role the object has to play in that client’s context. The object manages its role set dynamically. By representing roles as individual objects, different contexts are kept separate and system configuration is simplified.

Sequence diagram

![Role Object sequence diagram](https://java-design-patterns.com/assets/img/role-object-sequence-diagram.795cc32f.png)

## [Programmatic Example of Role Object Pattern in Java](https://java-design-patterns.com/patterns/role-object/#programmatic-example-of-role-object-pattern-in-java)

The Role Object design pattern is a pattern that suggests modeling context-specific views of an object as separate role objects. These role objects are dynamically attached to and removed from the core object. The resulting composite object structure, consisting of the core and its role objects, is called a subject. A subject often plays several roles and the same role is likely to be played by different subjects.

In the provided code, we have a `Customer` object that can play different roles such as `Borrower` and `Investor`. These roles are represented by `BorrowerRole` and `InvestorRole` classes respectively, which extend the `CustomerRole` class.

Here is the `Customer` class:

```java
public abstract class Customer {

  public abstract boolean addRole(Role role);

  public abstract boolean hasRole(Role role);

  public abstract boolean remRole(Role role);

  public abstract <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole);

  public static Customer newCustomer() {
    return new CustomerCore();
  }

  public static Customer newCustomer(Role... role) {
    var customer = newCustomer();
    Arrays.stream(role).forEach(customer::addRole);
    return customer;
  }
}
```

Here is the `BorrowerRole` class:

```java
@Getter
@Setter
public class BorrowerRole extends CustomerRole {

  private String name;

  public String borrow() {
    return String.format("Borrower %s wants to get some money.", name);
  }
}
```

In this class, the `borrow` method represents an operation specific to the `Borrower` role.

Similarly, the `InvestorRole` class represents the `Investor` role:

```java
@Getter
@Setter
public class InvestorRole extends CustomerRole {

  private String name;

  private long amountToInvest;

  public String invest() {
    return String.format("Investor %s has invested %d dollars", name, amountToInvest);
  }
}
```

In the `InvestorRole` class, the `invest` method represents an operation specific to the `Investor` role.

The `Customer` object can play either of these roles or both. This is demonstrated in the `main` function:

```java
public static void main(String[] args) {
    var customer = Customer.newCustomer(BORROWER, INVESTOR);

    LOGGER.info("New customer created : {}", customer);

    var hasBorrowerRole = customer.hasRole(BORROWER);
    LOGGER.info("Customer has a borrower role - {}", hasBorrowerRole);
    var hasInvestorRole = customer.hasRole(INVESTOR);
    LOGGER.info("Customer has an investor role - {}", hasInvestorRole);

    customer.getRole(INVESTOR, InvestorRole.class)
            .ifPresent(inv -> {
                inv.setAmountToInvest(1000);
                inv.setName("Billy");
            });
    customer.getRole(BORROWER, BorrowerRole.class)
            .ifPresent(inv -> inv.setName("Johny"));

    customer.getRole(INVESTOR, InvestorRole.class)
            .map(InvestorRole::invest)
            .ifPresent(LOGGER::info);

    customer.getRole(BORROWER, BorrowerRole.class)
            .map(BorrowerRole::borrow)
            .ifPresent(LOGGER::info);
}
```

In this class, a `Customer` object is created with both `Borrower` and `Investor` roles. The `hasRole` method is used to check if the `Customer` object has a specific role. The `getRole` method is used to get a reference to the role object, which is then used to perform role-specific operations.

Running the example outputs:

```
10:22:02.561 [main] INFO com.iluwatar.roleobject.ApplicationRoleObject -- New customer created : Customer{roles=[INVESTOR, BORROWER]}
10:22:02.564 [main] INFO com.iluwatar.roleobject.ApplicationRoleObject -- Customer has a borrower role - true
10:22:02.564 [main] INFO com.iluwatar.roleobject.ApplicationRoleObject -- Customer has an investor role - true
10:22:02.574 [main] INFO com.iluwatar.roleobject.ApplicationRoleObject -- Investor Billy has invested 1000 dollars
10:22:02.575 [main] INFO com.iluwatar.roleobject.ApplicationRoleObject -- Borrower Johny wants to get some money.
```

## [When to Use the Role Object Pattern in Java](https://java-design-patterns.com/patterns/role-object/#when-to-use-the-role-object-pattern-in-java)

- When an object needs to change its behavior dynamically based on its role.
- When multiple objects share common behaviors but should exhibit those behaviors differently based on their roles.
- In scenarios where roles can be added, removed, or changed at runtime.

## [Real-World Applications of Role Object Pattern in Java](https://java-design-patterns.com/patterns/role-object/#real-world-applications-of-role-object-pattern-in-java)

- User role management in applications where users can have different permissions and responsibilities.
- Game character roles where characters can take on different roles (e.g., healer, warrior, mage) dynamically.
- Workflow systems where tasks can be assigned different roles depending on the context.

## [Benefits and Trade-offs of Role Object Pattern](https://java-design-patterns.com/patterns/role-object/#benefits-and-trade-offs-of-role-object-pattern)

Benefits:

- Enhances software flexibility by enabling Java objects to dynamically switch roles, catering to evolving application needs.
- Enhances code maintainability by decoupling role-specific behaviors from core object logic.
- Facilitates the addition of new roles without modifying existing code.

Trade-offs:

- Increases complexity due to the need for managing multiple role objects.
- Potential performance overhead due to the dynamic nature of role assignment and behavior switching.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/role-object/#related-java-design-patterns)

- [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in dynamically changing an object's behavior, but Role Object focuses on roles that can be combined.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Both can add behaviors to objects, but Role Object allows for dynamic role switching rather than static enhancement.
- [State](https://java-design-patterns.com/patterns/state/): Manages state transitions similar to role changes, but Role Object deals more with behavioral roles rather than states.

## [References and Credits](https://java-design-patterns.com/patterns/role-object/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU)
- [Role-Based Access Control](https://amzn.to/3UJzL2l)
- [Dealing with Roles (Martin Fowler)](https://martinfowler.com/apsupp/roles.pdf)
- [Role Object (wiki.c2.com)](http://wiki.c2.com/?RoleObject)
- [The Role Object Pattern (Dirk Bäumer, Dirk Riehle, Wolf Siberski, and Martina Wulf)](https://hillside.net/plop/plop97/Proceedings/riehle.pdf)

---

## [structural/separated-interface] Separated Interface
> 官方文档: https://java-design-patterns.com/patterns/separated-interface/

StructuralAPI designDecouplingInterfaceAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/separated-interface/#also-known-as)

- API Segregation
- Client-Server Interface

## [Intent of Separated Interface Design Pattern](https://java-design-patterns.com/patterns/separated-interface/#intent-of-separated-interface-design-pattern)

The Separated Interface design pattern defines a client interface in a separate package from its implementation to allow for easier swapping of implementations and better separation of concerns.

## [Detailed Explanation of Separated Interface Pattern with Real-World Examples](https://java-design-patterns.com/patterns/separated-interface/#detailed-explanation-of-separated-interface-pattern-with-real-world-examples)

Real-world example

> Consider a restaurant where the menu (interface) is separate from the kitchen operations (implementation).
>
> In this analogy, the menu lists the dishes customers can order, without detailing how they are prepared. Different restaurants (or even different chefs within the same restaurant) can use their own recipes and methods to prepare the dishes listed on the menu. This separation allows the restaurant to update its menu or change its chefs without disrupting the overall dining experience. Similarly, in software, the Separated Interface pattern decouples the interface from its implementation, allowing changes and variations in the implementation without affecting the client code that relies on the interface.

In plain words

> Defines a client interface separate from its implementation to allow for flexible and interchangeable components.

Sequence diagram

![Separated Interface sequence diagram](https://java-design-patterns.com/assets/img/separated-interface-sequence-diagram.f1aa6e86.png)

## [Programmatic Example of Separated Interface Pattern in Java](https://java-design-patterns.com/patterns/separated-interface/#programmatic-example-of-separated-interface-pattern-in-java)

The Java Separated Interface design pattern is a crucial software architecture strategy that promotes separating the interface definition from its implementation, crucial for enhancing system flexibility and scalability. This allows the client to be completely unaware of the implementation, promoting loose coupling and enhancing flexibility.

In the given code, the `InvoiceGenerator` class is the client that uses the `TaxCalculator` interface to calculate tax. The `TaxCalculator` interface is implemented by two classes: `ForeignTaxCalculator` and `DomesticTaxCalculator`. These implementations are injected into the `InvoiceGenerator` class at runtime, demonstrating the Separated Interface pattern.

Let's break down the code:

First, we have the `TaxCalculator` interface. This interface defines a single method `calculate` that takes an amount and returns the calculated tax.

```java
public interface TaxCalculator {
  double calculate(double amount);
}
```

Next, we have two classes `ForeignTaxCalculator` and `DomesticTaxCalculator` that implement the `TaxCalculator` interface. These classes provide the concrete logic for tax calculation.

```java
public class ForeignTaxCalculator implements TaxCalculator {
  public static final double TAX_PERCENTAGE = 60;

  @Override
  public double calculate(double amount) {
    return amount * TAX_PERCENTAGE / 100.0;
  }
}

public class DomesticTaxCalculator implements TaxCalculator {
  public static final double TAX_PERCENTAGE = 20;

  @Override
  public double calculate(double amount) {
    return amount * TAX_PERCENTAGE / 100.0;
  }
}
```

The `InvoiceGenerator` class is the client that uses the `TaxCalculator` interface. It doesn't know about the concrete implementations of the `TaxCalculator` interface. It just knows that it has a `TaxCalculator` that can calculate tax.

```java
public class InvoiceGenerator {
  private final TaxCalculator taxCalculator;
  private final double amount;

  public InvoiceGenerator(double amount, TaxCalculator taxCalculator) {
    this.amount = amount;
    this.taxCalculator = taxCalculator;
  }

  public double getAmountWithTax() {
    return amount + taxCalculator.calculate(amount);
  }
}
```

Finally, in the `App` class, we create instances of `InvoiceGenerator` with different `TaxCalculator` implementations. This demonstrates how the Separated Interface pattern allows us to inject different implementations at runtime.

```java
public class App {
  public static final double PRODUCT_COST = 50.0;

  public static void main(String[] args) {
    var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST, new ForeignTaxCalculator());
    LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax());

    var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator());
    LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax());
  }
}
```

Console output:

```
11:38:53.208 [main] INFO com.iluwatar.separatedinterface.App -- Foreign Tax applied: 80.0
11:38:53.210 [main] INFO com.iluwatar.separatedinterface.App -- Domestic Tax applied: 60.0
```

In this way, the Separated Interface pattern allows us to decouple the interface of a component from its implementation, enhancing flexibility and maintainability and making it ideal for dynamic Java application environments.

## [When to Use the Separated Interface Pattern in Java](https://java-design-patterns.com/patterns/separated-interface/#when-to-use-the-separated-interface-pattern-in-java)

- Use when you want to decouple the interface of a component from its implementation.
- Particularly effective in large-scale Java systems, where separate teams handle different components, the Separated Interface pattern ensures seamless integration and easier maintenance.
- Ideal when the implementation might change over time or vary between deployments.

## [Separated Interface Pattern Tutorials](https://java-design-patterns.com/patterns/separated-interface/#separated-interface-pattern-tutorials)

- [Separated Interface Design Pattern Explained (Ram N Java)](https://www.youtube.com/watch?v=d3k-hOA7k2Y)

## [Real-World Applications of Separated Interface Pattern in Java](https://java-design-patterns.com/patterns/separated-interface/#real-world-applications-of-separated-interface-pattern-in-java)

- Java's JDBC (Java Database Connectivity) API separates the client interface from the database driver implementations.
- Remote Method Invocation (RMI) in Java, where the client and server interfaces are defined separately from the implementations.

## [Benefits and Trade-offs of Separated Interface Pattern](https://java-design-patterns.com/patterns/separated-interface/#benefits-and-trade-offs-of-separated-interface-pattern)

Benefits:

- Enhances flexibility by allowing multiple implementations to coexist.
- Facilitates testing by allowing mock implementations.
- Improves maintainability by isolating changes to specific parts of the code.

Trade-offs:

- Initial setup might be more complex.
- May lead to increased number of classes and interfaces in the codebase.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/separated-interface/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Adapts one interface to another, which can be used alongside Separated Interface to integrate different implementations.
- [Bridge](https://java-design-patterns.com/patterns/bridge/): Separates an object’s interface from its implementation, similar to Separated Interface but usually applied to larger-scale architectural issues.
- [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): Often used to inject the implementation of a separated interface, promoting loose coupling.

## [References and Credits](https://java-design-patterns.com/patterns/separated-interface/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Separated Interface (Martin Fowler)](https://www.martinfowler.com/eaaCatalog/separatedInterface.html)

---

## [structural/servant] Servant
> 官方文档: https://java-design-patterns.com/patterns/servant/

StructuralDecouplingInterfaceMessagingObject compositionResource managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/servant/#also-known-as)

- Helper

## [Intent of Servant Design Pattern](https://java-design-patterns.com/patterns/servant/#intent-of-servant-design-pattern)

The Servant pattern is used to perform specific operations for a group of objects without changing the classes of the elements on which it operates.

## [Detailed Explanation of Servant Pattern with Real-World Examples](https://java-design-patterns.com/patterns/servant/#detailed-explanation-of-servant-pattern-with-real-world-examples)

Real-world example

> In a restaurant, a waiter (Servant) serves multiple tables (objects) by taking orders, delivering food, and handling payments. The waiter provides these common services without altering the fundamental nature of the tables or customers, allowing the restaurant to efficiently manage customer service while keeping the roles of the tables and customers unchanged.

In plain words

> The Java Servant pattern effectively centralizes common functionality for multiple classes, enabling decoupled and reusable operations in software development without altering the original classes, promoting efficient Java design practices.

Wikipedia says

> In software engineering, the servant pattern defines an object used to offer some functionality to a group of classes without defining that functionality in each of them. A Servant is a class whose instance (or even just class) provides methods that take care of a desired service, while objects for which (or with whom) the servant does something, are taken as parameters.

Sequence diagram

![Servant sequence diagram](https://java-design-patterns.com/assets/img/servant-sequence-diagram.89c2b655.png)

## [Programmatic Example of Servant Pattern in Java](https://java-design-patterns.com/patterns/servant/#programmatic-example-of-servant-pattern-in-java)

The Servant design pattern is a behavioral design pattern that defines a class that provides some sort of service to a group of classes. This pattern is particularly useful when these classes lack some common functionality that can't be added to the superclass. The Servant class brings this common functionality to a group of classes.

In the provided code, we have a `Servant` class that provides services to the `Royalty` class. The `Servant` class has methods like `feed()`, `giveWine()`, and `giveCompliments()` which are services provided to the `Royalty` class.

Here is the `Servant` class:

```java
public class Servant {

    public String name;

    public Servant(String name) {
        this.name = name;
    }

    public void feed(Royalty r) {
        r.getFed();
    }

    public void giveWine(Royalty r) {
        r.getDrink();
    }

    public void giveCompliments(Royalty r) {
        r.receiveCompliments();
    }

    public boolean checkIfYouWillBeHanged(List<Royalty> tableGuests) {
        return tableGuests.stream().allMatch(Royalty::getMood);
    }
}
```

The `Royalty` class is an interface that is implemented by the classes that use the services of the `Servant`. Here is a simplified version of the `Royalty` interface:

```java
public interface Royalty {
    void getFed();

    void getDrink();

    void receiveCompliments();

    void changeMood();

    boolean getMood();
}
```

The `App` class uses the `Servant` to provide services to the `Royalty` objects. Here is a simplified version of the `App` class:

```java
public class App {

    private static final Servant jenkins = new Servant("Jenkins");
    private static final Servant travis = new Servant("Travis");

    public static void main(String[] args) {
        scenario(jenkins, 1);
        scenario(travis, 0);
    }

    public static void scenario(Servant servant, int compliment) {
        var k = new King();
        var q = new Queen();

        var guests = List.of(k, q);

        servant.feed(k);
        servant.feed(q);
        servant.giveWine(k);
        servant.giveWine(q);
        servant.giveCompliments(guests.get(compliment));

        guests.forEach(Royalty::changeMood);

        if (servant.checkIfYouWillBeHanged(guests)) {
            LOGGER.info("{} will live another day", servant.name);
        } else {
            LOGGER.info("Poor {}. His days are numbered", servant.name);
        }
    }
}
```

Running the application produces:

```
09:10:38.795 [main] INFO com.iluwatar.servant.App -- Jenkins will live another day
09:10:38.797 [main] INFO com.iluwatar.servant.App -- Poor Travis. His days are numbered
```

In this example, the `Servant` class provides services to the `Royalty` objects. The `Servant` class doesn't know about the specific implementation of the `Royalty` objects, it only knows that it can provide certain services to them. This is a good example of the Servant design pattern.

## [When to Use the Servant Pattern in Java](https://java-design-patterns.com/patterns/servant/#when-to-use-the-servant-pattern-in-java)

- Use the Servant pattern when you need to provide a common functionality to a group of classes without polluding their class definitions, perfect for enhancing Java application architecture.
- Suitable when the operations performed on the objects are not the primary responsibility of the objects themselves.

## [Real-World Applications of Servant Pattern in Java](https://java-design-patterns.com/patterns/servant/#real-world-applications-of-servant-pattern-in-java)

- In GUI applications to handle operations like rendering or hit-testing which are common across different UI components.
- In games where various entities (like players, enemies, or items) need common behavior such as movement or collision detection.
- Logging or auditing functionalities that are required across multiple business objects.

## [Benefits and Trade-offs of Servant Pattern](https://java-design-patterns.com/patterns/servant/#benefits-and-trade-offs-of-servant-pattern)

Benefits:

- Promotes code reuse and separation of concerns by decoupling the operations from the objects they operate on.
- Reduces code duplication by centralizing the shared functionality.

Trade-offs:

- Can lead to an increase in the number of classes, potentially making the system harder to understand.
- May introduce tight coupling between the Servant and the classes it serves if not designed carefully.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/servant/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): The Servant pattern is similar to the Adapter pattern in that both provide a way to work with classes without modifying them, but the Servant pattern focuses on providing additional behavior to multiple classes rather than adapting one interface to another.
- [Facade](https://java-design-patterns.com/patterns/facade/): Both patterns provide a simplified interface to a set of functionalities, but the Servant pattern is typically used for adding functionalities to a group of classes, while the Facade pattern hides the complexities of a subsystem.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The Servant pattern can be used in conjunction with the Strategy pattern to define operations that apply to multiple classes.
- View Helper: The View Helper pattern is related as it also centralizes common functionality, but it focuses on separating presentation logic from business logic in web applications.

## [References and Credits](https://java-design-patterns.com/patterns/servant/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU)

---

## [structural/service-locator] Service Locator
> 官方文档: https://java-design-patterns.com/patterns/service-locator/

StructuralDecouplingDependency managementEnterprise patternsInstantiationAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/service-locator/#also-known-as)

- Service Registry

## [Intent of Service Locator Design Pattern](https://java-design-patterns.com/patterns/service-locator/#intent-of-service-locator-design-pattern)

The Java Service Locator pattern provides a method to decouple Java clients and services by using a central service registry.

## [Detailed Explanation of Service Locator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/service-locator/#detailed-explanation-of-service-locator-pattern-with-real-world-examples)

Real-world example

> In a large hotel, the concierge desk acts as a Service Locator. When guests need a service, such as booking a restaurant reservation, finding transportation, or arranging a city tour, they do not directly seek out each service themselves. Instead, they go to the concierge desk, which locates and arranges the required services. This way, the guests are decoupled from the service providers and can rely on a central point to handle their requests, ensuring convenience and efficiency.

In plain words

> The Service Locator pattern centralizes the logic for locating services, thereby decoupling clients from the concrete implementations of these services.

Wikipedia says

> The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the "service locator", which on request returns the information necessary to perform a certain task. Proponents of the pattern say the approach simplifies component-based applications where all dependencies are cleanly listed at the beginning of the whole application design, consequently making traditional dependency injection a more complex way of connecting objects. Critics of the pattern argue that it is an antipattern which obscures dependencies and makes software harder to test.

Sequence diagram

![Service Locator sequence diagram](https://java-design-patterns.com/assets/img/service-locator-sequence-diagram.fa46611d.png)

## [Programmatic Example of Service Locator Pattern in Java](https://java-design-patterns.com/patterns/service-locator/#programmatic-example-of-service-locator-pattern-in-java)

The Service Locator design pattern is used to abstract the processes involved in obtaining a service. It uses a central registry, the "service locator", which returns the necessary information to perform a task upon request. This Java design pattern is particularly useful in enterprise Java applications where services need centralized management.

In this example, we have a `Service` interface and a `ServiceLocator` class. The `Service` interface defines the methods that all services must implement. The `ServiceLocator` class is responsible for retrieving and caching these services.

```java
public interface Service {
    String getName();

    int getId();

    void execute();
}
```

The `Service` interface defines three methods: `getName()`, `getId()`, and `execute()`. Any class that implements this interface must provide an implementation for these methods.

```java
public class App {

    public static final String JNDI_SERVICE_A = "jndi/serviceA";
    public static final String JNDI_SERVICE_B = "jndi/serviceB";

    public static void main(String[] args) {
        // Get the service from the ServiceLocator
        var service = ServiceLocator.getService(JNDI_SERVICE_A);
        // Execute the service
        service.execute();
        // Get another service from the ServiceLocator
        service = ServiceLocator.getService(JNDI_SERVICE_B);
        // Execute the service
        service.execute();
        // Get the service from the ServiceLocator again
        service = ServiceLocator.getService(JNDI_SERVICE_A);
        // Execute the service
        service.execute();
        // Get the service from the ServiceLocator again
        service = ServiceLocator.getService(JNDI_SERVICE_A);
        // Execute the service
        service.execute();
    }
}
```

In the `App` class, we use the `ServiceLocator` to get services by their names and then execute them. The `ServiceLocator` handles the details of looking up and caching the services. This way, the `App` class is decoupled from the concrete implementations of the services.

Here is the output from running the example:

```
15:39:51.417 [main] INFO com.iluwatar.servicelocator.InitContext -- Looking up service A and creating new service for A
15:39:51.419 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56
15:39:51.420 [main] INFO com.iluwatar.servicelocator.InitContext -- Looking up service B and creating new service for B
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceB is now executing with id 196
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceCache -- (cache call) Fetched service jndi/serviceA(56) from cache... !
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceCache -- (cache call) Fetched service jndi/serviceA(56) from cache... !
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56
```

## [When to Use the Service Locator Pattern in Java](https://java-design-patterns.com/patterns/service-locator/#when-to-use-the-service-locator-pattern-in-java)

- Use when you want to decouple service creation from client classes to reduce dependencies and improve code maintainability.
- Applicable in large-scale enterprise applications where multiple services are used and dependencies need to be managed centrally.
- Suitable when service instances need to be reused or shared among multiple clients.

## [Real-World Applications of Service Locator Pattern in Java](https://java-design-patterns.com/patterns/service-locator/#real-world-applications-of-service-locator-pattern-in-java)

- Enterprise Java applications often use Service Locator to manage business services.
- Spring Framework uses a similar concept with its BeanFactory and ApplicationContext for dependency injection.
- EJB (Enterprise JavaBeans) uses the Service Locator pattern to find and access EJB components.

## [Benefits and Trade-offs of Service Locator Pattern](https://java-design-patterns.com/patterns/service-locator/#benefits-and-trade-offs-of-service-locator-pattern)

Benefits:

- Decouples client and service classes, reducing code dependencies.
- Centralizes service management, making it easier to configure and manage services.
- Promotes reuse of service instances, which can improve performance and resource utilization.

Trade-offs:

- Can introduce a single point of failure if the Service Locator itself fails.
- May add complexity to the codebase, especially in terms of configuration and maintenance.
- Potential performance overhead due to the lookup mechanism.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/service-locator/#related-java-design-patterns)

- [Factory](https://java-design-patterns.com/patterns/factory/): Both patterns deal with object creation but Service Locator focuses on locating services while Factory focuses on creating them.
- [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): An alternative to Service Locator that injects dependencies directly into clients rather than having clients request them from a locator.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Service Locator often uses Singleton pattern to ensure a single instance of the locator.

## [References and Credits](https://java-design-patterns.com/patterns/service-locator/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Pattern-Oriented Software Architecture Volume 3: Patterns for Resource Management](https://amzn.to/4bnBcKZ)

---

## [structural/session-facade] Session Facade
> 官方文档: https://java-design-patterns.com/patterns/session-facade/

StructuralAPI designAbstractionArchitectureBusinessDecouplingEnterprise patternsFacadeLayered architectureSession managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/session-facade/#also-known-as)

- Remote Facade

## [Intent of Session Facade Design Pattern](https://java-design-patterns.com/patterns/session-facade/#intent-of-session-facade-design-pattern)

Provide a simplified interface to a complex subsystem, reducing complexity and coupling between client and business logic in enterprise Java applications.

## [Detailed Explanation of Session Facade Pattern with Real-World Examples](https://java-design-patterns.com/patterns/session-facade/#detailed-explanation-of-session-facade-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Session Facade pattern is a hotel concierge service. Guests (clients) don't directly interact with various departments like housekeeping, kitchen, transport services, or maintenance. Instead, they interact with the concierge (the facade), who simplifies these interactions. When a guest requests services like room cleaning, dinner reservations, or taxi bookings, the concierge handles communication with multiple hotel departments behind the scenes, providing a simplified and unified interface to the guest, reducing complexity and enhancing guest satisfaction.

In plain words

> Session Facade provides a simplified interface to complex business logic in Java applications, reducing client complexity and minimizing network overhead by encapsulating interactions within a single session component.

Sequence diagram

![Session Facade sequence diagram](https://java-design-patterns.com/assets/img/session-facade-sequence-diagram.9230d6fe.png)

## [Programmatic Example of Session Facade Pattern in Java](https://java-design-patterns.com/patterns/session-facade/#programmatic-example-of-session-facade-pattern-in-java)

The Session Facade pattern is a structural design pattern that provides a simplified interface to complex subsystems, making the system easier for clients to interact with. It is especially useful when a client needs access to multiple underlying services without needing to understand their internal complexities.

In the context of an e-commerce website, consider a scenario where users browse products, manage their shopping carts, place orders, and process payments. Rather than directly interacting with each subsystem individually (such as the cart, order, and payment systems), a client can communicate through a single unified Session Facade interface.

### [Example Scenario:](https://java-design-patterns.com/patterns/session-facade/#example-scenario)

In this example, the `ShoppingFacade` class simplifies client interactions with three services: the `CartService`, `OrderService`, and `PaymentService`. The client uses the facade to perform high-level operations like adding products to the cart, placing an order, and choosing a payment method, without needing to know the underlying details.

Here's a simplified Java program demonstrating this pattern:

```java
public class App {
    public static void main(String[] args) {
        ShoppingFacade shoppingFacade = new ShoppingFacade();
        shoppingFacade.addToCart(1);
        shoppingFacade.order();
        shoppingFacade.selectPaymentMethod("cash");
    }
}
```

The `ShoppingFacade` serves as a centralized point of interaction for various shopping-related operations, thereby reducing direct coupling between client code and individual subsystem services:

```java
public class ShoppingFacade {

    private final CartService cartService;
    private final OrderService orderService;
    private final PaymentService paymentService;

    public ShoppingFacade() {
        Map<Integer, Product> productCatalog = new HashMap<>();
        productCatalog.put(1, new Product(1, "Wireless Mouse", 25.99, "Ergonomic wireless mouse with USB receiver."));
        productCatalog.put(2, new Product(2, "Gaming Keyboard", 79.99, "RGB mechanical gaming keyboard with programmable keys."));
        Map<Integer, Product> cart = new HashMap<>();
        cartService = new CartService(cart, productCatalog);
        orderService = new OrderService(cart);
        paymentService = new PaymentService();
    }

    public Map<Integer, Product> getCart() {
        return this.cartService.getCart();
    }

    public void addToCart(int productId) {
        this.cartService.addToCart(productId);
    }

    public void removeFromCart(int productId) {
        this.cartService.removeFromCart(productId);
    }

    public void order() {
        this.orderService.order();
    }

    public Boolean isPaymentRequired() {
        double total = this.orderService.getTotal();
        if (total==0.0) {
            LOGGER.info("No payment required");
            return false;
        }
        return true;
    }

    public void processPayment(String method) {
        Boolean isPaymentRequired = isPaymentRequired();
        if (Boolean.TRUE.equals(isPaymentRequired)) {
            paymentService.selectPaymentMethod(method);
        }
    }
}
```

### [Console Output](https://java-design-patterns.com/patterns/session-facade/#console-output)

When running the provided example (App.main()), the output might look similar to:

```
19:43:17.883 [main] INFO com.iluwatar.sessionfacade.CartService -- ID: 1
Name: Wireless Mouse
Price: $25.99
Description: Ergonomic wireless mouse with USB receiver. successfully added to the cart
19:43:17.910 [main] INFO com.iluwatar.sessionfacade.OrderService -- Client has chosen to order [ID: 1\
```\
\
This simplified example demonstrates the essence of the Session Facade pattern. Your actual implementation may vary based on the specific needs of your application.\
\
## [When to Use the Session Facade Pattern in Java](https://java-design-patterns.com/patterns/session-facade/#when-to-use-the-session-facade-pattern-in-java)\
\
- When dealing with complex enterprise applications containing multiple business objects.\
- To provide simplified API calls to clients, hiding the underlying complexity.\
- When seeking improved performance and reduced network calls between clients and servers.\
\
## [Real-World Applications of Server Session Pattern in Java](https://java-design-patterns.com/patterns/session-facade/#real-world-applications-of-server-session-pattern-in-java)\
\
- Java EE applications utilizing Enterprise JavaBeans (EJB) as session facades to encapsulate business logic.\
- Spring-based applications using services as session facades to simplify interactions between controllers and repositories.\
\
## [Benefits and Trade-offs of Server Session Pattern](https://java-design-patterns.com/patterns/session-facade/#benefits-and-trade-offs-of-server-session-pattern)\
\
Benefits:\
\
- Reduces complexity by providing a simpler interface to a subsystem.\
- Improves performance by minimizing network traffic and reducing remote calls.\
- Enhances modularity and maintainability by clearly separating business logic and client interactions.\
\
Trade-offs:\
\
- Can introduce additional layers that might increase initial complexity.\
- Risk of creating overly broad facades that violate single responsibility principles.\
\
## [Related Java Design Patterns](https://java-design-patterns.com/patterns/session-facade/#related-java-design-patterns)\
\
- [Data Transfer Object (DTO)](https://java-design-patterns.com/patterns/data-transfer-object/): Often used together, Session Facade simplifies data transfer by utilizing DTOs to encapsulate data passed between client and server.\
- [Facade](https://java-design-patterns.com/patterns/facade/): Session Facade is a specialized version of the Facade pattern, applied specifically in enterprise systems to manage business logic and remote interactions.\
\
## [References and Credits](https://java-design-patterns.com/patterns/session-facade/#references-and-credits)\
\
- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)\
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)\
- [Real World Java EE Patterns-Rethinking Best Practices](https://amzn.to/3EvkzS8)\
- [Remote Facade (Martin Fowler)](https://martinfowler.com/eaaCatalog/remoteFacade.html)

---

## [structural/spatial-partition] Spatial Partition
> 官方文档: https://java-design-patterns.com/patterns/spatial-partition/

StructuralGame programmingOptimizationPerformanceResource managementScalabilityAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/spatial-partition/#also-known-as)

- Space Partitioning
- Spatial Indexing

## [Intent of Spatial Partition Design Pattern](https://java-design-patterns.com/patterns/spatial-partition/#intent-of-spatial-partition-design-pattern)

Efficiently organize a large number of objects in space to optimize queries and operations.

## [Detailed Explanation of Spatial Partition Pattern with Real-World Examples](https://java-design-patterns.com/patterns/spatial-partition/#detailed-explanation-of-spatial-partition-pattern-with-real-world-examples)

Real-world example

> Imagine managing a large warehouse where items are constantly being moved, added, or retrieved. To optimize the search for specific items and manage space efficiently, the warehouse is divided into different sections or zones. Each zone contains shelves, and each shelf holds a specific category of items.
>
> This setup is analogous to the Spatial Partition design pattern in software, where a large space (the warehouse) is divided into manageable parts (zones) to optimize operations like searching for an item or checking inventory (spatial queries). By organizing the warehouse this way, it becomes easier to locate and manage items, much like how spatial partitioning helps in efficiently managing and querying objects in a large spatial environment.

In plain words

> The Spatial Partition design pattern organizes objects in a defined space to optimize spatial queries and operations.

Wikipedia says

> The Spatial Partition design pattern, also known as Space Partitioning, involves dividing a space into non-overlapping regions to manage and query spatial data efficiently. This method is widely used in computer graphics, particularly for optimizing tasks like collision detection, ray tracing, and rendering large scenes with numerous objects. Organizing objects into hierarchical structures like BSP trees, Quadtrees, or Octrees under the Spatial Partition pattern allows for more efficient spatial queries, a significant advantage in Java applications for complex graphic rendering and collision detection.
>
> For example, in ray tracing, space partitioning helps quickly determine the objects a ray might intersect by narrowing down the search space, leading to faster rendering times. Similarly, in game development, Quadtrees can efficiently manage 2D game environments by segmenting the space into smaller regions, facilitating quicker collision detection and rendering.

Flowchart

![Spatial Partition flowchart](https://java-design-patterns.com/assets/img/spatial-partition-flowchart.396e7ef2.png)

## [Programmatic Example of Spatial Partition Pattern in Java](https://java-design-patterns.com/patterns/spatial-partition/#programmatic-example-of-spatial-partition-pattern-in-java)

The Spatial Partition design pattern in Java is a strategic approach for handling multiple objects in expansive game worlds or detailed simulation environments, boosting query efficiency and operational speed. It allows us to efficiently manage these objects and perform operations like collision detection or range queries. The pattern works by dividing the space into smaller, manageable regions, and each object is associated with the region it belongs to. This way, we can limit our operations to a specific region, instead of checking every object against every other object.

In the provided code, we have an example of a war game where the positions of players are updated every frame. The simple way to handle interactions on the battlefield is to check each player's position against every other player's position. However, this approach includes a lot of unnecessary checks between players who are too far apart to influence each other. The Spatial Partition pattern can help us optimize this operation.

Here's a simplified version of the code with added comments to explain the Spatial Partition pattern:

```java
// This is the simple way to handle interactions on the battlefield
// It includes a lot of unnecessary checks between players who are too far apart to influence each other
public void handleMeLee(Unit units[], int numUnits) {
    for (var a = 0; a < numUnits - 1; a++) {
        for (var b = a + 1; b < numUnits; b++) {
            // We check if two units are at the same position
            if (units[a].position() == units[b].position()) {
                // If they are, we handle the attack
                handleAttack(units[a], units[b]);
            }
        }
    }
}
```

The above code has a time complexity of O(n^2), which can be quite inefficient when the number of units is large. The Spatial Partition pattern can help us reduce this complexity.

In the Spatial Partition pattern, we would divide the battlefield into smaller regions, and each unit would be associated with the region it belongs to. When we need to check for interactions, we would only need to check the units within the same region, significantly reducing the number of checks.

Here's a simplified version of how this might look:

```java
// We first create a spatial partition (e.g., a grid or a quadtree)
SpatialPartition partition = new SpatialPartition();

// We then add each unit to the partition
for (Unit unit : units) {
    partition.add(unit);
}

// When we need to handle interactions, we only check the units within the same region
for (Unit unit : units) {
    List<Unit> nearbyUnits = partition.getUnitsInSameRegion(unit);
    for (Unit nearbyUnit : nearbyUnits) {
        if (unit.position() == nearbyUnit.position()) {
            handleAttack(unit, nearbyUnit);
        }
    }
}
```

In this code, `SpatialPartition` is a class that represents the spatial partition. The `add` method is used to add a unit to the partition, and the `getUnitsInSameRegion` method is used to get all units in the same region as a given unit. The exact implementation of these methods would depend on the specific type of spatial partition used (e.g., grid, quadtree, etc.).

This way, we can reduce the time complexity of finding the units within a certain range from O(n^2) to O(nlogn), decreasing the computations required significantly in case of a large number of units.

## [When to Use the Spatial Partition Pattern in Java](https://java-design-patterns.com/patterns/spatial-partition/#when-to-use-the-spatial-partition-pattern-in-java)

- Use when managing a large number of objects in a spatial environment, such as in games or simulations.
- Useful for optimizing spatial queries like finding nearby objects or detecting collisions.

## [Spatial Partition Pattern Java Tutorials](https://java-design-patterns.com/patterns/spatial-partition/#spatial-partition-pattern-java-tutorials)

- [Coding Challenge #98.1: Quadtree - Part 1 (The Coding Train)](https://www.youtube.com/watch?v=OJxEcs0w_kE)

## [Real-World Applications of Spatial Partition Pattern in Java](https://java-design-patterns.com/patterns/spatial-partition/#real-world-applications-of-spatial-partition-pattern-in-java)

- Quadtree in 2D games for collision detection.
- Octree in 3D environments for rendering and physics calculations.
- KD-tree in spatial databases for efficient range searches.

## [Benefits and Trade-offs of Spatial Partition Pattern](https://java-design-patterns.com/patterns/spatial-partition/#benefits-and-trade-offs-of-spatial-partition-pattern)

Benefits:

- Significant performance improvements in spatial queries.
- Reduces the complexity of managing objects in large spaces.
- Scales well with an increasing number of objects.

Trade-offs:

- Increased complexity in implementation.
- May require periodic rebalancing or restructuring as objects move.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/spatial-partition/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Helps manage hierarchical data structures like trees used in spatial partitioning.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used to manage memory efficiently for objects stored in spatial partitions.

## [References and Credits](https://java-design-patterns.com/patterns/spatial-partition/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/3K96fOn)
- [Introduction to Algorithms](https://amzn.to/4aC5hW0)
- [Real-Time Collision Detection](https://amzn.to/4as9gnW)
- [Spatial Partition (Game Programming Patterns)](http://gameprogrammingpatterns.com/spatial-partition.html)

---

## [structural/special-case] Special Case
> 官方文档: https://java-design-patterns.com/patterns/special-case/

StructuralAbstractionCode simplificationDecouplingError handlingPolymorphismRuntimeAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/special-case/#also-known-as)

- Exceptional Case

## [Intent of Special Case Design Pattern](https://java-design-patterns.com/patterns/special-case/#intent-of-special-case-design-pattern)

The Special Case design pattern in Java offers a robust framework for addressing unique or exceptional conditions in software development without complicating the main codebase.

## [Detailed Explanation of Special Case Pattern with Real-World Examples](https://java-design-patterns.com/patterns/special-case/#detailed-explanation-of-special-case-pattern-with-real-world-examples)

Real-world example

> Consider a toll booth system on a highway. Normally, vehicles pass through the booth, and the system charges a toll based on the vehicle type. However, there are special cases: emergency vehicles like ambulances and fire trucks, which should not be charged.
>
> For instance, in a toll management system, the Special Case pattern facilitates separate handling for emergency vehicles, ensuring a streamlined toll process without additional checks. The emergency vehicle class would override the toll calculation method to ensure no charge is applied, encapsulating this special behavior without cluttering the main toll calculation logic with conditional checks. This keeps the codebase clean and ensures the special case is handled consistently.

In plain words

> The Special Case design pattern encapsulates and isolates exceptional conditions and specific scenarios to simplify the main code logic and enhance maintainability.

In [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) Martin Fowler says:

> If you’ll pardon the unresistable pun, I see [Null Object](https://java-design-patterns.com/patterns/null-object/) as special case of Special Case.

Sequnce diagram

![Special Case sequence diagram](https://java-design-patterns.com/assets/img/special-case-sequence-diagram.6d878ffd.png)

## [Programmatic Example of Special Case Pattern in Java](https://java-design-patterns.com/patterns/special-case/#programmatic-example-of-special-case-pattern-in-java)

The Special Case Pattern is a software design pattern that is used to handle a specific, often uncommon, case separately from the general case in the code. This pattern is useful when a class has behavior that requires conditional logic based on its state. Instead of cluttering the class with conditional logic, we can encapsulate the special behavior in a subclass.

In an e-commerce system, the presentation layer relies on the application layer to generate a specific view model. There is a successful scenario where the receipt view model includes actual purchase data, along with a few failure scenarios.

The `Db` class is a singleton that holds data for users, accounts, and products. It provides methods to seed data into the database and find data in the database.

```java
@RequiredArgsConstructor
@Getter
public class Db {
    // Singleton instance of Db
    private static Db instance;

    // Maps to hold data
    private Map<String, User> userName2User;
    private Map<User, Account> user2Account;
    private Map<String, Product> itemName2Product;

    // Singleton method to get instance of Db
    public static synchronized Db getInstance() {
        if (instance == null) {
            Db newInstance = new Db();
            newInstance.userName2User = new HashMap<>();
            newInstance.user2Account = new HashMap<>();
            newInstance.itemName2Product = new HashMap<>();
            instance = newInstance;
        }
        return instance;
    }

    // Methods to seed data into Db
    public void seedUser(String userName, Double amount) { /*...*/ }

    public void seedItem(String itemName, Double price) { /*...*/ }

    // Methods to find data in Db
    public User findUserByUserName(String userName) { /*...*/ }

    public Account findAccountByUser(User user) { /*...*/ }

    public Product findProductByItemName(String itemName) { /*...*/ }
}
```

Next, here are the presentation layer, the receipt view model interface and its implementation of successful scenario.

```java
public interface ReceiptViewModel {
    void show();
}
```

```java
@RequiredArgsConstructor
@Getter
public class ReceiptDto implements ReceiptViewModel {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReceiptDto.class);

    private final Double price;

    @Override
    public void show() {
        LOGGER.info(String.format("Receipt: %s paid", price));
    }
}
```

And here are the implementations of failure scenarios, which are the special cases.

```java
public class DownForMaintenance implements ReceiptViewModel {
    private static final Logger LOGGER = LoggerFactory.getLogger(DownForMaintenance.class);

    @Override
    public void show() {
        LOGGER.info("Down for maintenance");
    }
}
```

```java
public class InvalidUser implements ReceiptViewModel {
    private static final Logger LOGGER = LoggerFactory.getLogger(InvalidUser.class);

    private final String userName;

    public InvalidUser(String userName) {
        this.userName = userName;
    }

    @Override
    public void show() {
        LOGGER.info("Invalid user: " + userName);
    }
}
```

```java
public class OutOfStock implements ReceiptViewModel {

    private static final Logger LOGGER = LoggerFactory.getLogger(OutOfStock.class);

    private String userName;
    private String itemName;

    public OutOfStock(String userName, String itemName) {
        this.userName = userName;
        this.itemName = itemName;
    }

    @Override
    public void show() {
        LOGGER.info("Out of stock: " + itemName + " for user = " + userName + " to buy");
    }
}
```

```java
public class InsufficientFunds implements ReceiptViewModel {
    private static final Logger LOGGER = LoggerFactory.getLogger(InsufficientFunds.class);

    private String userName;
    private Double amount;
    private String itemName;

    public InsufficientFunds(String userName, Double amount, String itemName) {
        this.userName = userName;
        this.amount = amount;
        this.itemName = itemName;
    }

    @Override
    public void show() {
        LOGGER.info("Insufficient funds: " + amount + " of user: " + userName
                + " for buying item: " + itemName);
    }
}
```

Here is the `App` and its `main` function that executes the different scenarios.

```java
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    private static final String LOGGER_STRING = "[REQUEST] User: {} buy product: {}";
    private static final String TEST_USER_1 = "ignite1771";
    private static final String TEST_USER_2 = "abc123";
    private static final String ITEM_TV = "tv";
    private static final String ITEM_CAR = "car";
    private static final String ITEM_COMPUTER = "computer";

    public static void main(String[] args) {
        // DB seeding
        LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, "
                + "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}");
        Db.getInstance().seedUser(TEST_USER_1, 1000.0);
        Db.getInstance().seedItem(ITEM_COMPUTER, 800.0);
        Db.getInstance().seedItem(ITEM_CAR, 20000.0);

        final var applicationServices = new ApplicationServicesImpl();
        ReceiptViewModel receipt;

        LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV);
        receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV);
        receipt.show();
        MaintenanceLock.getInstance().setLock(false);
        LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV);
        receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV);
        receipt.show();
        LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_TV);
        receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_TV);
        receipt.show();
        LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_CAR);
        receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_CAR);
        receipt.show();
        LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_COMPUTER);
        receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_COMPUTER);
        receipt.show();
    }
}
```

Here is the output from running the example.

```
11:23:48.669 [main] INFO com.iluwatar.specialcase.App -- Db seeding: 1 user: {"ignite1771", amount = 1000.0}, 2 products: {"computer": price = 800.0, "car": price = 20000.0}
11:23:48.672 [main] INFO com.iluwatar.specialcase.App -- [REQUEST] User: abc123 buy product: tv
11:23:48.672 [main] INFO com.iluwatar.specialcase.DownForMaintenance -- Down for maintenance
11:23:48.672 [main] INFO com.iluwatar.specialcase.MaintenanceLock -- Maintenance lock is set to: false
11:23:48.672 [main] INFO com.iluwatar.specialcase.App -- [REQUEST] User: abc123 buy product: tv
11:23:48.673 [main] INFO com.iluwatar.specialcase.InvalidUser -- Invalid user: abc123
11:23:48.674 [main] INFO com.iluwatar.specialcase.App -- [REQUEST] User: ignite1771 buy product: tv
11:23:48.674 [main] INFO com.iluwatar.specialcase.OutOfStock -- Out of stock: tv for user = ignite1771 to buy
11:23:48.674 [main] INFO com.iluwatar.specialcase.App -- [REQUEST] User: ignite1771 buy product: car
11:23:48.676 [main] INFO com.iluwatar.specialcase.InsufficientFunds -- Insufficient funds: 1000.0 of user: ignite1771 for buying item: car
11:23:48.676 [main] INFO com.iluwatar.specialcase.App -- [REQUEST] User: ignite1771 buy product: computer
11:23:48.676 [main] INFO com.iluwatar.specialcase.ReceiptDto -- Receipt: 800.0 paid
```

In conclusion, the Special Case Pattern helps to keep the code clean and easy to understand by separating the special case from the general case. It also promotes code reuse and makes the code easier to maintain.

## [When to Use the Special Case Pattern in Java](https://java-design-patterns.com/patterns/special-case/#when-to-use-the-special-case-pattern-in-java)

- Use when you want to encapsulate and handle special cases or error conditions in a manner that avoids conditional logic scattered throughout the main codebase.
- Useful in scenarios where certain operations have known exceptional cases that require different handling.

## [Real-World Applications of Special Case Pattern in Java](https://java-design-patterns.com/patterns/special-case/#real-world-applications-of-special-case-pattern-in-java)

- Implementing null object patterns to avoid null checks.
- Handling specific business rules or validation logic in e-commerce applications.
- Managing different file formats or protocols in data processing applications.

## [Benefits and Trade-offs of Special Case Pattern](https://java-design-patterns.com/patterns/special-case/#benefits-and-trade-offs-of-special-case-pattern)

Benefits:

Adopting the Special Case design pattern

- Simplifies the main logic by removing special case handling from the core algorithms.
- Enhances code readability and maintainability by isolating special cases.

Trade-offs:

- May introduce additional classes or interfaces, increasing the number of components in the system.
- Requires careful design to ensure that special cases are correctly encapsulated and do not introduce unexpected behaviors.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/special-case/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add special case behavior to objects dynamically without modifying their code.
- [Null Object](https://java-design-patterns.com/patterns/null-object/): Used to provide a default behavior for null references, which is a specific type of special case.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Allows dynamic switching of special case behaviors by encapsulating them in different strategy classes.

## [References and Credits](https://java-design-patterns.com/patterns/special-case/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Special Case (Martin Fowler)](https://www.martinfowler.com/eaaCatalog/specialCase.html)

---

## [structural/strangler] Strangler
> 官方文档: https://java-design-patterns.com/patterns/strangler/

StructuralMigrationModernizationRefactoringAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/strangler/#also-known-as)

- Strangler Fig

## [Intent of Strangler Design Pattern](https://java-design-patterns.com/patterns/strangler/#intent-of-strangler-design-pattern)

The Strangler Pattern incrementally replaces the legacy system by building a new system alongside the old one, eventually strangling the old system. Using the pattern offer a seamless transition from old to new systems.

## [Detailed Explanation of Strangler Pattern with Real-World Examples](https://java-design-patterns.com/patterns/strangler/#detailed-explanation-of-strangler-pattern-with-real-world-examples)

Real-world example

> Imagine a city planning department that decides to modernize an old bridge that's crucial for daily commutes. Instead of demolishing the old bridge and causing major disruptions, they build a new, modern bridge next to it. As sections of the new bridge are completed, traffic is gradually diverted from the old bridge to the new one. Eventually, the entire flow of traffic moves to the new bridge, and the old bridge is either decommissioned or demolished. This way, the transition is smooth, and the city's daily activities are minimally affected. This approach mirrors the Strangler Design Pattern, where a legacy system is incrementally replaced by a new system, ensuring continuous operation during the transition.

In plain words

> The Strangler Design Pattern incrementally replaces a legacy system by developing a new system alongside it and gradually migrating functionality until the old system is entirely replaced.

Wikipedia says

> The Strangler Design Pattern involves incrementally migrating a legacy system by gradually replacing it with a new system. It wraps old code with new code, redirecting or logging uses of the old code to ensure a seamless transition. This pattern is named after the strangler fig plant, which grows around a host tree and eventually replaces it entirely. It's particularly useful for modernizing monolithic applications and transitioning them to microservices architecture with minimal risk and disruption.

Flowchart

![Strangler flowchart](https://java-design-patterns.com/assets/img/strangler-flowchart.a8664fdf.png)

## [Programmatic Example of Strangler Pattern in Java](https://java-design-patterns.com/patterns/strangler/#programmatic-example-of-strangler-pattern-in-java)

The Strangler design pattern in Java is a software design pattern that incrementally migrates a legacy system by gradually replacing specific pieces of functionality with new applications and services. As features from the legacy system are replaced, the new system eventually replaces all the old system's features, strangling the old system and allowing you to decommission it.

In the provided code, we have an example of the Strangler pattern in action. The `OldArithmetic` class represents the legacy system, while the `HalfArithmetic` and `NewArithmetic` classes represent the new system at different stages of development.

Let's break down the code to understand how the Strangler pattern is implemented.

```java
public class OldArithmetic {
  private final OldSource source;

  public OldArithmetic(OldSource source) {
    this.source = source;
  }

  // The sum and mul methods represent the functionality of the legacy system.
  public int sum(int... nums) {
    return source.accumulateSum(nums);
  }

  public int mul(int... nums) {
    return source.accumulateMul(nums);
  }
}
```

The `OldArithmetic` class represents the legacy system. It has two methods, `sum` and `mul`, which depend on the `OldSource` class.

```java
public class HalfArithmetic {
  private final HalfSource newSource;
  private final OldSource oldSource;

  public HalfArithmetic(HalfSource newSource, OldSource oldSource) {
    this.newSource = newSource;
    this.oldSource = oldSource;
  }

  // The sum method has been migrated to use the new source.
  public int sum(int... nums) {
    return newSource.accumulateSum(nums);
  }

  // The mul method still uses the old source.
  public int mul(int... nums) {
    return oldSource.accumulateMul(nums);
  }

  // The ifHasZero method is a new feature added in the new system.
  public boolean ifHasZero(int... nums) {
    return !newSource.ifNonZero(nums);
  }
}
```

The `HalfArithmetic` class represents the system during the migration process. It depends on both the `OldSource` and `HalfSource` classes. The `sum` method has been migrated to use the new source, while the `mul` method still uses the old source. The `ifHasZero` method is a new feature added in the new system.

```java
public class NewArithmetic {
  private final NewSource source;

  public NewArithmetic(NewSource source) {
    this.source = source;
  }

  // All methods now use the new source.
  public int sum(int... nums) {
    return source.accumulateSum(nums);
  }

  public int mul(int... nums) {
    return source.accumulateMul(nums);
  }

  public boolean ifHasZero(int... nums) {
    return !source.ifNonZero(nums);
  }
}
```

The `NewArithmetic` class represents the system after the migration process. It only depends on the `NewSource` class. All methods now use the new source.

Here is the `main` method executing our example.

```java
public static void main(final String[] args) {
    final var nums = new int[]{1, 2, 3, 4, 5};
    //Before migration
    final var oldSystem = new OldArithmetic(new OldSource());
    oldSystem.sum(nums);
    oldSystem.mul(nums);
    //In process of migration
    final var halfSystem = new HalfArithmetic(new HalfSource(), new OldSource());
    halfSystem.sum(nums);
    halfSystem.mul(nums);
    halfSystem.ifHasZero(nums);
    //After migration
    final var newSystem = new NewArithmetic(new NewSource());
    newSystem.sum(nums);
    newSystem.mul(nums);
    newSystem.ifHasZero(nums);
  }
```

Console output:

```
13:02:25.030 [main] INFO com.iluwatar.strangler.OldArithmetic -- Arithmetic sum 1.0
13:02:25.032 [main] INFO com.iluwatar.strangler.OldSource -- Source module 1.0
13:02:25.032 [main] INFO com.iluwatar.strangler.OldArithmetic -- Arithmetic mul 1.0
13:02:25.032 [main] INFO com.iluwatar.strangler.OldSource -- Source module 1.0
13:02:25.032 [main] INFO com.iluwatar.strangler.HalfArithmetic -- Arithmetic sum 1.5
13:02:25.032 [main] INFO com.iluwatar.strangler.HalfSource -- Source module 1.5
13:02:25.033 [main] INFO com.iluwatar.strangler.HalfArithmetic -- Arithmetic mul 1.5
13:02:25.033 [main] INFO com.iluwatar.strangler.OldSource -- Source module 1.0
13:02:25.033 [main] INFO com.iluwatar.strangler.HalfArithmetic -- Arithmetic check zero 1.5
13:02:25.033 [main] INFO com.iluwatar.strangler.HalfSource -- Source module 1.5
13:02:25.034 [main] INFO com.iluwatar.strangler.NewArithmetic -- Arithmetic sum 2.0
13:02:25.034 [main] INFO com.iluwatar.strangler.NewSource -- Source module 2.0
13:02:25.034 [main] INFO com.iluwatar.strangler.NewArithmetic -- Arithmetic mul 2.0
13:02:25.034 [main] INFO com.iluwatar.strangler.NewSource -- Source module 2.0
13:02:25.034 [main] INFO com.iluwatar.strangler.NewArithmetic -- Arithmetic check zero 2.0
13:02:25.035 [main] INFO com.iluwatar.strangler.NewSource -- Source module 2.0
```

This is a typical example of the Strangler pattern. The legacy system (`OldArithmetic`) is gradually replaced by the new system (`HalfArithmetic` and `NewArithmetic`). The new system is developed incrementally, and at each stage, it strangles a part of the legacy system until the legacy system is completely replaced.

## [When to Use the Strangler Pattern in Java](https://java-design-patterns.com/patterns/strangler/#when-to-use-the-strangler-pattern-in-java)

- Use when you need to replace a monolithic or legacy system incrementally.
- Ideal for scenarios where the system cannot be replaced in one go due to risk or complexity.
- Suitable when you need to modernize parts of an application while ensuring continuous operation.
- Perfect for applications requiring updates with zero downtime, the Strangler pattern supports incremental updates in complex Java systems.

## [Strangler Pattern Java Tutorials](https://java-design-patterns.com/patterns/strangler/#strangler-pattern-java-tutorials)

- [Legacy Application Strangulation: Case Studies (Paul Hammant)](https://paulhammant.com/2013/07/14/legacy-application-strangulation-case-studies/)

## [Real-World Applications of Strangler Pattern in Java](https://java-design-patterns.com/patterns/strangler/#real-world-applications-of-strangler-pattern-in-java)

- Replacing a legacy monolithic application with a microservices architecture.
- Transitioning from an on-premise system to a cloud-based system.
- Incrementally migrating from an old database schema to a new one without downtime.

## [Benefits and Trade-offs of Strangler Pattern](https://java-design-patterns.com/patterns/strangler/#benefits-and-trade-offs-of-strangler-pattern)

Benefits:

- Reduces risk by allowing gradual replacement.
- Enables continuous delivery and operation during migration.
- Allows for testing and validating new components before full replacement.

Trade-offs:

- Requires managing interactions between new and old systems, which can be complex.
- May introduce temporary performance overhead due to coexistence of old and new systems.
- Potentially increases the initial development time due to the need for integration.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/strangler/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Used to make new systems interact with the old system during the transition period.
- [Facade](https://java-design-patterns.com/patterns/facade/): Can provide a unified interface to the old and new systems, simplifying client interactions.
- Microservices: The target architecture in many cases where the Strangler Pattern is applied.

## [References and Credits](https://java-design-patterns.com/patterns/strangler/#references-and-credits)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB)
- [Strangler pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/strangler)

---

## [structural/twin] Twin
> 官方文档: https://java-design-patterns.com/patterns/twin/

StructuralDecouplingObject compositionPerformanceResilienceAbout 4 min

* * *

## [Intent of Twin Design Pattern](https://java-design-patterns.com/patterns/twin/#intent-of-twin-design-pattern)

The Twin design pattern in Java provides a way to handle multiple, related classes in a manner that allows them to work together without inheriting from a common base class.

## [Detailed Explanation of Twin Pattern with Real-World Examples](https://java-design-patterns.com/patterns/twin/#detailed-explanation-of-twin-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Twin design pattern can be found in the relationship between a driver and a driving simulator. Imagine a driver (the first class) and a driving simulator (the second class) that both need to interact with the same set of vehicle controls (steering, acceleration, braking) and receive the same feedback (speed, engine status).
>
> Despite performing similar functions, the driver and the simulator cannot share a common base class because they operate in fundamentally different environments—one in the physical world and the other in a virtual environment. Instead, they are "twinned" to ensure consistent interaction with the vehicle controls and feedback mechanisms. This setup allows improvements or changes to be made to the simulator without affecting the driver and vice versa, maintaining the system's overall flexibility and resilience.

In plain words

> It provides a way to form two closely coupled subclasses that can act as a twin class having two ends.

Wikipedia says

> The Twin pattern is a software design pattern that allows developers to simulate multiple inheritance in languages that don't support it. Instead of creating a single class inheriting from multiple parents, two closely linked subclasses are created, each inheriting from one of the parents. These subclasses are mutually dependent, working together as a pair to achieve the desired functionality. This approach avoids the complications and inefficiencies often associated with multiple inheritance, while still allowing the reuse of functionalities from different classes.

Sequence diagram

![Twin Pattern Sequence Diagram](https://java-design-patterns.com/assets/img/twin-sequence-diagram.17a4b499.png)

## [Programmatic Example of Twin Pattern in Java](https://java-design-patterns.com/patterns/twin/#programmatic-example-of-twin-pattern-in-java)

Consider a game where a ball needs to function as both a `GameItem` and a `Thread`. Instead of inheriting from both, we use the Twin pattern with two closely linked objects: `BallItem` and `BallThread`.

Here is the `GameItem` class:

```java
@Slf4j
public abstract class GameItem {
  public void draw() {
    LOGGER.info("draw");
    doDraw();
  }
  public abstract void doDraw();
  public abstract void click();
}
```

`BallItem` and `BallThread` subclasses:

```java
@Slf4j
public class BallItem extends GameItem {
  private boolean isSuspended;
  @Setter
  private BallThread twin;

  @Override
  public void doDraw() {
    LOGGER.info("doDraw");
  }

  public void move() {
    LOGGER.info("move");
  }

  @Override
  public void click() {
    isSuspended = !isSuspended;
    if (isSuspended) {
      twin.suspendMe();
    } else {
      twin.resumeMe();
    }
  }
}
```

```java
@Slf4j
public class BallThread extends Thread {
  @Setter
  private BallItem twin;
  private volatile boolean isSuspended;
  private volatile boolean isRunning = true;

  public void run() {
    while (isRunning) {
      if (!isSuspended) {
        twin.draw();
        twin.move();
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }

  public void suspendMe() {
    isSuspended = true;
    LOGGER.info("Begin to suspend BallThread");
  }

  public void resumeMe() {
    isSuspended = false;
    LOGGER.info("Begin to resume BallThread");
  }

  public void stopMe() {
    this.isRunning = false;
    this.isSuspended = true;
  }
}
```

To use these classes together:

```java
public class App {

    public static void main(String[] args) throws Exception {

        var ballItem = new BallItem();
        var ballThread = new BallThread();

        ballItem.setTwin(ballThread);
        ballThread.setTwin(ballItem);

        ballThread.start();

        waiting();

        ballItem.click();

        waiting();

        ballItem.click();

        waiting();

        // exit
        ballThread.stopMe();
    }

    private static void waiting() throws Exception {
        Thread.sleep(750);
    }
}
```

Let's break down what happens in `App`.

1. An instance of `BallItem` and `BallThread` are created.
2. The `BallItem` and `BallThread` instances are set as twins of each other. This means that each instance has a reference to the other.
3. The `BallThread` is started. This begins the execution of the `run` method in the `BallThread` class, which continuously calls the `draw` and `move` methods of the `BallItem` (its twin) as long as the `BallThread` is not suspended.
4. The program waits for 750 milliseconds. This is done to allow the `BallThread` to execute its `run` method a few times.
5. The `click` method of the `BallItem` is called. This toggles the `isSuspended` state of the `BallItem` and its twin `BallThread`. If the `BallThread` was running, it gets suspended. If it was suspended, it resumes running.
6. Steps 4 and 5 are repeated twice. This means the `BallThread` is suspended and resumed once.
7. Finally, the `stopMe` method of the `BallThread` is called to stop its execution.

Console output:

```
14:29:33.778 [Thread-0] INFO com.iluwatar.twin.GameItem -- draw
14:29:33.780 [Thread-0] INFO com.iluwatar.twin.BallItem -- doDraw
14:29:33.780 [Thread-0] INFO com.iluwatar.twin.BallItem -- move
14:29:34.035 [Thread-0] INFO com.iluwatar.twin.GameItem -- draw
14:29:34.035 [Thread-0] INFO com.iluwatar.twin.BallItem -- doDraw
14:29:34.035 [Thread-0] INFO com.iluwatar.twin.BallItem -- move
14:29:34.291 [Thread-0] INFO com.iluwatar.twin.GameItem -- draw
14:29:34.291 [Thread-0] INFO com.iluwatar.twin.BallItem -- doDraw
14:29:34.291 [Thread-0] INFO com.iluwatar.twin.BallItem -- move
14:29:34.533 [main] INFO com.iluwatar.twin.BallThread -- Begin to suspend BallThread
14:29:35.285 [main] INFO com.iluwatar.twin.BallThread -- Begin to resume BallThread
14:29:35.308 [Thread-0] INFO com.iluwatar.twin.GameItem -- draw
14:29:35.308 [Thread-0] INFO com.iluwatar.twin.BallItem -- doDraw
14:29:35.308 [Thread-0] INFO com.iluwatar.twin.BallItem -- move
14:29:35.564 [Thread-0] INFO com.iluwatar.twin.GameItem -- draw
14:29:35.564 [Thread-0] INFO com.iluwatar.twin.BallItem -- doDraw
14:29:35.565 [Thread-0] INFO com.iluwatar.twin.BallItem -- move
14:29:35.817 [Thread-0] INFO com.iluwatar.twin.GameItem -- draw
14:29:35.817 [Thread-0] INFO com.iluwatar.twin.BallItem -- doDraw
14:29:35.817 [Thread-0] INFO com.iluwatar.twin.BallItem -- move
```

This setup allows `BallItem` and `BallThread` to act together as a single cohesive unit in the game, leveraging the capabilities of both `GameItem` and `Thread` without multiple inheritance.

## [When to Use the Twin Pattern in Java](https://java-design-patterns.com/patterns/twin/#when-to-use-the-twin-pattern-in-java)

- Use when you need to decouple classes that share common functionality but cannot inherit from a common base class due to various reasons such as the use of different frameworks or languages.
- Useful in performance-critical applications where inheritance might introduce unnecessary overhead.
- Applicable in systems requiring resilience through the ability to replace or update one of the twins without affecting the other.

## [Twin Pattern Java Tutorials](https://java-design-patterns.com/patterns/twin/#twin-pattern-java-tutorials)

- [Twin – A Design Pattern for Modeling Multiple Inheritance (Hanspeter Mössenböck)](http://www.ssw.uni-linz.ac.at/Research/Papers/Moe99/Paper.pdf)

## [Real-World Applications of Twin Pattern in Java](https://java-design-patterns.com/patterns/twin/#real-world-applications-of-twin-pattern-in-java)

- User interfaces where different frameworks are used for rendering and logic.
- Systems integrating legacy code with new implementations where direct inheritance is not feasible.

## [Benefits and Trade-offs of Twin Pattern](https://java-design-patterns.com/patterns/twin/#benefits-and-trade-offs-of-twin-pattern)

Benefits:

- Reduces coupling between classes, promoting modularity and easier maintenance.
- Improves flexibility and reuse of classes across different frameworks or languages.
- Enhances performance by avoiding the overhead associated with inheritance.

Trade-offs:

- Can lead to code duplication if not managed properly.
- Increased complexity in managing the interaction between twin classes.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/twin/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Both patterns deal with compatibility issues, but Adapter focuses on converting interfaces while Twin deals with class collaboration without inheritance.
- [Bridge](https://java-design-patterns.com/patterns/bridge/): Similar in decoupling abstraction from implementation, but Twin specifically avoids inheritance.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Manages object access, similar to how Twin handles interaction, but Proxy typically focuses on control and logging.

## [References and Credits](https://java-design-patterns.com/patterns/twin/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [structural/value-object] Value Object 值对象
> 官方文档: https://java-design-patterns.com/patterns/value-object/

StructuralData accessData bindingDomainEncapsulationEnterprise patternsImmutableOptimizationPerformancePersistenceAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/value-object/#also-known-as)

- Embedded Value
- Immutable Object
- Inline Value
- Integrated Value

## [Intent of Value Object Design Pattern](https://java-design-patterns.com/patterns/value-object/#intent-of-value-object-design-pattern)

The Value Object pattern in Java creates immutable objects that represent a descriptive aspect of the domain with no conceptual identity. It aims to enhance performance and reduce memory overhead by storing frequently accessed immutable data directly within the object that uses it, rather than separately.

## [Detailed Explanation of Value Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/value-object/#detailed-explanation-of-value-object-pattern-with-real-world-examples)

Real-world example

> Consider the case of a business card. In our example, a BusinessCard class is implemented as a Value Object to demonstrate immutable data handling and efficiency in Java applications. In the real world, a business card contains information such as the person's name, job title, phone number, and email address. This information represents a specific and complete set of attributes describing the contact details of an individual but doesn't have an identity itself beyond this information.
>
> In a software system, you can create a `BusinessCard` class as a Value Object. This class would be immutable, meaning once a `BusinessCard` object is created with a person's details, those details cannot change. If you need a different business card, you create a new instance rather than modifying the existing one. The equality of two `BusinessCard` objects would be based on their contained data rather than their memory addresses, ensuring that two business cards with the same details are considered equal. This mirrors how business cards in real life are used and compared based on their content, not on the physical card itself.

In plain words

> Value objects are equal when their attributes have the same value.

Wikipedia says

> In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object.

Flowchart

![Value Object Pattern Flowchart](https://java-design-patterns.com/assets/img/value-object-flowchart.64111ecc.png)

## [Programmatic Example of Value Object Pattern in Java](https://java-design-patterns.com/patterns/value-object/#programmatic-example-of-value-object-pattern-in-java)

There is a class for hero statistics in a role-playing game. The statistics contain attributes such as strength, intelligence, and luck. The statistics of different heroes should be equal when all the attributes are equal.

Here is the `HeroStat` class that is the value object. Notice the use of [Lombok's `@Value`](https://projectlombok.org/features/Value) annotation.

```java
@Value(staticConstructor = "valueOf")
@ToString
class HeroStat {
    int strength;
    int intelligence;
    int luck;
}
```

The example creates three different `HeroStat`s and compares their equality.

```java
public static void main(String[] args) {
    var statA = HeroStat.valueOf(10, 5, 0);
    var statB = HeroStat.valueOf(10, 5, 0);
    var statC = HeroStat.valueOf(5, 1, 8);

    LOGGER.info("statA: {}", statA);
    LOGGER.info("statB: {}", statB);
    LOGGER.info("statC: {}", statC);

    LOGGER.info("Are statA and statB equal? {}", statA.equals(statB));
    LOGGER.info("Are statA and statC equal? {}", statA.equals(statC));
}
```

Here's the console output.

```
20:11:12.199 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0)
20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=10, intelligence=5, luck=0)
20:11:12.202 [main] INFO com.iluwatar.value.object.App - HeroStat(strength=5, intelligence=1, luck=8)
20:11:12.202 [main] INFO com.iluwatar.value.object.App - Is statA and statB equal : true
20:11:12.203 [main] INFO com.iluwatar.value.object.App - Is statA and statC equal : false
```

## [When to Use the Value Object Pattern in Java](https://java-design-patterns.com/patterns/value-object/#when-to-use-the-value-object-pattern-in-java)

Use the Value Object when

- Apply the Value Object pattern when you need high-performance Java applications with reduced memory overhead, especially in systems requiring efficient data management.
- When representing a set of attributes that together describe an entity but without an identity.
- When the equality of the objects is based on the value of the properties, not the identity.
- When you need to ensure that objects cannot be altered once created.
- An application requires high performance and the data involved is immutable.
- Memory footprint reduction is critical, especially in environments with limited resources.
- Objects frequently access a particular piece of immutable data.

## [Value Object Pattern Java Tutorials](https://java-design-patterns.com/patterns/value-object/#value-object-pattern-java-tutorials)

- [VALJOs - Value Java Objects (Stephen Colebourne)](http://blog.joda.org/2014/03/valjos-value-java-objects.html)

## [Real-World Applications of Value Object Pattern in Java](https://java-design-patterns.com/patterns/value-object/#real-world-applications-of-value-object-pattern-in-java)

- Implementing complex data types like monetary values, measurements, and other domain-specific values.
- [java.util.Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)
- [java.time.LocalDate](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html)
- [java.awt.Color](https://docs.oracle.com/javase/8/docs/api/java/awt/Color.html)
- [joda-time, money, beans](http://www.joda.org/)

## [Benefits and Trade-offs of Value Object Pattern](https://java-design-patterns.com/patterns/value-object/#benefits-and-trade-offs-of-value-object-pattern)

Benefits:

- Simplifies code by making objects immutable.
- Thread-safe as the object's state cannot change after creation.
- Easier to reason about and maintain.
- Reduces the memory overhead by avoiding separate allocations for immutable data.
- Improves performance by minimizing memory accesses and reducing cache misses.

Trade-offs:

- Creating a new object for every change can be less efficient for complex objects.
- Increased memory usage due to the creation of multiple objects representing different states.
- Increases complexity in object design and can lead to tightly coupled systems.
- Modifying the embedded value necessitates changes across all objects that embed this value, which can complicate maintenance.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/value-object/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used to create instances of value objects.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Shares objects to support large quantities using a minimal amount of memory, somewhat similar in intent but different in implementation.
- [Builder](https://java-design-patterns.com/patterns/builder/): Can be used to construct complex value objects step by step.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Can be used to clone existing value objects, though cloning is less common with immutable objects.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensures a class has only one instance and provides a global point of access to it, can be used to manage a shared embedded value.

## [References and Credits](https://java-design-patterns.com/patterns/value-object/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [ValueObject (Martin Fowler)](https://martinfowler.com/bliki/ValueObject.html)

---

## [structural/virtual-proxy] Virtual Proxy
> 官方文档: https://java-design-patterns.com/patterns/virtual-proxy/

StructuralCachingDecouplingLazy initializationAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/virtual-proxy/#also-known-as)

- Lazy Initialization Proxy
- Virtual Surrogate

## [Intent of Virtual Proxy Design Pattern](https://java-design-patterns.com/patterns/virtual-proxy/#intent-of-virtual-proxy-design-pattern)

The Virtual Proxy Design Pattern is a crucial component in Java design patterns, enabling efficient resource management and performance optimization through controlled object creation. It provides a surrogate or placeholder for another object to control its creation and access, particularly when dealing with resource-intensive operations.

## [Detailed Explanation of Virtual Proxy Pattern with Real-World Examples](https://java-design-patterns.com/patterns/virtual-proxy/#detailed-explanation-of-virtual-proxy-pattern-with-real-world-examples)

Real-world example

> Just as a high-end art gallery uses photographs to save resources and reduce risks, the Virtual Proxy Pattern in Java manages resource-intensive operations by displaying only necessary objects, significantly enhancing system efficiency. To protect the actual artwork and reduce the risk of damage or theft, the gallery initially displays high-quality photographs of the artworks. When a serious buyer expresses genuine interest, the gallery then brings out the original artwork from a secure storage area for viewing.
>
> In this analogy, the high-quality photograph serves as the virtual proxy for the actual artwork. The real artwork is only fetched and displayed when truly necessary, thus saving resources and reducing risk, similar to how the Virtual Proxy pattern defers object creation until it is needed.

In plain words

> The virtual proxy pattern allows a representative class to stand in for another class to control access to it, particularly for resource-intensive operations.

Wikipedia says

> A proxy that controls access to a resource that is expensive to create.

Sequence diagram

![Virtual Proxy Sequence Diagram](https://java-design-patterns.com/assets/img/virtual-proxy-sequence-diagram.bce40486.png)

## [Programmatic Example of Virtual Proxy Pattern in Java](https://java-design-patterns.com/patterns/virtual-proxy/#programmatic-example-of-virtual-proxy-pattern-in-java)

The Virtual Proxy design pattern in Java can optimize resource utilization and system performance.

Consider an online video streaming platform where video objects are resource-intensive due to their large data size and required processing power. To efficiently manage resources, the system uses a virtual proxy to handle video objects. The virtual proxy defers the creation of actual video objects until they are explicitly required for playback, thus saving system resources and improving response times for users.

Given our example of a video streaming service, here is how it might be implemented:

First, we define an `ExpensiveObject` interface, which outlines the method for processing video.

```java
public interface ExpensiveObject {
    void process();
}
```

Here’s the implementation of a `RealVideoObject` that represents an expensive-to-create video object.

```java
@Slf4j
@Getter
public class RealVideoObject implements ExpensiveObject {

    public RealVideoObject() {
        heavyInitialConfiguration();
    }

    private void heavyInitialConfiguration() {
        LOGGER.info("Loading initial video configurations...");
    }

    @Override
    public void process() {
        LOGGER.info("Processing and playing video content...");
    }
}
```

The `VideoObjectProxy` serves as a stand-in for `RealExpensiveObject`.

```java
@Getter
public class VideoObjectProxy implements ExpensiveObject {

    private RealVideoObject realVideoObject;

    public void setRealVideoObject(RealVideoObject realVideoObject) {
        this.realVideoObject = realVideoObject;
    }

    @Override
    public void process() {
        if (realVideoObject == null) {
            realVideoObject = new RealVideoObject();
        }
        realVideoObject.process();
    }
}
```

And here’s how the proxy is used in the system.

```java
public static void main(String[] args) {
    ExpensiveObject videoObject = new VideoObjectProxy();
    videoObject.process();  // The first call creates and plays the video
    videoObject.process();  // Subsequent call uses the already created object
}
```

Program output:

```
14:54:30.602 [main] INFO com.iluwatar.virtual.proxy.RealVideoObject -- Loading initial video configurations...
14:54:30.604 [main] INFO com.iluwatar.virtual.proxy.RealVideoObject -- Processing and playing video content...
14:54:30.604 [main] INFO com.iluwatar.virtual.proxy.RealVideoObject -- Processing and playing video content...
```

## [When to Use the Virtual Proxy Pattern in Java](https://java-design-patterns.com/patterns/virtual-proxy/#when-to-use-the-virtual-proxy-pattern-in-java)

Use the Virtual Proxy pattern when:

- Object creation is resource-intensive, and not all instances are utilized immediately or ever.
- The performance of a system can be significantly improved by deferring the creation of objects until they are needed.
- There is a need for control over resource usage in systems dealing with large quantities of high-overhead objects.

## [Virtual Proxy Pattern Java Tutorials](https://java-design-patterns.com/patterns/virtual-proxy/#virtual-proxy-pattern-java-tutorials)

- [The Proxy Pattern in Java (Baeldung)](https://www.baeldung.com/java-proxy-pattern)

## [Real-World Applications of Virtual Proxy Pattern in Java](https://java-design-patterns.com/patterns/virtual-proxy/#real-world-applications-of-virtual-proxy-pattern-in-java)

- Lazy Initialization: Create objects only when they are actually needed.
- Resource Management: Efficiently manage resources by creating heavy objects only on demand.
- Access Control: Include logic to check conditions before delegating calls to the actual object.
- Performance Optimization: Incorporate caching of results or states that are expensive to obtain or compute.
- Data Binding and Integration: Delay integration and binding processes until the data is actually needed.
- In Java, the `java.awt.Image` class uses virtual proxies to load images on demand.
- Hibernate ORM framework uses proxies to implement lazy loading of entities.

## [Benefits and Trade-offs of Virtual Proxy Pattern](https://java-design-patterns.com/patterns/virtual-proxy/#benefits-and-trade-offs-of-virtual-proxy-pattern)

Benefits:

- Reduces memory usage by deferring object creation.
- Can improve performance by delaying heavy operations until needed.

Trade-offs:

- Introduces complexity in the codebase.
- Can lead to unexpected behaviors if not handled properly, especially in multithreaded environments.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/virtual-proxy/#related-java-design-patterns)

- [Proxy](https://java-design-patterns.com/patterns/proxy/): Virtual Proxy is a specific type of the Proxy pattern focused on lazy initialization.
- [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Directly related as the core idea of Virtual Proxy is to defer object creation.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar in structure, but Decorators add behavior to the objects while proxies control access.

## [References and Credits](https://java-design-patterns.com/patterns/virtual-proxy/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

<!-- ============================================ -->
<!-- Behavioral 行为型模式 (40 个) -->
<!-- ============================================ -->

## [behavioral/acyclic-visitor] Acyclic Visitor
> 官方文档: https://java-design-patterns.com/patterns/acyclic-visitor/

BehavioralDecouplingExtensibilityInterfaceObject compositionAbout 3 min

* * *

## [Intent of Acyclic Visitor Design Pattern](https://java-design-patterns.com/patterns/acyclic-visitor/#intent-of-acyclic-visitor-design-pattern)

The Acyclic Visitor pattern in Java decouples operations from an object hierarchy, providing a flexible design for various applications.

## [Detailed Explanation of Acyclic Visitor Pattern with Real-World Examples](https://java-design-patterns.com/patterns/acyclic-visitor/#detailed-explanation-of-acyclic-visitor-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Acyclic Visitor pattern in Java is a museum guide system, demonstrating the practical application of this design pattern. Imagine a museum with various exhibits like paintings, sculptures, and historical artifacts. The museum has different types of guides (audio guide, human guide, virtual reality guide) that provide information about each exhibit. Instead of modifying the exhibits every time a new guide type is introduced, each guide implements an interface to visit different exhibit types. This way, the museum can add new types of guides without altering the existing exhibits, ensuring that the system remains extensible and maintainable without forming any dependency cycles.

In plain words

> Acyclic Visitor allows functions to be added to existing class hierarchies without modifying the hierarchies.

[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) says

> The Acyclic Visitor pattern allows new functions to be added to existing class hierarchies without affecting those hierarchies, and without creating the dependency cycles that are inherent to the GangOfFour VisitorPattern.

Sequence diagram

![Acyclic Visitor sequence diagram](https://java-design-patterns.com/assets/img/acyclic-visitor-sequence-diagram.ef14fcbc.png)

## [Programmatic Example of Acyclic Visitor in Java](https://java-design-patterns.com/patterns/acyclic-visitor/#programmatic-example-of-acyclic-visitor-in-java)

In this Java example, we have a hierarchy of modem classes illustrating the Acyclic Visitor pattern. The modems in this hierarchy need to be visited by an external algorithm based on filtering criteria (is it Unix or DOS compatible modem).

Here's the `Modem` hierarchy.

```java
public abstract class Modem {
    public abstract void accept(ModemVisitor modemVisitor);
}

public class Zoom extends Modem {

    // Other properties and methods...

    @Override
    public void accept(ModemVisitor modemVisitor) {
        if (modemVisitor instanceof ZoomVisitor) {
            ((ZoomVisitor) modemVisitor).visit(this);
        } else {
            LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem");
        }
    }
}

public class Hayes extends Modem {

    // Other properties and methods...

    @Override
    public void accept(ModemVisitor modemVisitor) {
        if (modemVisitor instanceof HayesVisitor) {
            ((HayesVisitor) modemVisitor).visit(this);
        } else {
            LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
        }
    }
}
```

Next, we introduce the `ModemVisitor` hierarchy.

```java
public interface ModemVisitor {
}

public interface HayesVisitor extends ModemVisitor {
    void visit(Hayes hayes);
}

public interface ZoomVisitor extends ModemVisitor {
    void visit(Zoom zoom);
}

public interface AllModemVisitor extends ZoomVisitor, HayesVisitor {
}

public class ConfigureForDosVisitor implements AllModemVisitor {

    // Other properties and methods...

    @Override
    public void visit(Hayes hayes) {
        LOGGER.info(hayes + " used with Dos configurator.");
    }

    @Override
    public void visit(Zoom zoom) {
        LOGGER.info(zoom + " used with Dos configurator.");
    }
}

public class ConfigureForUnixVisitor implements ZoomVisitor {

    // Other properties and methods...

    @Override
    public void visit(Zoom zoom) {
        LOGGER.info(zoom + " used with Unix configurator.");
    }
}
```

Finally, here are the visitors in action.

```java
public static void main(String[] args) {
    var conUnix = new ConfigureForUnixVisitor();
    var conDos = new ConfigureForDosVisitor();

    var zoom = new Zoom();
    var hayes = new Hayes();

    hayes.accept(conDos); // Hayes modem with Dos configurator
    zoom.accept(conDos); // Zoom modem with Dos configurator
    hayes.accept(conUnix); // Hayes modem with Unix configurator
    zoom.accept(conUnix); // Zoom modem with Unix configurator
}
```

Program output:

```
09:15:11.125 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForDosVisitor -- Hayes modem used with Dos configurator.
09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForDosVisitor -- Zoom modem used with Dos configurator.
09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.Hayes -- Only HayesVisitor is allowed to visit Hayes modem
09:15:11.127 [main] INFO com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor -- Zoom modem used with Unix configurator.
```

## [When to Use the Acyclic Visitor Pattern in Java](https://java-design-patterns.com/patterns/acyclic-visitor/#when-to-use-the-acyclic-visitor-pattern-in-java)

This pattern can be used:

- When you need to add a new function to an existing hierarchy without the need to alter or affect that hierarchy.
- When there are functions that operate upon a hierarchy, but which do not belong in the hierarchy itself. e.g. the ConfigureForDOS / ConfigureForUnix / ConfigureForX issue.
- When you need to perform very different operations on an object depending upon its type.
- When the visited class hierarchy will be frequently extended with new derivatives of the Element class.
- When the recompilation, relinking, retesting or redistribution of the derivatives of Element is very expensive.

## [Acyclic Visitor Pattern Java Tutorials](https://java-design-patterns.com/patterns/acyclic-visitor/#acyclic-visitor-pattern-java-tutorials)

- [The Acyclic Visitor Pattern (Code Crafter)](https://codecrafter.blogspot.com/2012/12/the-acyclic-visitor-pattern.html)

## [Benefits and Trade-offs of Acyclic Visitor Pattern](https://java-design-patterns.com/patterns/acyclic-visitor/#benefits-and-trade-offs-of-acyclic-visitor-pattern)

Benefits:

- Extensible: New operations can be added easily without changing the object structure.
- Decoupled: Reduces coupling between the objects and the operations on them.
- No dependency cycles: Ensures acyclic dependencies, improving maintainability and reducing complexity.

Trade-offs:

- Increased complexity: Can introduce additional complexity with the need for multiple visitor interfaces.
- Maintenance overhead: Modifying the object hierarchy requires updating all visitors.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/acyclic-visitor/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Often used in conjunction with Acyclic Visitor to allow treating individual objects and compositions uniformly.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used alongside to add responsibilities to objects dynamically.
- [Visitor](https://java-design-patterns.com/patterns/visitor/): The Acyclic Visitor pattern is a variation of the Visitor pattern that avoids cyclic dependencies.

## [References and Credits](https://java-design-patterns.com/patterns/acyclic-visitor/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML](https://amzn.to/4bOtzwF)
- [Acyclic Visitor (Robert C. Martin)](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf)
- [Acyclic Visitor (WikiWikiWeb)](https://wiki.c2.com/?AcyclicVisitor)

---

## [behavioral/bytecode] Bytecode
> 官方文档: https://java-design-patterns.com/patterns/bytecode/

BehavioralAbstractionCode simplificationEncapsulationGame programmingPerformanceRuntimeAbout 5 min

* * *

## [Intent of Bytecode Design Pattern](https://java-design-patterns.com/patterns/bytecode/#intent-of-bytecode-design-pattern)

The Bytecode design pattern in Java allows encoding behavior as instructions for a virtual machine, making it a powerful tool in game development and other applications.

## [Detailed Explanation of Bytecode Pattern with Real-World Examples](https://java-design-patterns.com/patterns/bytecode/#detailed-explanation-of-bytecode-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Bytecode design pattern can be seen in the process of translating a book into multiple languages. Instead of directly translating the book from the original language into every other language, the book is first translated into a common intermediate language, like Esperanto. This intermediate version is easier to translate because it is simpler and more structured. Translators for each target language then translate from Esperanto into their specific languages. This approach ensures consistency, reduces errors, and simplifies the translation process, similar to how bytecode serves as an intermediate representation to optimize and facilitate the execution of high-level programming languages across different platforms.

In plain words

> Bytecode pattern enables behavior driven by data instead of code.

[gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/bytecode.html) documentation states:

> An instruction set defines the low-level operations that can be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine executes these instructions one at a time, using a stack for intermediate values. By combining instructions, complex high-level behavior can be defined.

Sequence diagram

![Bytecode sequence diagram](https://java-design-patterns.com/assets/img/bytecode-sequence-diagram.c5497f31.png)

## [Programmatic Example of Bytecode Pattern in Java](https://java-design-patterns.com/patterns/bytecode/#programmatic-example-of-bytecode-pattern-in-java)

In this programmatic example, we show how the Bytecode pattern in Java can simplify the execution of complex virtual machine instructions through a well-defined set of operations. This real-world example demonstrates how the Bytecode design pattern in Java can streamline game programming by allowing wizards' behavior to be easily adjusted through bytecode instructions.

A team is working on a new game where wizards battle against each other. The wizard behavior needs to be carefully adjusted and iterated hundreds of times through playtesting. It's not optimal to ask the programmer to make changes each time the game designer wants to vary the behavior, so the wizard behavior is implemented as a data-driven virtual machine.

One of the most important game objects is the `Wizard` class.

```java

@AllArgsConstructor
@Setter
@Getter
@Slf4j
public class Wizard {

    private int health;
    private int agility;
    private int wisdom;
    private int numberOfPlayedSounds;
    private int numberOfSpawnedParticles;

    public void playSound() {
        LOGGER.info("Playing sound");
        numberOfPlayedSounds++;
    }

    public void spawnParticles() {
        LOGGER.info("Spawning particles");
        numberOfSpawnedParticles++;
    }
}
```

Next, we show the available instructions for our virtual machine. Each of the instructions has its own semantics on how it operates with the stack data. For example, the ADD instruction takes the top two items from the stack, adds them together and pushes the result to the stack.

```java

@AllArgsConstructor
@Getter
public enum Instruction {

    LITERAL(1),         // e.g. "LITERAL 0", push 0 to stack
    SET_HEALTH(2),      // e.g. "SET_HEALTH", pop health and wizard number, call set health
    SET_WISDOM(3),      // e.g. "SET_WISDOM", pop wisdom and wizard number, call set wisdom
    SET_AGILITY(4),     // e.g. "SET_AGILITY", pop agility and wizard number, call set agility
    PLAY_SOUND(5),      // e.g. "PLAY_SOUND", pop value as wizard number, call play sound
    SPAWN_PARTICLES(6), // e.g. "SPAWN_PARTICLES", pop value as wizard number, call spawn particles
    GET_HEALTH(7),      // e.g. "GET_HEALTH", pop value as wizard number, push wizard's health
    GET_AGILITY(8),     // e.g. "GET_AGILITY", pop value as wizard number, push wizard's agility
    GET_WISDOM(9),      // e.g. "GET_WISDOM", pop value as wizard number, push wizard's wisdom
    ADD(10),            // e.g. "ADD", pop 2 values, push their sum
    DIVIDE(11);         // e.g. "DIVIDE", pop 2 values, push their division

    // Other properties and methods...
}
```

At the heart of our example is the `VirtualMachine` class. It takes instructions as input and executes them to provide the game object behavior.

```java

@Getter
@Slf4j
public class VirtualMachine {

    private final Stack<Integer> stack = new Stack<>();

    private final Wizard[] wizards = new Wizard[2];

    public VirtualMachine() {
        wizards[0] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32),
                0, 0);
        wizards[1] = new Wizard(randomInt(3, 32), randomInt(3, 32), randomInt(3, 32),
                0, 0);
    }

    public VirtualMachine(Wizard wizard1, Wizard wizard2) {
        wizards[0] = wizard1;
        wizards[1] = wizard2;
    }

    public void execute(int[] bytecode) {
        for (var i = 0; i < bytecode.length; i++) {
            Instruction instruction = Instruction.getInstruction(bytecode[i]);
            switch (instruction) {
                case LITERAL:
                    // Read the next byte from the bytecode.
                    int value = bytecode[++i];
                    // Push the next value to stack
                    stack.push(value);
                    break;
                case SET_AGILITY:
                    var amount = stack.pop();
                    var wizard = stack.pop();
                    setAgility(wizard, amount);
                    break;
                case SET_WISDOM:
                    amount = stack.pop();
                    wizard = stack.pop();
                    setWisdom(wizard, amount);
                    break;
                case SET_HEALTH:
                    amount = stack.pop();
                    wizard = stack.pop();
                    setHealth(wizard, amount);
                    break;
                case GET_HEALTH:
                    wizard = stack.pop();
                    stack.push(getHealth(wizard));
                    break;
                case GET_AGILITY:
                    wizard = stack.pop();
                    stack.push(getAgility(wizard));
                    break;
                case GET_WISDOM:
                    wizard = stack.pop();
                    stack.push(getWisdom(wizard));
                    break;
                case ADD:
                    var a = stack.pop();
                    var b = stack.pop();
                    stack.push(a + b);
                    break;
                case DIVIDE:
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(b / a);
                    break;
                case PLAY_SOUND:
                    wizard = stack.pop();
                    getWizards()[wizard].playSound();
                    break;
                case SPAWN_PARTICLES:
                    wizard = stack.pop();
                    getWizards()[wizard].spawnParticles();
                    break;
                default:
                    throw new IllegalArgumentException("Invalid instruction value");
            }
            LOGGER.info("Executed " + instruction.name() + ", Stack contains " + getStack());
        }
    }

    public void setHealth(int wizard, int amount) {
        wizards[wizard].setHealth(amount);
    }

    // Other properties and methods...
}
```

Now we can show the full example utilizing the virtual machine.

```java
public static void main(String[] args) {

    var vm = new VirtualMachine(
            new Wizard(45, 7, 11, 0, 0),
            new Wizard(36, 18, 8, 0, 0));

    vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
    vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
    vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET")));
    vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
    vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY));
    vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
    vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM));
    vm.execute(InstructionConverterUtil.convertToByteCode(ADD));
    vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2));
    vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE));
    vm.execute(InstructionConverterUtil.convertToByteCode(ADD));
    vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET")));
}
```

Here is the console output.

```
16:20:10.193 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0]
16:20:10.196 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 0]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_HEALTH, Stack contains [0, 45]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 0]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_AGILITY, Stack contains [0, 45, 7]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 7, 0]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed GET_WISDOM, Stack contains [0, 45, 7, 11]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 45, 18]
16:20:10.197 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed LITERAL, Stack contains [0, 45, 18, 2]
16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed DIVIDE, Stack contains [0, 45, 9]
16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed ADD, Stack contains [0, 54]
16:20:10.198 [main] INFO com.iluwatar.bytecode.VirtualMachine - Executed SET_HEALTH, Stack contains []
```

Utilizing the Bytecode design pattern in Java can significantly enhance the flexibility and maintainability of your virtual machine-based applications.

## [When to Use the Bytecode Pattern in Java](https://java-design-patterns.com/patterns/bytecode/#when-to-use-the-bytecode-pattern-in-java)

Use the Bytecode pattern when you have a lot of behavior you need to define and your game’s implementation language isn’t a good fit because:

- It’s too low-level, making it tedious or error-prone to program in.
- Iterating on it takes too long due to slow compile times or other tooling issues.
- It has too much trust. If you want to ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of the codebase.

## [Real-World Applications of Bytecode Pattern in Java](https://java-design-patterns.com/patterns/bytecode/#real-world-applications-of-bytecode-pattern-in-java)

- Java Virtual Machine (JVM) uses bytecode to allow Java programs to run on any device that has JVM installed
- Python compiles its scripts to bytecode which is then interpreted by Python Virtual Machine
- The .NET Framework uses a form of bytecode called Microsoft Intermediate Language (MSIL)

## [Benefits and Trade-offs of Bytecode Pattern](https://java-design-patterns.com/patterns/bytecode/#benefits-and-trade-offs-of-bytecode-pattern)

Benefits:

- Portability: Programs can run on any platform that has a compatible VM.
- Security: The VM can enforce security checks on the bytecode.
- Performance: JIT compilers can optimize bytecode at runtime, potentially improving performance over interpreted code.

Trade-offs:

- Overhead: Running bytecode typically involves more overhead than running native code, potentially affecting performance.
- Complexity: Implementing and maintaining a VM adds complexity to the system.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/bytecode/#related-java-design-patterns)

- [Interpreter](https://java-design-patterns.com/patterns/interpreter/) is often used within the implementation of VMs to interpret bytecode instructions
- [Command](https://java-design-patterns.com/patterns/command/): Bytecode instructions can be seen as commands executed by the VM.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): VMs may use factory methods to instantiate operations or instructions defined in the bytecode.

## [References and Credits](https://java-design-patterns.com/patterns/bytecode/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/3K96fOn)
- [Programming Language Pragmatics](https://amzn.to/49Tusnn)
- [Bytecode (Game Programming Patterns)](http://gameprogrammingpatterns.com/bytecode.html)

---

## [behavioral/chain-of-responsibility] Chain of Responsibility 责任链
> 官方文档: https://java-design-patterns.com/patterns/chain-of-responsibility/

BehavioralDecouplingEvent-drivenGang of FourMessagingAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/chain-of-responsibility/#also-known-as)

- Chain of Command
- Chain of Objects
- Responsibility Chain

## [Intent of Chain of Responsibility Design Pattern](https://java-design-patterns.com/patterns/chain-of-responsibility/#intent-of-chain-of-responsibility-design-pattern)

The Chain of Responsibility pattern in Java is a behavioral design pattern that decouples the sender of a request from its receivers by giving more than one object a chance to handle the request. The receiving objects are chained and the request is passed along the chain until an object handles it.

## [Detailed Explanation of Chain of Responsibility Pattern with Real-World Examples](https://java-design-patterns.com/patterns/chain-of-responsibility/#detailed-explanation-of-chain-of-responsibility-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Chain of Responsibility pattern in Java is a technical support call center. When implementing this Java design pattern, each level of support represents a handler in the chain. When a customer calls in with an issue, the call is first received by a front-line support representative. If the issue is simple, the representative handles it directly. If the issue is more complex, the representative forwards the call to a second-level support technician. This process continues, with the call being escalated through multiple levels of support until it reaches a specialist who can resolve the problem. Each level of support represents a handler in the chain, and the call is passed along the chain until it finds an appropriate handler, thereby decoupling the request from the specific receiver.

In plain words

> It helps to build a chain of objects. A request enters from one end and keeps going from an object to another until it finds a suitable handler.

Wikipedia says

> In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.

Flowchart

![Chain of Responsibility flowchart](https://java-design-patterns.com/assets/img/chain-of-responsibility-flowchart.8ba1d5ea.png)

## [Programmatic Example of Chain of Responsibility Pattern](https://java-design-patterns.com/patterns/chain-of-responsibility/#programmatic-example-of-chain-of-responsibility-pattern)

In this Java example, the Orc King gives orders which are processed by a chain of command representing the Chain of Responsibility pattern. Learn how to implement this design pattern in Java with the following code snippet.

The Orc King gives loud orders to his army. The closest one to react is the commander, then an officer, and then a soldier. The commander, officer, and soldier form a chain of responsibility.

First, we have the `Request` class:

```java
@Getter
public class Request {

    private final RequestType requestType;
    private final String requestDescription;
    private boolean handled;

    public Request(final RequestType requestType, final String requestDescription) {
        this.requestType = Objects.requireNonNull(requestType);
        this.requestDescription = Objects.requireNonNull(requestDescription);
    }

    public void markHandled() {
        this.handled = true;
    }

    @Override
    public String toString() {
        return getRequestDescription();
    }
}

public enum RequestType {
    DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
}
```

Next, we show the `RequestHandler` hierarchy.

```java
public interface RequestHandler {

    boolean canHandleRequest(Request req);

    int getPriority();

    void handle(Request req);

    String name();
}

@Slf4j
public class OrcCommander implements RequestHandler {
    @Override
    public boolean canHandleRequest(Request req) {
        return req.getRequestType() == RequestType.DEFEND_CASTLE;
    }

    @Override
    public int getPriority() {
        return 2;
    }

    @Override
    public void handle(Request req) {
        req.markHandled();
        LOGGER.info("{} handling request \"{}\"", name(), req);
    }

    @Override
    public String name() {
        return "Orc commander";
    }
}

// OrcOfficer and OrcSoldier are defined similarly as OrcCommander ...
```

The `OrcKing` gives the orders and forms the chain.

```java
public class OrcKing {

    private List<RequestHandler> handlers;

    public OrcKing() {
        buildChain();
    }

    private void buildChain() {
        handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier());
    }

    public void makeRequest(Request req) {
        handlers
                .stream()
                .sorted(Comparator.comparing(RequestHandler::getPriority))
                .filter(handler -> handler.canHandleRequest(req))
                .findFirst()
                .ifPresent(handler -> handler.handle(req));
    }
}
```

The chain of responsibility in action.

```java
  public static void main(String[] args) {

    var king = new OrcKing();
    king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
    king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
    king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
}
```

The console output:

```
Orc commander handling request "defend castle"
Orc officer handling request "torture prisoner"
Orc soldier handling request "collect tax"
```

## [When to Use the Chain of Responsibility Pattern in Java](https://java-design-patterns.com/patterns/chain-of-responsibility/#when-to-use-the-chain-of-responsibility-pattern-in-java)

Use Chain of Responsibility when

- More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.
- You want to issue a request to one of several objects without specifying the receiver explicitly.
- The set of objects that can handle a request should be specified dynamically.

## [Real-World Applications of Chain of Responsibility Pattern in Java](https://java-design-patterns.com/patterns/chain-of-responsibility/#real-world-applications-of-chain-of-responsibility-pattern-in-java)

- Event bubbling in GUI frameworks where an event might be handled at multiple levels of a UI component hierarchy
- Middleware frameworks where a request passes through a chain of processing objects
- Logging frameworks where messages can be passed through a series of loggers, each possibly handling them differently
- [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29)
- [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html)
- [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-)

## [Benefits and Trade-offs of Chain of Responsibility Pattern](https://java-design-patterns.com/patterns/chain-of-responsibility/#benefits-and-trade-offs-of-chain-of-responsibility-pattern)

Benefits:

- Reduced coupling. The sender of a request does not need to know the concrete handler that will process the request.
- Increased flexibility in assigning responsibilities to objects. You can add or change responsibilities for handling a request by changing the members and order of the chain.
- Allows you to set a default handler if no concrete handler can handle the request.

Trade-Offs:

- It can be challenging to debug and understand the flow, especially if the chain is long and complex.
- The request might end up unhandled if the chain doesn't include a catch-all handler.
- Performance concerns might arise due to potentially going through several handlers before finding the right one, or not finding it at all.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/chain-of-responsibility/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/): can be used to encapsulate a request as an object, which might be passed along the chain.
- [Composite](https://java-design-patterns.com/patterns/composite/): the Chain of Responsibility is often applied in conjunction with the Composite pattern.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): decorators can be chained in a similar manner as responsibilities in the Chain of Responsibility pattern.

## [References and Credits](https://java-design-patterns.com/patterns/chain-of-responsibility/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PAJUg5)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)
- [Pattern languages of program design 3](https://amzn.to/4a4NxTH)

---

## [behavioral/client-session] Client-Session
> 官方文档: https://java-design-patterns.com/patterns/client-session/

BehavioralClient-serverSession managementState trackingWeb developmentAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/client-session/#also-known-as)

- User Session

## [Intent of Client Session Design Pattern](https://java-design-patterns.com/patterns/client-session/#intent-of-client-session-design-pattern)

The Client Session design pattern is essential for web development involving client-server interactions. It aims to maintain a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. This pattern helps in creating a seamless user experience by managing user state and data effectively across different sessions, crucial for modern web applications.

## [Detailed Explanation of Client Session Pattern with Real-World Examples](https://java-design-patterns.com/patterns/client-session/#detailed-explanation-of-client-session-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Client Session pattern is a library membership system. When a member logs in, the system starts a session to track their borrowing activities. This session holds data such as the member's ID, current borrowed books, due dates, and any fines. As the member browses the catalog, borrows books, or returns them, the session maintains this stateful information, ensuring the member's interactions are consistent and personalized until they log out or the session expires. This approach helps the library system manage user-specific data efficiently across multiple interactions, providing a seamless and personalized experience for the members.

In plain words

> The Client Session pattern manages user-specific data across multiple requests within a web application to maintain continuity and personalization.

Wikipedia says

> The client-server model on Wikipedia describes a system where client devices request services and resources from centralized servers. This model is crucial in web applications where client sessions are used to manage user-specific data across multiple requests. For example, when a bank customer accesses online banking services, their login credentials and session state are managed by the web server to maintain continuity of their interactions.

Sequence diagram

![Client Session sequence diagram](https://java-design-patterns.com/assets/img/client-session-sequence-diagram.d9898715.png)

## [Programmatic Example of Client Session Pattern in Java](https://java-design-patterns.com/patterns/client-session/#programmatic-example-of-client-session-pattern-in-java)

The Client Session design pattern is a behavioral design pattern that maintains a user's state and data across multiple requests within a web application, ensuring a continuous and personalized user experience. This pattern is commonly used in web applications where user-specific data needs to be managed across multiple requests.

In the given code, we have a `Server` class and a `Session` class. The `Server` class represents the server that processes incoming requests and assigns sessions to clients. The `Session` class represents a session that is assigned to a client.

```java
// The Server class represents the server that processes incoming requests and assigns sessions to clients.
public class Server {
  private String host;
  private int port;

  public Server(String host, int port) {
    this.host = host;
    this.port = port;
  }

  // Other methods...

  // This method returns a new session for a client.
  public Session getSession(String name) {
    return new Session(name, "ClientName");
  }

  // This method processes a request from a client.
  public void process(Request request) {
    // Process the request...
  }
}

// The Session class represents a session that is assigned to a client.
public class Session {
  private String id;
  private String clientName;

  public Session(String id, String clientName) {
    this.id = id;
    this.clientName = clientName;
  }

  // Other methods...
}
```

In the `main` method, we create an instance of `Server`, create two sessions for two different clients, and then pass these sessions to the server in the request along with the data. The server is then able to interpret the client based on the session associated with it.

```java
public class App {
  public static void main(String[] args) {
    var server = new Server("localhost", 8080);
    var session1 = server.getSession("Session1");
    var session2 = server.getSession("Session2");
    var request1 = new Request("Data1", session1);
    var request2 = new Request("Data2", session2);
    server.process(request1);
    server.process(request2);
  }
}
```

In this example, the `Server` class is responsible for creating and managing sessions for clients, and the `Session` class represents the client's session. The `Request` class represents a request from a client, which includes the client's session and data. The server processes the request based on the client's session.

Running the program produces the following console output:

```
19:28:49.152 [main] INFO com.iluwatar.client.session.Server -- Processing Request with client: Session1 data: Data1
19:28:49.154 [main] INFO com.iluwatar.client.session.Server -- Processing Request with client: Session2 data: Data2
```

## [When to Use the Client Session Pattern in Java](https://java-design-patterns.com/patterns/client-session/#when-to-use-the-client-session-pattern-in-java)

Use the client state pattern when:

- Web applications requiring user authentication and authorization.
- Applications needing to track user activities and preferences over multiple requests or visits.
- Systems where server resources need to be optimized by offloading state management to the client side.

## [Real-World Applications of Client Session Pattern in Java](https://java-design-patterns.com/patterns/client-session/#real-world-applications-of-client-session-pattern-in-java)

- E-commerce websites to track shopping cart contents across sessions.
- Online platforms that offer personalized content based on user preferences and history.
- Web applications requiring user login to access personalized or secured content.

## [Benefits and Trade-offs of Client Session Pattern](https://java-design-patterns.com/patterns/client-session/#benefits-and-trade-offs-of-client-session-pattern)

Benefits:

- Improved server performance by reducing the need to store user state on the server.
- Enhanced user experience through personalized content and seamless navigation across different parts of the application.
- Flexibility in managing sessions through various client-side storage mechanisms (e.g., cookies, Web Storage API).

Trade-offs:

- Potential security risks if sensitive information is stored in client sessions without proper encryption and validation.
- Dependence on client-side capabilities and settings, such as cookie policies, which can vary across browsers and user configurations.
- Increased complexity in session management logic, especially in handling session expiration, renewal, and synchronization across multiple devices or tabs.

## [Related Patterns](https://java-design-patterns.com/patterns/client-session/#related-patterns)

- Server Session: Often used in conjunction with the Client Session pattern to provide a balance between client-side efficiency and server-side control.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Ensuring a single instance of a user's session throughout the application.
- [State](https://java-design-patterns.com/patterns/state/): Managing state transitions in a session, such as authenticated, guest, or expired states.

## [References and Credits](https://java-design-patterns.com/patterns/client-session/#references-and-credits)

- [Professional Java for Web Applications](https://amzn.to/4aazY59)
- [Securing Web Applications with Spring Security](https://amzn.to/3PCCEA1)
- [Client Session State Design Pattern: Explained Simply (Ram N Java)](https://www.youtube.com/watch?v=ycOSj9g41pc)

---

## [behavioral/collecting-parameter] Collecting Parameter
> 官方文档: https://java-design-patterns.com/patterns/collecting-parameter/

BehavioralAccumulationData processingData transferGenericAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/collecting-parameter/#also-known-as)

- Collector
- Accumulator

## [Intent of Collecting Parameter Design Pattern](https://java-design-patterns.com/patterns/collecting-parameter/#intent-of-collecting-parameter-design-pattern)

The Collecting Parameter pattern in Java design patterns aims to simplify method calls by aggregating multiple parameters into a single collection object. This pattern is particularly effective for methods that collect information by passing a single collection object through various method calls. Each method can then add results to this collection, instead of creating its own collection. This approach enhances code readability and maintainability, optimizing the process of information collection in Java programming.

## [Detailed Explanation of Collecting Parameter Pattern with Real-World Examples](https://java-design-patterns.com/patterns/collecting-parameter/#detailed-explanation-of-collecting-parameter-pattern-with-real-world-examples)

Real-world example

> In software development, the Collecting Parameter pattern provides significant benefits by optimizing method calls and improving code maintainability.
>
> Imagine a scenario in a restaurant where a waiter needs to take an order from a customer. Instead of noting down each item separately (e.g., appetizer, main course, dessert, drink), the waiter uses an order form that collects all the items into a single document. This order form simplifies the communication between the waiter and the kitchen staff by aggregating all the details into one place. Similarly, in software, the Collecting Parameter pattern aggregates multiple parameters into a single object, streamlining method calls and improving code readability and maintainability.

In plain words

> The Collecting Parameter pattern simplifies method calls by encapsulating multiple parameters into a single object.

Wikipedia says

> In the Collecting Parameter idiom a collection (list, map, etc.) is passed repeatedly as a parameter to a method which adds items to the collection.

Flowchart

![Collecting Parameter flowchart](https://java-design-patterns.com/assets/img/collecting-parameter-flowchart.80b727ae.png)

## [Programmatic Example of Collecting Parameter Pattern in Java](https://java-design-patterns.com/patterns/collecting-parameter/#programmatic-example-of-collecting-parameter-pattern-in-java)

Within a large corporate building, there exists a global printer queue that is a collection of all the printing jobs that are currently pending. Various floors contain different models of printers, each having a different printing policy. We must construct a program that can continually add appropriate printing jobs to a collection, which is called the collecting parameter.

The following business rules are implemented:

- If an A4 paper is coloured, it must also be single-sided. All other non-coloured papers are accepted
- A3 papers must be non-coloured and single-sided
- A2 papers must be single-page, single-sided, and non-coloured

Let's see the implementation first and explain afterward.

```java
public class App {
  static PrinterQueue printerQueue = PrinterQueue.getInstance();

  public static void main(String[] args) {
    printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false));
    printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false));
    printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A2, 5, false, false));

    var result = new LinkedList<PrinterItem>();

    addValidA4Papers(result);
    addValidA3Papers(result);
    addValidA2Papers(result);
  }

  public static void addValidA4Papers(Queue<PrinterItem> printerItemsCollection) {
    for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
      if (nextItem.paperSize.equals(PaperSizes.A4)) {
        var isColouredAndSingleSided = nextItem.isColour && !nextItem.isDoubleSided;
        if (isColouredAndSingleSided || !nextItem.isColour) {
          printerItemsCollection.add(nextItem);
        }
      }
    }
  }

  public static void addValidA3Papers(Queue<PrinterItem> printerItemsCollection) {
    for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
      if (nextItem.paperSize.equals(PaperSizes.A3)) {
        var isNotColouredAndSingleSided = !nextItem.isColour && !nextItem.isDoubleSided;
        if (isNotColouredAndSingleSided) {
          printerItemsCollection.add(nextItem);
        }
      }
    }
  }

  public static void addValidA2Papers(Queue<PrinterItem> printerItemsCollection) {
    for (PrinterItem nextItem : printerQueue.getPrinterQueue()) {
      if (nextItem.paperSize.equals(PaperSizes.A2)) {
        var isNotColouredSingleSidedAndOnePage = nextItem.pageCount == 1 && !nextItem.isDoubleSided
                && !nextItem.isColour;
        if (isNotColouredSingleSidedAndOnePage) {
          printerItemsCollection.add(nextItem);
        }
      }
    }
  }
}
```

This `App` class is the main entry point of the application. It uses the Collecting Parameter design pattern to filter print jobs based on certain policies.

1. **Initialization**: The `printerQueue` is initialized with three print jobs of different paper sizes (A4, A3, A2).

2. **Creating the Collecting Parameter**: A `LinkedList` named `result` is created to store the print jobs that meet the policy requirements.

3. **Adding Valid Jobs to the Collecting Parameter**: The `addValidA4Papers`, `addValidA3Papers`, and `addValidA2Papers` methods are called. These methods iterate over the `printerQueue` and add the print jobs that meet the policy requirements to the `result` list.


The `result` list, which is the collecting parameter, accumulates the valid print jobs as it is passed from method to method. This is the essence of the Collecting Parameter design pattern.

Utilizing the Collecting Parameter pattern in Java design patterns leads to more efficient method calls and improved overall code structure.

## [When to Use the Collecting Parameter Pattern in Java](https://java-design-patterns.com/patterns/collecting-parameter/#when-to-use-the-collecting-parameter-pattern-in-java)

This pattern is useful for managing parameters in Java coding practices, ensuring efficient code refactoring and enhanced readability.

- Use when a method needs to accept a large number of parameters, making the method signature unwieldy.
- Use when the same group of parameters is passed to multiple methods, reducing redundancy and potential errors.
- Use to improve the readability and maintainability of the code.

## [Collecting Parameter Pattern Java Tutorials](https://java-design-patterns.com/patterns/collecting-parameter/#collecting-parameter-pattern-java-tutorials)

- [Refactoring To Patterns (Joshua Kerivsky)](http://www.tarrani.net/RefactoringToPatterns.pdf)
- [Smalltalk Best Practice Patterns (Kent Beck)](https://ptgmedia.pearsoncmg.com/images/9780134769042/samplepages/013476904X.pdf)

## [Real-World Applications of Collecting Parameter Pattern in Java](https://java-design-patterns.com/patterns/collecting-parameter/#real-world-applications-of-collecting-parameter-pattern-in-java)

- Use when a method needs to accept a large number of parameters, making the method signature unwieldy.
- Use when the same group of parameters is passed to multiple methods, reducing redundancy and potential errors.
- Use to improve the readability and maintainability of the code.

## [Benefits and Trade-offs of Collecting Parameter Pattern](https://java-design-patterns.com/patterns/collecting-parameter/#benefits-and-trade-offs-of-collecting-parameter-pattern)

Benefits:

- Improves code readability by reducing the number of parameters in method signatures.
- Facilitates the reuse of parameter sets across different methods.
- Enhances maintainability by centralizing the parameter structure.

Trade-offs:

- Introduces an additional class, which may increase complexity if not managed properly.
- Can lead to over-generalization if the parameter object becomes too large or unwieldy.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/collecting-parameter/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/): Commands may utilize Collecting Parameter to aggregate results from multiple operations executed by the command objects.
- [Composite](https://java-design-patterns.com/patterns/composite/): Can be used in tandem with Collecting Parameter when dealing with hierarchical structures, allowing results to be collected across a composite structure.
- [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together, where Visitor handles traversal and operations on a structure, and Collecting Parameter accumulates the results.

## [References and Credits](https://java-design-patterns.com/patterns/collecting-parameter/#references-and-credits)

- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/4aApLP0)
- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3TVEgaB)
- [Collecting Parameter (WikiWikiWeb)](https://wiki.c2.com/?CollectingParameter)

---

## [behavioral/command] Command 命令
> 官方文档: https://java-design-patterns.com/patterns/command/

BehavioralDecouplingExtensibilityGang of FourUndoAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/command/#also-known-as)

- Action
- Transaction

## [Intent of Command Design Pattern](https://java-design-patterns.com/patterns/command/#intent-of-command-design-pattern)

The Command design pattern is a behavioral pattern used in Java programming. It encapsulates a request as an object, allowing for parameterization of clients with queues, requests, and operations. This pattern also supports undoable operations, enhancing flexibility in managing and executing commands.

## [Detailed Explanation of Command Pattern with Real-World Examples](https://java-design-patterns.com/patterns/command/#detailed-explanation-of-command-pattern-with-real-world-examples)

Real-world example

> Imagine a smart home system where you can control devices such as lights, thermostats, and security cameras through a central application. Each command to operate these devices is encapsulated as an object, enabling the system to queue, execute sequentially, and undo commands if necessary. This approach decouples control logic from device implementation, allowing easy addition of new devices or features without altering the core application. This flexibility and functionality illustrate the practical application of the Command design pattern in Java programming.

In plain words

> Storing requests as command objects allows performing an action or undoing it at a later time.

Wikipedia says

> In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

Sequence diagram

![Command sequence diagram](https://java-design-patterns.com/assets/img/command-sequence-diagram.b787a512.png)

## [Programmatic Example of Command Pattern in Java](https://java-design-patterns.com/patterns/command/#programmatic-example-of-command-pattern-in-java)

In the Command pattern, objects are used to encapsulate all information needed to perform an action or trigger an event at a later time. This pattern is particularly useful for implementing undo functionality in applications.

In our example, a `Wizard` casts spells on a `Goblin`. Each spell is a command object that can be executed and undone, demonstrating the core principles of the Command pattern in Java. The spells are executed on the goblin one by one. The first spell shrinks the goblin and the second makes him invisible. Then the wizard reverses the spells one by one. Each spell here is a command object that can be undone.

Let's start from the `Wizard` class.

```java

@Slf4j
public class Wizard {

    private final Deque<Runnable> undoStack = new LinkedList<>();
    private final Deque<Runnable> redoStack = new LinkedList<>();

    public Wizard() {
    }

    public void castSpell(Runnable runnable) {
        runnable.run();
        undoStack.offerLast(runnable);
    }

    public void undoLastSpell() {
        if (!undoStack.isEmpty()) {
            var previousSpell = undoStack.pollLast();
            redoStack.offerLast(previousSpell);
            previousSpell.run();
        }
    }

    public void redoLastSpell() {
        if (!redoStack.isEmpty()) {
            var previousSpell = redoStack.pollLast();
            undoStack.offerLast(previousSpell);
            previousSpell.run();
        }
    }

    @Override
    public String toString() {
        return "Wizard";
    }
}
```

Next, we have the `Goblin` who's the `Target` of the spells.

```java
@Slf4j
@Getter
@Setter
public abstract class Target {

    private Size size;

    private Visibility visibility;

    public void printStatus() {
        LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility());
    }

    public void changeSize() {
        var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL;
        setSize(oldSize);
    }

    public void changeVisibility() {
        var visible = getVisibility() == Visibility.INVISIBLE
                ? Visibility.VISIBLE : Visibility.INVISIBLE;
        setVisibility(visible);
    }
}
```

```java
public class Goblin extends Target {

    public Goblin() {
        setSize(Size.NORMAL);
        setVisibility(Visibility.VISIBLE);
    }

    @Override
    public String toString() {
        return "Goblin";
    }
}
```

Finally, we can show the full example of `Wizard` casting spells.

```java
public static void main(String[] args) {
    var wizard = new Wizard();
    var goblin = new Goblin();

    goblin.printStatus();

    wizard.castSpell(goblin::changeSize);
    goblin.printStatus();

    wizard.castSpell(goblin::changeVisibility);
    goblin.printStatus();

    wizard.undoLastSpell();
    goblin.printStatus();

    wizard.undoLastSpell();
    goblin.printStatus();

    wizard.redoLastSpell();
    goblin.printStatus();

    wizard.redoLastSpell();
    goblin.printStatus();
}
```

Here's the program output:

```
20:13:38.406 [main] INFO com.iluwatar.command.Target -- Goblin, [size=normal] [visibility=visible]
20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=visible]
20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=invisible]
20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=visible]
20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=normal] [visibility=visible]
20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=visible]
20:13:38.409 [main] INFO com.iluwatar.command.Target -- Goblin, [size=small] [visibility=invisible]
```

## [When to Use the Command Pattern in Java](https://java-design-patterns.com/patterns/command/#when-to-use-the-command-pattern-in-java)

The Command design pattern is applicable when you need to parameterize objects with actions, support undo operations, or structure a system around high-level operations built on primitive ones. It is commonly used in GUI buttons, database transactions, and macro recording.

Use the Command pattern when you want to:

- Parameterize objects with actions to perform, offering an object-oriented alternative to callbacks found in procedural languages. Commands can be registered and executed later.
- Specify, queue, and execute requests at different times, allowing commands to exist independently of the original request and even be transferred across processes.
- Support undo functionality, where the Command’s execute operation stores state and includes an un-execute operation to reverse previous actions. This allows for unlimited undo and redo capabilities by maintaining a history list.
- Log changes to reapply them after a system crash. By adding load and store operations to the Command interface, you can maintain a persistent log of changes and recover by reloading and re-executing commands from this log.
- Structure a system around high-level operations built on primitive operations, which is common in transaction-based systems. The Command pattern models transactions by providing a common interface for invoking and extending operations.
- Keep a history of requests.
- Implement callback functionality.
- Implement undo functionality.

## [Real-World Applications of Command Pattern in Java](https://java-design-patterns.com/patterns/command/#real-world-applications-of-command-pattern-in-java)

- GUI Buttons and menu items in desktop applications.
- Operations in database systems and transactional systems that support rollback.
- Macro recording in applications like text editors and spreadsheets.
- [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)
- [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java)
- [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki)
- [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html)

## [Benefits and Trade-offs of Command Pattern](https://java-design-patterns.com/patterns/command/#benefits-and-trade-offs-of-command-pattern)

Benefits:

- Decouples the object that invokes the operation from the one that knows how to perform it.
- It's easy to add new Commands, because you don't have to change existing classes.
- You can assemble a set of commands into a composite command.

Trade-offs:

- Increases the number of classes for each individual command.
- Can complicate the design by adding multiple layers between senders and receivers.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/command/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Commands can be composed using the Composite pattern to create macro commands.
- [Memento](https://java-design-patterns.com/patterns/memento/): Can be used for implementing undo mechanisms.
- [Observer](https://java-design-patterns.com/patterns/observer/): The pattern can be observed for changes that trigger commands.

## [References and Credits](https://java-design-patterns.com/patterns/command/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Pattern-Oriented Software Architecture, Volume 1: A System of Patterns](https://amzn.to/3PFUqSY)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [behavioral/commander] Commander
> 官方文档: https://java-design-patterns.com/patterns/commander/

BehavioralCloud distributedMicroservicesTransactionsAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/commander/#also-known-as)

- Distributed Transaction Commander
- Transaction Coordinator

## [Intent of Commander Design Pattern](https://java-design-patterns.com/patterns/commander/#intent-of-commander-design-pattern)

The intent of the Commander pattern in Java, especially in the context of distributed transactions, is to manage and coordinate complex transactions across multiple distributed components or services. This pattern ensures data consistency and integrity in distributed systems, making it crucial for microservices architecture. It encapsulates transaction commands and coordination logic, facilitating the implementation of distributed transaction protocols like two-phase commit or Saga.

## [Detailed Explanation of Commander Pattern with Real-World Examples](https://java-design-patterns.com/patterns/commander/#detailed-explanation-of-commander-pattern-with-real-world-examples)

Real-world example

> Imagine organizing a large international music festival where various bands from around the world are scheduled to perform. Each band's arrival, soundcheck, and performance are akin to individual transactions in a distributed system. This scenario mirrors the Commander pattern in Java, where the "Commander" coordinates distributed transactions to maintain overall consistency and reliability. The festival organizer acts as the "Commander," coordinating these transactions to ensure that if a band's flight is delayed (akin to a transaction failure), there's a backup plan, such as rescheduling or swapping time slots with another band (compensating actions), to keep the overall schedule intact. This setup mirrors the Commander pattern in distributed transactions, where various components must be coordinated to achieve a successful outcome despite individual failures.

In plain words

> The Commander pattern turns a request into a stand-alone object, allowing for the parameterization of commands, queueing of actions, and the implementation of undo operations.

Sequence diagram

![Commander sequence diagram](https://java-design-patterns.com/assets/img/commander-sequence-diagram.3fa41977.png)

## [Programmatic Example of Commander Pattern in Java](https://java-design-patterns.com/patterns/commander/#programmatic-example-of-commander-pattern-in-java)

Managing transactions across different services in a distributed system, such as an e-commerce platform with separate `Payment` and `Shipping` microservices, requires careful coordination. Using the Commander pattern in Java for transaction coordination helps ensure data consistency and reliability, even when services experience partial failures.

A strategy to address this involves using a `Commander` component that orchestrates the process. Initially, the order is processed by the available service (`Shipping` in this case). The `Commander` then attempts to synchronize the order with the currently unavailable service (`Payment`) by storing the order details in a database or queueing it for future processing. This queueing system must also account for possible failures in adding requests to the queue.

The `Commander` repeatedly tries to process the queued orders to ensure both services eventually reflect the same transaction data. This process involves ensuring idempotence, meaning that even if the same order synchronization request is made multiple times, it will only be executed once, preventing duplicate transactions. The goal is to achieve eventual consistency across services, where all systems are synchronized over time despite initial failures or delays.

Here's a simplified example of how the `Commander` class is used in the `AppAllCases` class:

```java
public class AppAllCases {
  // ... other methods ...

  // Shipping Database Fail Cases
  void itemUnavailableCase() {
    var ps = new PaymentService(new PaymentDatabase());
    var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
    var ms = new MessagingService(new MessagingDatabase());
    var eh = new EmployeeHandle(new EmployeeDatabase());
    var qdb = new QueueDatabase();
    // Create a Commander instance
    var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
    var user = new User("Jim", "ABCD");
    var order = new Order(user, "book", 10f);
    // Use the Commander instance to place an order
    c.placeOrder(order);
  }

  // ... other methods ...
}
```

In the `itemUnavailableCase` method, a `Commander` instance is created with the respective services and their databases. Then, a `User` and an `Order` are created, and the `placeOrder` method of the `Commander` instance is called with the order. This triggers the process of placing the order and handling any failures according to the Commander pattern.

The `Commander` class encapsulates the logic for handling the order placement and any potential failures. This separation of concerns makes the code easier to understand and maintain, and it allows for the reuse of the `Commander` class in different parts of the application. In a real-world application, the `Commander` class would be more complex and would include additional logic for handling different types of failures, retrying failed operations, and coordinating transactions across multiple services.

Here is the output from executing the `itemUnavailableCase`:

```
09:10:13.894 [main] DEBUG com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Error in creating shipping request..
09:10:13.896 [main] INFO com.iluwatar.commander.Commander -- This item is currently unavailable. We will inform you as soon as the item becomes available again.
09:10:13.896 [main] INFO com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Item book unavailable, trying to add problem to employee handle..
09:10:13.897 [Thread-0] INFO com.iluwatar.commander.Commander -- Order YN3V8B7IL2PI: Added order to employee database
```

## [When to Use the Commander Pattern in Java](https://java-design-patterns.com/patterns/commander/#when-to-use-the-commander-pattern-in-java)

Use the Commander pattern in Java for distributed transactions when:

- You need to ensure data consistency across distributed services in the event of partial system failures.
- Transactions span multiple microservices or distributed components requiring coordinated commit or rollback.
- You are implementing long-lived transactions requiring compensating actions for rollback.

## [Real-World Applications of Commander Pattern in Java](https://java-design-patterns.com/patterns/commander/#real-world-applications-of-commander-pattern-in-java)

- Two-Phase Commit (2PC) Protocols: Coordinating commit or rollback across distributed databases or services.
- Saga Pattern Implementations: Managing long-lived business processes that span multiple microservices, with each step having a compensating action for rollback.
- Distributed Transactions in Microservices Architecture: Coordinating complex operations across microservices while maintaining data integrity and consistency.

## [Benefits and Trade-offs of Commander Pattern](https://java-design-patterns.com/patterns/commander/#benefits-and-trade-offs-of-commander-pattern)

Benefits:

- Provides a clear mechanism for managing complex distributed transactions, enhancing system reliability.
- Enables the implementation of compensating transactions, which are crucial for maintaining consistency in long-lived transactions.
- Facilitates the integration of heterogeneous systems within a transactional context.

Trade-offs:

- Increases complexity, especially in failure scenarios, due to the need for coordinated rollback mechanisms.
- Potentially impacts performance due to the overhead of coordination and consistency checks.
- Saga-based implementations can lead to increased complexity in understanding the overall business process flow.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/commander/#related-java-design-patterns)

- [Saga Pattern](https://java-design-patterns.com/patterns/saga/): Often discussed in tandem with the Commander pattern for distributed transactions, focusing on long-lived transactions with compensating actions.

## [References and Credits](https://java-design-patterns.com/patterns/commander/#references-and-credits)

- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4aATcRe)
- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4axHwOV)
- [Microservices Patterns: With examples in Java](https://amzn.to/4axjnYW)
- [Distributed Transactions: The Icebergs of Microservices (Graham Lea)](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/)

---

## [behavioral/context-object] Context Object
> 官方文档: https://java-design-patterns.com/patterns/context-object/

BehavioralContextDecouplingEncapsulationSession managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/context-object/#also-known-as)

- Context
- Context Encapsulation
- Context Holder
- Encapsulate Context

## [Intent of Context Object Design Pattern](https://java-design-patterns.com/patterns/context-object/#intent-of-context-object-design-pattern)

Encapsulate the context (state and behaviors) relevant to the user or the request being processed to decouple Java application components from the complexities of the environment. This design pattern helps in managing the application's context efficiently.

## [Detailed Explanation of Context Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/context-object/#detailed-explanation-of-context-object-pattern-with-real-world-examples)

Real-world example

> Imagine a busy airport where multiple services need to access and share passenger information throughout their journey. Instead of each service requesting and passing passenger details separately, the airport uses a "Passenger Context Object." This context object holds all relevant passenger information, such as identity, flight details, and preferences. Various services like check-in, security, boarding, and customer service access this context object to get or update passenger data as needed. This approach ensures consistent and efficient information handling without tightly coupling the services, similar to how the Context Object design pattern works in software.

In plain words

> Create an object to store and manage context data, and pass this context object wherever needed in the Java application, ensuring decoupled and cleaner code.

[Core J2EE Patterns](http://corej2eepatterns.com/ContextObject.htm) says

> Use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application.

Sequence diagram

![Context Object sequence diagram](https://java-design-patterns.com/assets/img/context-object-sequence-diagram.094da2dc.png)

## [Programmatic Example of Context Object in Java](https://java-design-patterns.com/patterns/context-object/#programmatic-example-of-context-object-in-java)

In a multi-layered Java application, different layers such as A, B, and C extract specific information from a shared context. Passing each piece of information individually is inefficient. The Context Object pattern efficiently stores and passes this information, improving the overall performance and maintainability of the Java application.

Define the data that the `ServiceContext` object contains.

```java
@Getter
@Setter
public class ServiceContext {

    String accountService;
    String sessionService;
    String searchService;
}
```

Create interface `ServiceContextFactory` to be used in parts of the application for context objects to be created.

```java
public class ServiceContextFactory {

    public static ServiceContext createContext() {
        return new ServiceContext();
    }
}
```

Instantiate the context object in the first layer. The adjoining layer calls the context in the current layer, which then further structures the object.

```java
@Getter
public class LayerA {

    private static ServiceContext context;

    public LayerA() {
        context = ServiceContextFactory.createContext();
    }

    public void addAccountInfo(String accountService) {
        context.setACCOUNT_SERVICE(accountService);
    }
}
```

```java
@Getter
public class LayerB {

    private static ServiceContext context;

    public LayerB(LayerA layerA) {
        this.context = layerA.getContext();
    }

    public void addSessionInfo(String sessionService) {
        context.setSESSION_SERVICE(sessionService);
    }
}
```

```java
@Getter
public class LayerC {

    public static ServiceContext context;

    public LayerC(LayerB layerB) {
        this.context = layerB.getContext();
    }

    public void addSearchInfo(String searchService) {
        context.setSEARCH_SERVICE(searchService);
    }
}
```

Here is the context object and layers in action.

```java
@Slf4j
public class App {

    private static final String SERVICE = "SERVICE";

    public static void main(String[] args) {
        //Initiate first layer and add service information into context
        var layerA = new LayerA();
        layerA.addAccountInfo(SERVICE);

        logContext(layerA.getContext());

        //Initiate second layer and preserving information retrieved in first layer through passing context object
        var layerB = new LayerB(layerA);
        layerB.addSessionInfo(SERVICE);

        logContext(layerB.getContext());

        //Initiate third layer and preserving information retrieved in first and second layer through passing context object
        var layerC = new LayerC(layerB);
        layerC.addSearchInfo(SERVICE);

        logContext(layerC.getContext());
    }

    private static void logContext(ServiceContext context) {
        LOGGER.info("Context = {}", context);
    }
}
```

Program output:

```
08:15:32.134 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b
08:15:32.136 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b
08:15:32.137 [main] INFO com.iluwatar.context.object.App -- Context = com.iluwatar.context.object.ServiceContext@5577140b
```

## [When to Use the Context Object Pattern in Java](https://java-design-patterns.com/patterns/context-object/#when-to-use-the-context-object-pattern-in-java)

- When there is a need to abstract and encapsulate context information in a Java application to avoid cluttering the business logic with environment-specific code. This is especially useful in web applications for encapsulating request-specific information and in distributed systems for managing user preferences and security credentials.
- In web applications, to encapsulate request-specific information and make it easily accessible throughout the application without passing it explicitly between functions or components.
- In distributed systems, to encapsulate contextual information about the task being performed, user preferences, or security credentials, facilitating their propagation across different components and services.

## [Real-World Applications of Context Object Pattern in Java](https://java-design-patterns.com/patterns/context-object/#real-world-applications-of-context-object-pattern-in-java)

- Web application frameworks often use the Context Object pattern to encapsulate HTTP request and response objects, session information, and other request-specific data. Enterprise Java applications leverage this pattern to manage and propagate transactional information, security credentials, and user-specific settings across different layers and services.
- Enterprise applications use Context Objects to manage and propagate transactional information, security credentials, and user-specific settings across different layers and services.
- [Spring: ApplicationContext](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html)
- [Oracle: SecurityContext](https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/SecurityContext.html)
- [Oracle: ServletContext](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html)

## [Benefits and Trade-offs of Context Object Pattern](https://java-design-patterns.com/patterns/context-object/#benefits-and-trade-offs-of-context-object-pattern)

Benefits:

- Decoupling: Components and services are decoupled from the specificities of the execution environment, enhancing modularity and maintainability.
- Centralization: Contextual information is centralized in one place, making it easier to manage, access, and debug.
- Flexibility: The pattern allows for flexible and dynamic context management, which can adapt to changes in the environment or requirements.

Trade-offs:

- Overhead: Introducing a Context Object can add overhead in terms of performance, especially if not implemented efficiently.
- Complexity: If the Context Object is not well-designed, it can become a bloated and complex monolith, difficult to manage and understand.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/context-object/#related-java-design-patterns)

- [Singleton](https://java-design-patterns.com/patterns/singleton/): The Context Object is often implemented as a Singleton to ensure a global point of access.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Context Objects can use Strategies to adapt their behavior based on the context they encapsulate.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to dynamically add responsibilities to the Context Object.

## [References and Credits](https://java-design-patterns.com/patterns/context-object/#references-and-credits)

- [Core J2EE Design Patterns](https://amzn.to/3IhcY9w)
- [Context Object (Core J2EE Patterns)](http://corej2eepatterns.com/ContextObject.htm)
- [The Encapsulate Context Pattern (Accu)](https://accu.org/journals/overload/12/63/kelly_246/)
- [Context Object - A Design Pattern for Efficient Information Sharing across Multiple System Layers (Arvid S. Krishna et al.)](https://www.dre.vanderbilt.edu/~schmidt/PDF/Context-Object-Pattern.pdf)

---

## [behavioral/data-mapper] Data Mapper
> 官方文档: https://java-design-patterns.com/patterns/data-mapper/

BehavioralData accessDecouplingDomainObject mappingPersistenceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/data-mapper/#also-known-as)

- Object-Relational Mapping (ORM)

## [Intent of the Data Mapper Pattern](https://java-design-patterns.com/patterns/data-mapper/#intent-of-the-data-mapper-pattern)

The Data Mapper pattern aims to create an abstraction layer between the database and the business logic, allowing them to evolve independently. It maps data from the database objects to in-memory data structures and vice versa, minimizing direct dependencies between the application's core logic and the underlying database structure. This decoupling is essential in promoting maintainability and flexibility in Java programming.

## [Detailed Explanation of Data Mapper Pattern with Real-World Examples](https://java-design-patterns.com/patterns/data-mapper/#detailed-explanation-of-data-mapper-pattern-with-real-world-examples)

Real-world example

> Consider a library system where books are stored in a database with complex relationships and various attributes such as title, author, publication year, and genre. In this scenario, a Data Mapper pattern can be used to map the database records of books to in-memory objects in the application. The Data Mapper would handle the retrieval, storage, and update of book objects in the database, allowing the application's business logic to work directly with the book objects without concern for the underlying database structure. This separation makes it easier to change the database schema without affecting the business logic, and vice versa.

In plain words

> A layer of mappers that moves data between objects and a database while keeping them independent of each other.

Wikipedia says

> A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in-memory data representation (the domain layer). The goal of the pattern is to keep the in-memory representation and the persistent data store independent of each other and the data mapper itself. This is useful when one needs to model and enforce strict business processes on the data in the domain layer that do not map neatly to the persistent data store.

Sequence diagram

![Data Mapper sequence diagram](https://java-design-patterns.com/assets/img/data-mapper-sequence-diagram.3bcc93d0.png)

## [Programmatic Example of Data Mapper Pattern in Java](https://java-design-patterns.com/patterns/data-mapper/#programmatic-example-of-data-mapper-pattern-in-java)

The Data Mapper is a design pattern that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. This pattern promotes the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns).

In the data-mapper module, the pattern is demonstrated using a `Student` class and a `StudentDataMapper` interface.

The `Student` class is a simple POJO (Plain Old Java Object) that represents a student. It has properties like studentId, name, and grade.

```java
public class Student {
    private int studentId;
    private String name;
    private char grade;
    // ...
}
```

The `StudentDataMapper` interface defines the operations that can be performed on `Student` objects. These operations include `insert`, `update`, `delete`, and `find`.

```java
public interface StudentDataMapper {
    void insert(final Student student);

    void update(final Student student);

    void delete(final Student student);

    Optional<Student> find(final int studentId);
    // ...
}
```

The `StudentDataMapperImpl` class implements the `StudentDataMapper` interface. It contains the actual logic for interacting with the database.

```java
public class StudentDataMapperImpl implements StudentDataMapper {
    // ...
    @Override
    public void insert(final Student student) {
        // Insert student into the database
    }

    @Override
    public void update(final Student student) {
        // Update student in the database
    }

    @Override
    public void delete(final Student student) {
        // Delete student from the database
    }

    @Override
    public Optional<Student> find(final int studentId) {
        // Find student in the database
    }
    // ...
}
```

The `App` class contains the main method that demonstrates the use of the `StudentDataMapper`. It creates a `Student` object, inserts it into the database, finds it, updates it, and finally deletes it.

```java
public class App {
    public static void main(final String... args) {
        final var mapper = new StudentDataMapperImpl();
        var student = new Student(1, "Adam", 'A');
        mapper.insert(student);
        final var studentToBeFound = mapper.find(student.getStudentId());
        student = new Student(student.getStudentId(), "AdamUpdated", 'A');
        mapper.update(student);
        mapper.delete(student);
    }
}
```

Program output:

```
13:54:29.234 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=Adam, grade=A), is inserted
13:54:29.237 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Optional[Student(studentId=1, name=Adam, grade=A)], is searched
13:54:29.237 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is updated
13:54:29.238 [main] DEBUG com.iluwatar.datamapper.App -- App.main(), student : Student(studentId=1, name=AdamUpdated, grade=A), is going to be deleted
```

## [When to Use the Data Mapper Pattern in Java](https://java-design-patterns.com/patterns/data-mapper/#when-to-use-the-data-mapper-pattern-in-java)

Use the Data Mapper in any of the following situations

- When there's a need to decouple the in-memory objects from the database entities to promote the [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) and [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns).
- In applications requiring an ORM tool to bridge the gap between object-oriented models and relational databases.
- When working with complex database schemas where direct data manipulation and object creation lead to cumbersome and error-prone code.

## [Data Mapper Pattern Java Tutorials](https://java-design-patterns.com/patterns/data-mapper/#data-mapper-pattern-java-tutorials)

- [Spring Boot RowMapper (ZetCode)](https://zetcode.com/springboot/rowmapper/)
- [Spring BeanPropertyRowMapper tutorial (ZetCode)](https://zetcode.com/spring/beanpropertyrowmapper/)
- [Data Transfer Object Pattern in Java - Implementation and Mapping (StackAbuse)](https://stackabuse.com/data-transfer-object-pattern-in-java-implementation-and-mapping/)

## [Real-World Applications of Data Mapper Pattern in Java](https://java-design-patterns.com/patterns/data-mapper/#real-world-applications-of-data-mapper-pattern-in-java)

- ORM frameworks such as Hibernate in Java.
- Data access layers in enterprise applications where business logic and database management are kept separate.
- Applications requiring database interactions without tying the code to a specific database implementation.

## [Benefits and Trade-offs of Data Mapper Pattern](https://java-design-patterns.com/patterns/data-mapper/#benefits-and-trade-offs-of-data-mapper-pattern)

Benefits:

- Promotes [Single Responsibility Principle](https://java-design-patterns.com/principles/#single-responsibility-principle) by separating persistence logic from business logic.
- Enhances maintainability and readability by centralizing data interaction logic.
- Improves application's ability to adapt to changes in the database schema with minimal changes to the business logic.

Trade-offs:

- Introduces complexity through the additional abstraction layer.
- Might lead to performance overhead due to the abstraction layer, especially in large-scale applications or with complex queries.
- Requires developers to learn and understand the abstraction layer in addition to the database and ORM framework being used.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/data-mapper/#related-java-design-patterns)

- Active Record: Combines data access logic and business logic in the domain entities themselves, contrary to Data Mapper's separation of concerns.
- Object–Relational Mapping (ORM): A technique to map object-oriented programming language data to a relational database.
- [Repository](https://java-design-patterns.com/patterns/repository/): Provides an abstraction of the data layer, acting as a collection of domain objects in memory.
- [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Manages transactions and keeps track of the objects affected by a business transaction to ensure changes are consistent and transactional.

## [References and Credits](https://java-design-patterns.com/patterns/data-mapper/#references-and-credits)

- [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3xyEFag)
- [Java Persistence with Hibernate](https://amzn.to/3VNzlKe)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [behavioral/delegation] Delegation
> 官方文档: https://java-design-patterns.com/patterns/delegation/

BehavioralDecouplingDelegationObject compositionAbout 2 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/delegation/#also-known-as)

- Helper
- Surrogate

## [Intent of Delegation Design Pattern](https://java-design-patterns.com/patterns/delegation/#intent-of-delegation-design-pattern)

To allow an object to delegate responsibility for a task to another helper object.

## [Detailed Explanation of Delegation Pattern with Real-World Examples](https://java-design-patterns.com/patterns/delegation/#detailed-explanation-of-delegation-pattern-with-real-world-examples)

Real-world example

> In a restaurant, the head chef delegates tasks to sous-chefs: one manages grilling, another handles salads, and a third is in charge of desserts. Each sous-chef specializes in their area, allowing the head chef to focus on overall kitchen management. This mirrors the Delegation design pattern, where a main object delegates specific tasks to helper objects, each expert in their domain.

In plain words

> Delegation is a design pattern where an object passes on a task to a helper object.

Wikipedia says

> In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). Delegation can be done explicitly, by passing the sending object to the receiving object, which can be done in any object-oriented language; or implicitly, by the member lookup rules of the language, which requires language support for the feature.

Sequence diagram

![Delegation sequence diagram](https://java-design-patterns.com/assets/img/delegation-sequence-diagram.ca137059.png)

## [Programmatic Example of Delegation Pattern in Java](https://java-design-patterns.com/patterns/delegation/#programmatic-example-of-delegation-pattern-in-java)

Let's consider a printing example.

We have an interface `Printer` and three implementations `CanonPrinter`, `EpsonPrinter` and `HpPrinter`.

```java
public interface Printer {
    void print(final String message);
}

@Slf4j
public class CanonPrinter implements Printer {
    @Override
    public void print(String message) {
        LOGGER.info("Canon Printer : {}", message);
    }
}

@Slf4j
public class EpsonPrinter implements Printer {
    @Override
    public void print(String message) {
        LOGGER.info("Epson Printer : {}", message);
    }
}

@Slf4j
public class HpPrinter implements Printer {
    @Override
    public void print(String message) {
        LOGGER.info("HP Printer : {}", message);
    }
}
```

The `PrinterController` can be used as a `Printer` by delegating any work handled by this interface to an object implementing it.

```java
public class PrinterController implements Printer {

    private final Printer printer;

    public PrinterController(Printer printer) {
        this.printer = printer;
    }

    @Override
    public void print(String message) {
        printer.print(message);
    }
}
```

In the client code, printer controllers can print messages differently depending on the object they're delegating that work to.

```java
public class App {

    private static final String MESSAGE_TO_PRINT = "hello world";

    public static void main(String[] args) {
        var hpPrinterController = new PrinterController(new HpPrinter());
        var canonPrinterController = new PrinterController(new CanonPrinter());
        var epsonPrinterController = new PrinterController(new EpsonPrinter());

        hpPrinterController.print(MESSAGE_TO_PRINT);
        canonPrinterController.print(MESSAGE_TO_PRINT);
        epsonPrinterController.print(MESSAGE_TO_PRINT);
    }
}
```

Program output:

```
HP Printer:hello world
Canon Printer:hello world
Epson Printer:hello world
```

## [When to Use the Delegation Pattern in Java](https://java-design-patterns.com/patterns/delegation/#when-to-use-the-delegation-pattern-in-java)

- When you want to pass responsibility from one class to another without inheritance.
- To achieve composition-based reuse instead of inheritance-based.
- When you need to use several interchangeable helper classes at runtime.

## [Real-World Applications of Delegation Pattern in Java](https://java-design-patterns.com/patterns/delegation/#real-world-applications-of-delegation-pattern-in-java)

- Java's java.awt.event package, where listeners are often used to handle events.
- Wrapper classes in Java's Collections Framework (java.util.Collections), which delegate to other collection objects.
- In Spring Framework, delegation is used extensively in the IoC container where beans delegate tasks to other beans.

## [Benefits and Trade-offs of Delegation Pattern](https://java-design-patterns.com/patterns/delegation/#benefits-and-trade-offs-of-delegation-pattern)

Benefits:

- Reduces subclassing: Objects can delegate operations to different objects and change them at runtime, reducing the need for subclassing.
- Encourages reuse: Delegation promotes the reuse of the helper object's code.
- Increases flexibility: By delegating tasks to helper objects, you can change the behavior of your classes at runtime.

Trade-offs:

- Runtime Overhead: Delegation can introduce additional layers of indirection, which may result in slight performance costs.
- Complexity: The design can become more complicated since it involves additional classes and interfaces to manage delegation.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/delegation/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Delegation can be used within a composite pattern to delegate component-specific behavior to child components.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Delegation is often used in the strategy pattern where a context object delegates tasks to a strategy object.
- [https://java-design-patterns.com/patterns/proxy/:](https://java-design-patterns.com/patterns/proxy/:) The proxy pattern is a form of delegation where a proxy object controls access to another object, which it delegates work to.

## [References and Credits](https://java-design-patterns.com/patterns/delegation/#references-and-credits)

- [Effective Java](https://amzn.to/4aGE7gX)
- [Head First Design Patterns](https://amzn.to/3J9tuaB)
- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3VOcRsw)
- [Delegate Pattern: Wikipedia](https://en.wikipedia.org/wiki/Delegation_pattern)

---

## [behavioral/dirty-flag] Dirty Flag
> 官方文档: https://java-design-patterns.com/patterns/dirty-flag/

BehavioralGame programmingPerformanceResource managementState trackingAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/dirty-flag/#also-known-as)

- Change Tracking
- Is-Modified Flag

## [Intent of Dirty Flag Design Pattern](https://java-design-patterns.com/patterns/dirty-flag/#intent-of-dirty-flag-design-pattern)

The Dirty Flag design pattern is employed to avoid unnecessary computations or resource-heavy operations by maintaining a boolean flag that tracks whether the state of an object has changed ('dirty') or remains unchanged ('clean'). This flag, when set, indicates that a particular operation, such as recalculating or refreshing data, needs to be performed again to reflect the updated state.

## [Detailed Explanation of Dirty Flag Pattern with Real-World Examples](https://java-design-patterns.com/patterns/dirty-flag/#detailed-explanation-of-dirty-flag-pattern-with-real-world-examples)

Real-world example

> Imagine a library with an electronic catalog system that tracks which books are checked out and returned. Each book record has a "dirty flag" that gets marked whenever a book is checked out or returned. At the end of each day, the library staff reviews only those records marked as "dirty" to update the physical inventory, instead of checking every single book in the library. This system significantly reduces the effort and time required for daily inventory checks by focusing only on the items that have changed status, analogous to how the Dirty Flag design pattern minimizes resource-intensive operations by performing them only when necessary.

In plain words

> The Dirty Flag design pattern minimizes unnecessary operations by using a flag to track when an object's state has changed and an update is needed.

Wikipedia says

> A dirty bit or modified bit is a bit that is associated with a block of computer memory and indicates whether the corresponding block of memory has been modified. The dirty bit is set when the processor writes to (modifies) this memory. The bit indicates that its associated block of memory has been modified and has not been saved to storage yet. When a block of memory is to be replaced, its corresponding dirty bit is checked to see if the block needs to be written back to secondary memory before being replaced or if it can simply be removed. Dirty bits are used by the CPU cache and in the page replacement algorithms of an operating system.

Flowchart

![Dirty Flag flowchart](https://java-design-patterns.com/assets/img/dirty-flag-flowchart.d0ae61d6.png)

## [Programmatic Example of Dirty Flag Pattern in Java](https://java-design-patterns.com/patterns/dirty-flag/#programmatic-example-of-dirty-flag-pattern-in-java)

The `DataFetcher` class is responsible for fetching data from a file. It has a dirty flag that indicates whether the data in the file has changed since the last fetch.

```java
public class DataFetcher {
    private long lastFetched;
    private boolean isDirty = true;
    // Other properties and methods...
}
```

The `DataFetcher` class has a fetch method that checks the dirty flag before fetching data. If the flag is true, it fetches the data from the file and sets the flag to false. If the flag is false, it returns the previously fetched data.

```java
public List<String> fetch() {
    if (!isDirty) {
        return data;
    }
    data = fetchFromDatabase();
    isDirty = false;
    return data;
}
```

The `World` class uses the `DataFetcher` to fetch data. It has a `fetch` method that calls the `fetch` method of the `DataFetcher`.

```java
public class World {
    private final DataFetcher fetcher = new DataFetcher();

    public List<String> fetch() {
        return fetcher.fetch();
    }
}
```

The `App` class contains the `main` method that demonstrates the use of the Dirty Flag pattern. It creates a `World` object and fetches data from it in a loop. The `World` object uses the `DataFetcher` to fetch data, and the `DataFetcher` only fetches data from the file if the dirty flag is true.

```java
@Slf4j
public class App {

  public void run() {
    final var executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
      final World world = new World();

      @Override
      public void run() {
        var countries = world.fetch();
        LOGGER.info("Our world currently has the following countries:-");
        countries.stream().map(country -> "\t" + country).forEach(LOGGER::info);
      }
    }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
  }

  public static void main(String[] args) {
    var app = new App();
    app.run();
  }
}
```

The program output is as follows:

```
12:06:02.612 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.DataFetcher -- world.txt is dirty! Re-fetching file content...
12:06:02.615 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- Our world currently has the following countries:-
12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- 	UNITED_KINGDOM
12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- 	MALAYSIA
12:06:02.616 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- 	UNITED_STATES
```

## [When to Use the Dirty Flag Pattern in Java](https://java-design-patterns.com/patterns/dirty-flag/#when-to-use-the-dirty-flag-pattern-in-java)

- When an operation is resource-intensive and only necessary after certain changes have occurred.
- In scenarios where checking for changes is significantly cheaper than performing the operation itself, enhancing cost-effectiveness.
- Within systems where objects maintain state that is expensive to update and the updates are infrequent, promoting performance efficiency.

## [Dirty Flag Pattern Java Tutorials](https://java-design-patterns.com/patterns/dirty-flag/#dirty-flag-pattern-java-tutorials)

- [89: Design Patterns: Dirty Flag (TakeUpCode)](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/)

## [Real-World Applications of Dirty Flag Pattern in Java](https://java-design-patterns.com/patterns/dirty-flag/#real-world-applications-of-dirty-flag-pattern-in-java)

- Graphic rendering engines to update only parts of the scene that have changed, utilizing the Dirty Flag pattern for efficient rendering.
- Web applications for partial page rendering or caching strategies.
- Database applications for tracking changes in datasets to minimize write operations, ensuring efficient database management.

## [Benefits and Trade-offs of Dirty Flag Pattern](https://java-design-patterns.com/patterns/dirty-flag/#benefits-and-trade-offs-of-dirty-flag-pattern)

Benefits:

- Reduces computational and resource overhead by avoiding unnecessary operations, leading to performance gains.
- Can significantly improve performance in systems where operations are costly and changes are infrequent, fostering system optimization.
- Simplifies the decision-making process about when to perform certain operations, aiding in effective resource allocation.

Trade-offs:

- Introduces complexity by adding state management responsibility to the system.
- Requires diligent management of the flag to ensure it accurately reflects the state changes, avoiding stale or incorrect data.
- Potentially increases the risk of bugs related to improper flag resetting, impacting system reliability.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/dirty-flag/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Can be used in conjunction to notify interested parties when the dirty flag is set or cleared.
- [Memento](https://java-design-patterns.com/patterns/memento/): Useful for storing the previous state of an object, which can work hand in hand with dirty flag logic to revert to clean states.
- [Command](https://java-design-patterns.com/patterns/command/): Commands can set the dirty flag when executed, indicating a change in state that requires attention.

## [References and Credits](https://java-design-patterns.com/patterns/dirty-flag/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/3PUzbgu)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)

---

## [behavioral/double-buffer] Double Buffer
> 官方文档: https://java-design-patterns.com/patterns/double-buffer/

BehavioralBufferingGame programmingOptimizationPerformanceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/double-buffer/#also-known-as)

- Buffer Switching
- Ping-Pong Buffer

## [Intent of Double Buffer Design Pattern](https://java-design-patterns.com/patterns/double-buffer/#intent-of-double-buffer-design-pattern)

The Double Buffer pattern in Java is designed to reduce rendering time and enhance performance in graphical or computational applications by utilizing two buffers. This pattern is crucial for smooth graphics rendering and is commonly used in game development and other real-time applications.

## [Detailed Explanation of Double Buffer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/double-buffer/#detailed-explanation-of-double-buffer-pattern-with-real-world-examples)

Real-world example

> Imagine a busy restaurant kitchen where chefs are constantly preparing dishes, and waitstaff are constantly picking up ready dishes to serve to customers. To avoid confusion and delays, the restaurant uses a double buffer system. They have two counters: one for chefs to place newly prepared dishes and another for waitstaff to pick up the dishes. While the chefs are filling one counter with prepared dishes, the waitstaff are simultaneously clearing the other counter by picking up dishes to serve. Once the waitstaff have cleared all dishes from their counter, they switch to the counter where the chefs have placed the newly prepared dishes, and the chefs start filling the now-empty counter. This system ensures a smooth and continuous workflow without either party waiting idly, maximizing efficiency and minimizing downtime.

In plain words

> It ensures a state that is being rendered correctly while that state is modifying incrementally. It is widely used in computer graphics.

Wikipedia says

> In computer science, multiple buffering is the use of more than one buffer to hold a block of data, so that a "reader" will see a complete (though perhaps old) version of the data, rather than a partially updated version of the data being created by a "writer". It is very commonly used for computer display images.

Sequence diagram

![Double Buffer sequence diagram](https://java-design-patterns.com/assets/img/double-buffer-sequence-diagram.73bb43df.png)

## [Programmatic Example of Double Buffer Pattern in Java](https://java-design-patterns.com/patterns/double-buffer/#programmatic-example-of-double-buffer-pattern-in-java)

A typical example, and one that every game engine must address, is rendering. When the game draws the world the users see, it does so one piece at a time - the mountains in the distance, the rolling hills, the trees, each in its turn. If the user watched the view draw incrementally like that, the illusion of a coherent world would be shattered. The scene must update smoothly and quickly, displaying a series of complete frames, each appearing instantly. Double buffering solves the problem.

`Buffer` interface that assures basic functionalities of a buffer.

```java
public interface Buffer {

    void clear(int x, int y);

    void draw(int x, int y);

    void clearAll();

    Pixel[] getPixels();
}
```

One of the implementations of `Buffer` interface.

```java
public class FrameBuffer implements Buffer {

    public static final int WIDTH = 10;
    public static final int HEIGHT = 8;

    private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT];

    public FrameBuffer() {
        clearAll();
    }

    @Override
    public void clear(int x, int y) {
        pixels[getIndex(x, y)] = Pixel.WHITE;
    }

    @Override
    public void draw(int x, int y) {
        pixels[getIndex(x, y)] = Pixel.BLACK;
    }

    @Override
    public void clearAll() {
        Arrays.fill(pixels, Pixel.WHITE);
    }

    @Override
    public Pixel[] getPixels() {
        return pixels;
    }

    private int getIndex(int x, int y) {
        return x + WIDTH * y;
    }
}
```

We support black and white pixels.

```java
public enum Pixel {

    WHITE,
    BLACK
}
```

`Scene` represents the game scene where current buffer has already been rendered.

```java
@Slf4j
public class Scene {

    private final Buffer[] frameBuffers;

    private int current;

    private int next;

    public Scene() {
        frameBuffers = new FrameBuffer[2];
        frameBuffers[0] = new FrameBuffer();
        frameBuffers[1] = new FrameBuffer();
        current = 0;
        next = 1;
    }

    public void draw(List<? extends Pair<Integer, Integer>> coordinateList) {
        LOGGER.info("Start drawing next frame");
        LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
        frameBuffers[next].clearAll();
        coordinateList.forEach(coordinate -> {
            var x = coordinate.getKey();
            var y = coordinate.getValue();
            frameBuffers[next].draw(x, y);
        });
        LOGGER.info("Swap current and next buffer");
        swap();
        LOGGER.info("Finish swapping");
        LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
    }

    public Buffer getBuffer() {
        LOGGER.info("Get current buffer: " + current);
        return frameBuffers[current];
    }

    private void swap() {
        current = current ^ next;
        next = current ^ next;
        current = current ^ next;
    }

}
```

Now, we can show the `App` class that drives the double buffering example.

```java
@Slf4j
public class App {

    public static void main(String[] args) {
        final var scene = new Scene();
        var drawPixels1 = List.of(
                new MutablePair<>(1, 1),
                new MutablePair<>(5, 6),
                new MutablePair<>(3, 2)
        );
        scene.draw(drawPixels1);
        var buffer1 = scene.getBuffer();
        printBlackPixelCoordinate(buffer1);

        var drawPixels2 = List.of(
                new MutablePair<>(3, 7),
                new MutablePair<>(6, 1)
        );
        scene.draw(drawPixels2);
        var buffer2 = scene.getBuffer();
        printBlackPixelCoordinate(buffer2);
    }

    private static void printBlackPixelCoordinate(Buffer buffer) {
        StringBuilder log = new StringBuilder("Black Pixels: ");
        var pixels = buffer.getPixels();
        for (var i = 0; i < pixels.length; ++i) {
            if (pixels[i] == Pixel.BLACK) {
                var y = i / FrameBuffer.WIDTH;
                var x = i % FrameBuffer.WIDTH;
                log.append(" (").append(x).append(", ").append(y).append(")");
            }
        }
        LOGGER.info(log.toString());
    }
}
```

The console output:

```text
12:33:02.525 [main] INFO com.iluwatar.doublebuffer.Scene -- Start drawing next frame
12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 0 Next buffer: 1
12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Swap current and next buffer
12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Finish swapping
12:33:02.529 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 1 Next buffer: 0
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Get current buffer: 1
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.App -- Black Pixels:  (1, 1) (3, 2) (5, 6)
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Start drawing next frame
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 1 Next buffer: 0
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Swap current and next buffer
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Finish swapping
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Current buffer: 0 Next buffer: 1
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.Scene -- Get current buffer: 0
12:33:02.530 [main] INFO com.iluwatar.doublebuffer.App -- Black Pixels:  (6, 1) (3, 7)
```

## [When to Use the Double Buffer Pattern in Java](https://java-design-patterns.com/patterns/double-buffer/#when-to-use-the-double-buffer-pattern-in-java)

- Real-time Applications: Ideal for video games, simulations, and GUI applications where frequent and smooth display updates are essential.
- High Computational Tasks: Suitable for applications that require intensive data preparation, enabling parallel processing and display.
- Minimizing Lag: Effective in reducing lag or stutter in data or graphics display.

## [Real-World Applications of Double Buffer Pattern in Java](https://java-design-patterns.com/patterns/double-buffer/#real-world-applications-of-double-buffer-pattern-in-java)

- Graphics Rendering Engines: Widely used in 2D and 3D rendering engines to ensure fluid animations and transitions.
- GUI Frameworks: Enhances the responsiveness and smoothness of user interfaces.
- Simulation and Modeling: Ensures real-time updates in simulations without interrupting ongoing processes.
- Video Playback Software: Provides seamless video playback by preloading the next frame during the display of the current one.

## [Benefits and Trade-offs of Double Buffer Pattern](https://java-design-patterns.com/patterns/double-buffer/#benefits-and-trade-offs-of-double-buffer-pattern)

Benefits:

- Smooth User Experience: Pre-renders frames to deliver smooth animations and transitions.
- Performance Optimization: Allows background rendering, optimizing overall application performance.
- Minimized Flickering: Reduces flickering and visual artifacts in graphical applications.

Trade-offs:

- Memory Overhead: Requires additional memory for the secondary buffer, potentially increasing memory usage.
- Implementation Complexity: Adds complexity to the architecture, necessitating careful buffer management.
- Latency: May introduce slight delays as data must be fully rendered in the back buffer before display.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/double-buffer/#related-java-design-patterns)

- Triple Buffering: An extension of the Double Buffer pattern, where three buffers are used to further optimize rendering and reduce latency.
- [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): The Double Buffer pattern can be seen as a variant of the Producer-Consumer pattern, with one buffer being "produced" while the other is "consumed".
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Often used in conjunction with the Strategy pattern to dynamically choose the buffering strategy based on runtime conditions.

## [References and Credits](https://java-design-patterns.com/patterns/double-buffer/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/4ayDNkS)
- [Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems](https://amzn.to/3xFfNxA)
- [Double Buffer (Game Programming Patterns)](https://gameprogrammingpatterns.com/double-buffer.html)

---

## [behavioral/double-dispatch] Double Dispatch
> 官方文档: https://java-design-patterns.com/patterns/double-dispatch/

BehavioralDecouplingDynamic typingPolymorphismRuntimeAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/double-dispatch/#also-known-as)

- Multi-methods

## [Intent of Double Dispatch Design Pattern](https://java-design-patterns.com/patterns/double-dispatch/#intent-of-double-dispatch-design-pattern)

The Double Dispatch pattern is used to achieve dynamic polymorphism based on the types of two objects involved in a method call. It allows method behavior to be different based on the combination of the runtime types of both the object on which the method is called and the object being passed as a parameter.

## [Detailed Explanation of Double Dispatch Pattern with Real-World Examples](https://java-design-patterns.com/patterns/double-dispatch/#detailed-explanation-of-double-dispatch-pattern-with-real-world-examples)

Real-world example

> In a logistics company, different types of delivery vehicles like trucks, drones, and bikes interact with various types of packages (fragile, oversized, standard). The Double Dispatch design pattern is used to determine the optimal delivery method: trucks might handle oversized items, drones for quick deliveries of light packages, and bikes for urban areas. Each vehicle-package combination results in a different handling and delivery strategy, dynamically determined at runtime based on the types of both the vehicle and the package.

In plain words

> The Double Dispatch design pattern in Java allows a program to select a different function to execute based on the types of two objects involved in a call, enhancing flexibility in handling interactions between them.

Wikipedia says

> In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called from a function call in the code depends on the dynamic type of a single object and therefore they are known as single dispatch calls, or simply virtual function calls.

Sequence diagram

![Double Dispatch sequence diagram](https://java-design-patterns.com/assets/img/double-dispatch-sequence-diagram.51743973.png)

## [Programmatic Example of Double Dispatch Pattern in Java](https://java-design-patterns.com/patterns/double-dispatch/#programmatic-example-of-double-dispatch-pattern-in-java)

The Double Dispatch pattern in Java is used to handle collisions between different types of game objects. Each game object is an instance of a class that extends the `GameObject` abstract class. The `GameObject` class has a `collision(GameObject)` method, which is overridden in each subclass to define the behavior when a collision occurs with another game object. Here is a simplified version of the `GameObject` class and its subclasses:

```java
public abstract class GameObject {
  // Other properties and methods...

  public abstract void collision(GameObject gameObject);
}

public class FlamingAsteroid extends GameObject {
  // Other properties and methods...

  @Override
  public void collision(GameObject gameObject) {
    gameObject.collisionWithFlamingAsteroid(this);
  }
}

public class SpaceStationMir extends GameObject {
  // Other properties and methods...

  @Override
  public void collision(GameObject gameObject) {
    gameObject.collisionWithSpaceStationMir(this);
  }
}
```

In the App class, the Double Dispatch pattern is used to check for collisions between all pairs of game objects:

```java
public static void main(String[] args) {
    // initialize game objects and print their status
    LOGGER.info("Init objects and print their status");
    var objects = List.of(
            new FlamingAsteroid(0, 0, 5, 5),
            new SpaceStationMir(1, 1, 2, 2),
            new Meteoroid(10, 10, 15, 15),
            new SpaceStationIss(12, 12, 14, 14)
    );
    objects.forEach(o -> LOGGER.info(o.toString()));

    // collision check
    LOGGER.info("Collision check");
    objects.forEach(o1 -> objects.forEach(o2 -> {
        if (o1 != o2 && o1.intersectsWith(o2)) {
            o1.collision(o2);
        }
    }));

    // output eventual object statuses
    LOGGER.info("Print object status after collision checks");
    objects.forEach(o -> LOGGER.info(o.toString()));
}
```

When a collision is detected between two objects, the `collision(GameObject)` method is called on the first object (o1) with the second object (o2) as the argument. This method call is dispatched at runtime to the appropriate `collision(GameObject)` method in the class of o1. Inside this method, another method call `gameObject.collisionWithX(this)` is made on o2 (where X is the type of o1), which is dispatched at runtime to the appropriate `collisionWithX(GameObject)` method in the class of o2. This is the "double dispatch" in Java - two method calls are dispatched at runtime based on the types of two objects.

Here is the program output:

```
15:47:23.763 [main] INFO com.iluwatar.doubledispatch.App -- Init objects and print their status
15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- FlamingAsteroid at [0,0,5,5] damaged=false onFire=true
15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationMir at [1,1,2,2] damaged=false onFire=false
15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- Meteoroid at [10,10,15,15] damaged=false onFire=false
15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationIss at [12,12,14,14] damaged=false onFire=false
15:47:23.772 [main] INFO com.iluwatar.doubledispatch.App -- Collision check
15:47:23.772 [main] INFO com.iluwatar.doubledispatch.SpaceStationMir -- FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire!
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.Meteoroid -- SpaceStationMir hits FlamingAsteroid.
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.SpaceStationMir --  {} is damaged! hits Meteoroid.
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.Meteoroid -- SpaceStationIss hits Meteoroid.
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- Print object status after collision checks
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- FlamingAsteroid at [0,0,5,5] damaged=false onFire=true
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationMir at [1,1,2,2] damaged=true onFire=true
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- Meteoroid at [10,10,15,15] damaged=false onFire=false
15:47:23.773 [main] INFO com.iluwatar.doubledispatch.App -- SpaceStationIss at [12,12,14,14] damaged=true onFire=false
```

## [When to Use the Double Dispatch Pattern in Java](https://java-design-patterns.com/patterns/double-dispatch/#when-to-use-the-double-dispatch-pattern-in-java)

- When the behavior of a method needs to vary not just based on the object it is called on, but also based on the type of the argument.
- In scenarios where if-else or switch-case type checks against the type of objects are cumbersome and not scalable.
- When implementing operations in domain classes without contaminating their code with complex decision-making logic about other domain classes.

## [Real-World Applications of Double Dispatch Pattern in Java](https://java-design-patterns.com/patterns/double-dispatch/#real-world-applications-of-double-dispatch-pattern-in-java)

- Graphical user interfaces where different actions are taken based on different types of mouse events interacting with different types of elements.
- Simulation systems where interactions between different types of objects need to trigger distinct behaviors.

## [Benefits and Trade-offs of Double Dispatch Pattern](https://java-design-patterns.com/patterns/double-dispatch/#benefits-and-trade-offs-of-double-dispatch-pattern)

Benefits:

- Increases the flexibility of code by handling interaction between objects in a manner that is easy to understand and maintain.
- Helps in adhering to the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle) by allowing new classes to be introduced without modifying existing classes.

Trade-offs:

- Can lead to more complex code structures, especially in languages like Java that do not support this pattern natively.
- May require additional effort in maintaining and extending as new classes are added.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/double-dispatch/#related-java-design-patterns)

- [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in intent where it's used to choose an algorithm at runtime, though Strategy focuses on single object context rather than interactions between multiple objects.
- [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together with Double Dispatch to encapsulate operations performed on a set of element objects.

## [References and Credits](https://java-design-patterns.com/patterns/double-dispatch/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4awj7cV)
- [Java Design Pattern Essentials](https://amzn.to/3Jg8ZZV)
- [Refactoring to Patterns](https://amzn.to/3vRBJ8k)

---

## [behavioral/execute-around] Execute Around
> 官方文档: https://java-design-patterns.com/patterns/execute-around/

BehavioralClosureCode simplificationEncapsulationFunctional decompositionResource managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/execute-around/#also-known-as)

- Around Method Pattern
- Resource Block Management

## [Intent of Execute Around Design Pattern](https://java-design-patterns.com/patterns/execute-around/#intent-of-execute-around-design-pattern)

Real-world business applications often require executing necessary operations before and after the business method invocation. The Execute Around Pattern in Java provides a way to encapsulate these operations, enhancing code readability and reusability.

## [Detailed Explanation of Execute Around Pattern with Real-World Examples](https://java-design-patterns.com/patterns/execute-around/#detailed-explanation-of-execute-around-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Execute Around pattern can be found in the use of rental cars. When you rent a car, the rental company handles all the setup (cleaning the car, filling it with gas, ensuring it's in good condition) and cleanup (checking the car back in, inspecting it for damage, refueling it if necessary) processes for you. As a customer, you simply use the car for your intended purpose without worrying about the setup and cleanup. This pattern of abstracting away the repetitive tasks around the main operation is similar to the Execute Around pattern in software, where the setup and cleanup of resources are handled by a reusable method, allowing the main logic to be executed seamlessly.

In plain words

> Execute Around idiom handles boilerplate code before and after business method.

[Stack Overflow](https://stackoverflow.com/questions/341971/what-is-the-execute-around-idiom) says

> Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource".

Flowchart

![Execute Around flowchart](https://java-design-patterns.com/assets/img/execute-around-flowchart.097b52ac.png)

## [Programmatic Example of Execute Around Pattern in Java](https://java-design-patterns.com/patterns/execute-around/#programmatic-example-of-execute-around-pattern-in-java)

The Execute Around Pattern is a design pattern that is widely used in Java programming to manage resource allocation and deallocation. It ensures that important setup and cleanup operations are performed reliably around a core business operation. This pattern is particularly useful for resource management, such as handling files, databases, or network connections in Java applications.

A class needs to be provided for writing text strings to files. To make it easy for the user, the service class opens and closes the file automatically. The user only has to specify what is written into which file.

`SimpleFileWriter` class implements the Execute Around idiom. It takes `FileWriterAction` as a constructor argument allowing the user to specify what gets written into the file.

```java

@FunctionalInterface
public interface FileWriterAction {
    void writeFile(FileWriter writer) throws IOException;
}

@Slf4j
public class SimpleFileWriter {
    public SimpleFileWriter(String filename, FileWriterAction action) throws IOException {
        LOGGER.info("Opening the file");
        try (var writer = new FileWriter(filename)) {
            LOGGER.info("Executing the action");
            action.writeFile(writer);
            LOGGER.info("Closing the file");
        }
    }
}
```

The following code demonstrates how `SimpleFileWriter` is used. `Scanner` is used to print the file contents after the writing finishes.

```java
  public static void main(String[] args) throws IOException {

    // create the file writer and execute the custom action
    FileWriterAction writeHello = writer -> writer.write("Gandalf was here");
    new SimpleFileWriter("testfile.txt", writeHello);

    // print the file contents
    try (var scanner = new Scanner(new File("testfile.txt"))) {
        while (scanner.hasNextLine()) {
            LOGGER.info(scanner.nextLine());
        }
    }
}
```

Here's the console output.

```
21:18:07.185 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Opening the file
21:18:07.188 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Executing the action
21:18:07.189 [main] INFO com.iluwatar.execute.around.SimpleFileWriter - Closing the file
21:18:07.199 [main] INFO com.iluwatar.execute.around.App - Gandalf was here
```

## [When to Use the Execute Around Pattern in Java](https://java-design-patterns.com/patterns/execute-around/#when-to-use-the-execute-around-pattern-in-java)

When to use the Execute Around Pattern in Java:

- Useful in scenarios requiring repetitive setup and cleanup activities, particularly in resource management (e.g., files, network connections, database sessions).
- Ideal for ensuring proper resource handling and cleanup in the face of exceptions, ensuring resources do not leak.
- Suitable in any Java application where the same preparation and finalization steps are executed around varying core functionalities.

## [Real-World Applications of Execute Around Pattern in Java](https://java-design-patterns.com/patterns/execute-around/#real-world-applications-of-execute-around-pattern-in-java)

In real-world Java applications, the Execute Around Pattern is applied in these scenarios:

- Java's try-with-resources statement, which ensures that resources are closed after execution regardless of whether an exception was thrown.
- Frameworks like Spring for managing database transactions, where predefined cleanup or rollback operations are performed depending on the execution outcome.

## [Benefits and Trade-offs of Execute Around Pattern](https://java-design-patterns.com/patterns/execute-around/#benefits-and-trade-offs-of-execute-around-pattern)

Implementing the Execute Around Pattern in Java offers several benefits and trade-offs.

Benefits:

- Reduces boilerplate code by abstracting routine setup and cleanup tasks.
- Increases code clarity and maintainability by separating business logic from resource management.
- Ensures robustness by automatically handling resource cleanup, even in error situations.

Trade-offs:

- Introduces additional abstraction layers, which might increase complexity and obscure control flow for some developers.
- May require more sophisticated understanding of closures and functional interfaces in Java.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/execute-around/#related-java-design-patterns)

- [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in concept but differs in that it uses inheritance and abstract classes, while Execute Around typically uses interfaces and lambdas.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Shares the concept of adding functionality around a core component; can be extended to wrap additional behaviors dynamically.

## [References and Credits](https://java-design-patterns.com/patterns/execute-around/#references-and-credits)

- [Effective Java](https://amzn.to/4aDdWbs)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3vUGApm)
- [Functional Programming in Java](https://amzn.to/3JUIc5Q)

---

## [behavioral/feature-toggle] Feature Toggle
> 官方文档: https://java-design-patterns.com/patterns/feature-toggle/

BehavioralDecouplingExtensibilityFeature managementScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/feature-toggle/#also-known-as)

- Feature Flag
- Feature Switch

## [Intent of Feature Toggle Design Pattern](https://java-design-patterns.com/patterns/feature-toggle/#intent-of-feature-toggle-design-pattern)

To enable or disable features in a software application dynamically without deploying new code.

## [Detailed Explanation of Feature Toggle Pattern with Real-World Examples](https://java-design-patterns.com/patterns/feature-toggle/#detailed-explanation-of-feature-toggle-pattern-with-real-world-examples)

Real-world Example

> A real-world example of the Feature Toggle pattern is Netflix's rollout of new user interface features. When Netflix decides to introduce a new feature, such as a redesigned homepage layout or a new recommendation algorithm, they use feature toggles to control the release. Initially, the new feature is toggled off for most users, allowing only a small group of users (e.g., beta testers) to experience and provide feedback on the feature. Based on the feedback and performance metrics, Netflix can quickly toggle the feature on for a broader audience or turn it off if issues are detected, all without redeploying the application. This approach allows Netflix to continuously innovate and improve their platform while minimizing risk and ensuring a stable user experience.

In plain words

> The Feature Toggle design pattern in Java allows developers to introduce new features gradually instead of deploying them all at once, facilitating better dynamic feature management.

Wikipedia says

> A feature toggle in software development provides an alternative to maintaining multiple feature branches in source code. A condition within the code enables or disables a feature during runtime. In agile settings the toggle is used in production, to switch on the feature on demand, for some or all the users.

Flowchart

![Feature Toggle flowchart](https://java-design-patterns.com/assets/img/feature-toggle-flowchart.02de1e45.png)

## [Programmatic Example of Feature Toggle Pattern in Java](https://java-design-patterns.com/patterns/feature-toggle/#programmatic-example-of-feature-toggle-pattern-in-java)

This Java code example demonstrates how to display a feature when it is enabled by the developer and the user is a Premium member of the application. This approach is useful for managing subscription-locked features.

The Feature Toggle pattern enables the seamless activation or deactivation of entire code executions. This allows features to be managed dynamically based on user information or configuration properties.

Key Components:

1. `PropertiesFeatureToggleVersion`: This class uses properties to control the feature toggle. The properties determine whether the enhanced version of the welcome message, which is personalized, is turned on or off.

2. `TieredFeatureToggleVersion`: This class uses user information to control the feature toggle. The feature of the personalized welcome message is dependent on the user group the user is in.

3. `User`: This class represents the user of the application.

4. `UserGroup`: This class represents the group the user belongs to.


```java
public static void main(String[] args) {

    // Demonstrates the PropertiesFeatureToggleVersion running with properties
    // that set the feature toggle to enabled.

    final var properties = new Properties();
    properties.put("enhancedWelcome", true);
    var service = new PropertiesFeatureToggleVersion(properties);
    final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
    LOGGER.info(welcomeMessage);

    // Demonstrates the PropertiesFeatureToggleVersion running with properties
    // that set the feature toggle to disabled. Note the difference in the printed welcome message
    // where the username is not included.

    final var turnedOff = new Properties();
    turnedOff.put("enhancedWelcome", false);
    var turnedOffService = new PropertiesFeatureToggleVersion(turnedOff);
    final var welcomeMessageturnedOff =
            turnedOffService.getWelcomeMessage(new User("Jamie No Code"));
    LOGGER.info(welcomeMessageturnedOff);

    // Demonstrates the TieredFeatureToggleVersion setup with
    // two users: one on the free tier and the other on the paid tier. When the
    // Service#getWelcomeMessage(User) method is called with the paid user, the welcome
    // message includes their username. In contrast, calling the same service with the free tier user results
    // in a more generic welcome message without the username.

    var service2 = new TieredFeatureToggleVersion();

    final var paidUser = new User("Jamie Coder");
    final var freeUser = new User("Alan Defect");

    UserGroup.addUserToPaidGroup(paidUser);
    UserGroup.addUserToFreeGroup(freeUser);

    final var welcomeMessagePaidUser = service2.getWelcomeMessage(paidUser);
    final var welcomeMessageFreeUser = service2.getWelcomeMessage(freeUser);
    LOGGER.info(welcomeMessageFreeUser);
    LOGGER.info(welcomeMessagePaidUser);
}
```

Running the example produces the following output.

```
07:31:50.802 [main] INFO com.iluwatar.featuretoggle.App -- Welcome Jamie No Code. You're using the enhanced welcome message.
07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- Welcome to the application.
07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- I suppose you can use this software.
07:31:50.804 [main] INFO com.iluwatar.featuretoggle.App -- You're amazing Jamie Coder. Thanks for paying for this awesome software.
```

## [When to Use the Feature Toggle Pattern in Java](https://java-design-patterns.com/patterns/feature-toggle/#when-to-use-the-feature-toggle-pattern-in-java)

Use the Feature Toggle Pattern in Java when:

- Dynamic feature management to different users and groups.
- Rolling out a new feature incrementally.
- Switching between development and production environments.
- Quickly disable problematic features
- External management of feature deployment
- Ability to maintain multiple version releases of a feature
- 'Hidden' deployment, releasing a feature in code for designated testing but not publicly making it available

## [Real-World Applications of Feature Toggle Pattern in Java](https://java-design-patterns.com/patterns/feature-toggle/#real-world-applications-of-feature-toggle-pattern-in-java)

- Many web development platforms utilize the Feature Toggle design pattern to gradually roll out new features to users, ensuring stability and effective dynamic feature management.
- Enterprise applications use feature toggles to enable or disable features during runtime to cater to different market needs.

## [Benefits and Trade-offs of Feature Toggle Pattern](https://java-design-patterns.com/patterns/feature-toggle/#benefits-and-trade-offs-of-feature-toggle-pattern)

Benefits:

- Facilitates A/B testing and canary releases.
- Allows for quicker rollback and minimal risk deployments.
- Enables conditional feature execution without redeploying the application.

Trade-offs:

- Code complexity is increased.
- Testing of multiple states is harder and more time-consuming.
- Potential for technical debt if toggles remain in the code longer than necessary.
- Risk of toggle misconfiguration leading to unexpected behavior.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/feature-toggle/#related-java-design-patterns)

- [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns allow changing the behavior of software at runtime. The Feature Toggle changes features dynamically, while the Strategy allows switching algorithms or strategies.
- [Observer](https://java-design-patterns.com/patterns/observer/): Useful for implementing feature toggles by notifying components of feature state changes, which allows dynamic feature modification without restarts.

## [References and Credits](https://java-design-patterns.com/patterns/feature-toggle/#references-and-credits)

- [Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation](https://amzn.to/4488ESM)
- [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3UoeJY4)
- [Feature Toggle (Martin Fowler)](http://martinfowler.com/bliki/FeatureToggle.html)

---

## [behavioral/filterer] Filterer
> 官方文档: https://java-design-patterns.com/patterns/filterer/

BehavioralData processingData transformationDecouplingFunctional decompositionObject compositionPerformanceRuntimeAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/filterer/#also-known-as)

- Filters
- Pipes and Filters

## [Intent of Filterer Design Pattern](https://java-design-patterns.com/patterns/filterer/#intent-of-filterer-design-pattern)

The Filterer design pattern in Java is essential for creating dynamic and scalable filtering solutions. This pattern allows the application of a series of filters to data objects, enhancing data processing flexibility and scalability.

## [Detailed Explanation of Filterer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/filterer/#detailed-explanation-of-filterer-pattern-with-real-world-examples)

Real-world example

> Imagine a library system employing the Filterer pattern to dynamically combine filter criteria such as genre, author, and availability. This Java pattern makes the system more maintainable and scalable. Instead of writing separate methods for each possible combination of criteria, the library system employs the Filterer design pattern. Each filter criterion is encapsulated as an object, and these filter objects can be combined dynamically at runtime to create complex filtering logic. For example, a user can search for books that are both available and published after 2010 by combining the availability filter and the publication year filter. This approach makes the system more flexible and easier to maintain, as new filtering criteria can be added without modifying existing code.

In plain words

> Filterer pattern is a design pattern that helps container-like objects return filtered versions of themselves.

Flowchart

![Filterer flowchart](https://java-design-patterns.com/assets/img/filterer-flowchart.f47fc80d.png)

## [Programmatic Example of Filterer Pattern in Java](https://java-design-patterns.com/patterns/filterer/#programmatic-example-of-filterer-pattern-in-java)

To illustrate, we use the Filterer design pattern for a malware detection system in Java. This system can filter threats based on various criteria, showcasing the pattern’s flexibility and dynamic nature. In the design we have to take into consideration that new Threat types can be added later. Additionally, there is a requirement that the threat detection system can filter the detected threats based on different criteria (the target system acts as container-like object for threats).

To model the threat detection system, we introduce `Threat` and `ThreatAwareSystem` interfaces.

```java
public interface Threat {
    String name();
    int id();
    ThreatType type();
}
```

```java
public interface ThreatAwareSystem {
    String systemId();
    List<? extends Threat> threats();
    Filterer<? extends ThreatAwareSystem, ? extends Threat> filtered();
}
```

Notice the `filtered` method that returns instance of `Filterer` interface which is defined as:

```java
@FunctionalInterface
public interface Filterer<G, E> {
    G by(Predicate<? super E> predicate);
}
```

A simple implementation of `ThreatAwareSystem`:

```java
public class SimpleThreatAwareSystem implements ThreatAwareSystem {

    private final String systemId;
    private final ImmutableList<Threat> issues;

    public SimpleThreatAwareSystem(final String systemId, final List<Threat> issues) {
        this.systemId = systemId;
        this.issues = ImmutableList.copyOf(issues);
    }

    @Override
    public String systemId() {
        return systemId;
    }

    @Override
    public List<? extends Threat> threats() {
        return new ArrayList<>(issues);
    }

    @Override
    public Filterer<? extends ThreatAwareSystem, ? extends Threat> filtered() {
        return this::filteredGroup;
    }

    private ThreatAwareSystem filteredGroup(Predicate<? super Threat> predicate) {
        return new SimpleThreatAwareSystem(this.systemId, filteredItems(predicate));
    }

    private List<Threat> filteredItems(Predicate<? super Threat> predicate) {
        return this.issues.stream()
                .filter(predicate)
                .collect(Collectors.toList());
    }
}
```

Now if we introduce a new subtype of `Threat` interface that adds probability with which given threat can appear:

```java
public interface ProbableThreat extends Threat {
    double probability();
}
```

We can also introduce a new interface that represents a system that is aware of threats with their probabilities:

```java
public interface ProbabilisticThreatAwareSystem extends ThreatAwareSystem {
    @Override
    List<? extends ProbableThreat> threats();
    @Override
    Filterer<? extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered();
}
```

We will be able to filter `ProbabilisticThreatAwareSystem` by `ProbableThreat` properties:

```java
public class SimpleProbabilisticThreatAwareSystem implements ProbabilisticThreatAwareSystem {

    private final String systemId;
    private final ImmutableList<ProbableThreat> threats;

    public SimpleProbabilisticThreatAwareSystem(final String systemId, final List<ProbableThreat> threats) {
        this.systemId = systemId;
        this.threats = ImmutableList.copyOf(threats);
    }

    @Override
    public String systemId() {
        return systemId;
    }

    @Override
    public List<? extends ProbableThreat> threats() {
        return threats;
    }

    @Override
    public Filterer<? extends ProbabilisticThreatAwareSystem, ? extends ProbableThreat> filtered() {
        return this::filteredGroup;
    }

    private ProbabilisticThreatAwareSystem filteredGroup(final Predicate<? super ProbableThreat> predicate) {
        return new SimpleProbabilisticThreatAwareSystem(this.systemId, filteredItems(predicate));
    }

    private List<ProbableThreat> filteredItems(final Predicate<? super ProbableThreat> predicate) {
        return this.threats.stream()
                .filter(predicate)
                .collect(Collectors.toList());
    }
}
```

Now let's see the full example in action showing how the filterer pattern works in practice.

```java
@Slf4j
public class App {

  public static void main(String[] args) {
    filteringSimpleThreats();
    filteringSimpleProbableThreats();
  }

  private static void filteringSimpleProbableThreats() {
    LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###");

    var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99);
    var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8);

    List<ProbableThreat> probableThreats = List.of(trojanArcBomb, rootkit);

    var probabilisticThreatAwareSystem =
        new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats);

    LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : "
        + probabilisticThreatAwareSystem);

    //Filtering using filterer
    var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered()
        .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0);

    LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem);
  }

  private static void filteringSimpleThreats() {
    LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###");

    var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit");
    var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan");
    List<Threat> threats = List.of(rootkit, trojan);

    var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats);

    LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem);

    //Filtering using Filterer
    var rootkitThreatAwareSystem = threatAwareSystem.filtered()
        .by(threat -> threat.type() == ThreatType.ROOTKIT);

    LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem);
  }
}
```

Running the example produces the following console output.

```
08:33:23.568 [main] INFO com.iluwatar.filterer.App -- ### Filtering ThreatAwareSystem by ThreatType ###
08:33:23.574 [main] INFO com.iluwatar.filterer.App -- Filtering ThreatAwareSystem. Initial : SimpleThreatAwareSystem(systemId=Sys-1, issues=[SimpleThreat(threatType=ROOTKIT, id=1, name=Simple-Rootkit), SimpleThreat(threatType=TROJAN, id=2, name=Simple-Trojan)])
08:33:23.576 [main] INFO com.iluwatar.filterer.App -- Filtered by threatType = ROOTKIT : SimpleThreatAwareSystem(systemId=Sys-1, issues=[SimpleThreat(threatType=ROOTKIT, id=1, name=Simple-Rootkit)])
08:33:23.576 [main] INFO com.iluwatar.filterer.App -- ### Filtering ProbabilisticThreatAwareSystem by probability ###
08:33:23.581 [main] INFO com.iluwatar.filterer.App -- Filtering ProbabilisticThreatAwareSystem. Initial : SimpleProbabilisticThreatAwareSystem(systemId=Sys-1, threats=[SimpleProbableThreat{probability=0.99} SimpleThreat(threatType=TROJAN, id=1, name=Trojan-ArcBomb), SimpleProbableThreat{probability=0.8} SimpleThreat(threatType=ROOTKIT, id=2, name=Rootkit-Kernel)])
08:33:23.581 [main] INFO com.iluwatar.filterer.App -- Filtered by probability = 0.99 : SimpleProbabilisticThreatAwareSystem(systemId=Sys-1, threats=[SimpleProbableThreat{probability=0.99} SimpleThreat(threatType=TROJAN, id=1, name=Trojan-ArcBomb)])
```

## [When to Use the Filterer Pattern in Java](https://java-design-patterns.com/patterns/filterer/#when-to-use-the-filterer-pattern-in-java)

- Use the Filterer pattern when dynamic and flexible filtering of a collection of objects is needed.
- This Java design pattern is ideal for applications where filtering logic frequently changes or requires combination in various ways.
- Ideal for scenarios requiring separation of filtering logic from the core business logic.

## [Filterer Pattern Java Tutorials](https://java-design-patterns.com/patterns/filterer/#filterer-pattern-java-tutorials)

- [Filterer Pattern (Tomasz Linkowski)](https://blog.tlinkowski.pl/2018/filterer-pattern/)
- [Filterer Pattern in 10 Steps (Java Code Geeks)](https://www.javacodegeeks.com/2019/02/filterer-pattern-10-steps.html)

## [Real-World Applications of Filterer Pattern in Java](https://java-design-patterns.com/patterns/filterer/#real-world-applications-of-filterer-pattern-in-java)

- Stream processing libraries in Java, such as Apache Kafka Streams, utilize this pattern to build complex data processing pipelines.
- Image processing software often uses filters to apply effects or transformations to images sequentially.

## [Benefits and Trade-offs of Filterer Pattern](https://java-design-patterns.com/patterns/filterer/#benefits-and-trade-offs-of-filterer-pattern)

Benefits:

- Increases flexibility by allowing different filters to be added or reorganized without affecting other parts of the system.
- Enhances testability, as filters can be tested independently.
- Promotes loose coupling between the stages of data processing.

Trade-offs:

- Potential performance overhead from continuous data passing between filters.
- Complexity can increase with the number of filters, potentially affecting maintainability.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/filterer/#related-java-design-patterns)

- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Filters can be seen as a specialized form of the Chain of Responsibility, where each filter decides if and how to process the input data and whether to pass it along the chain.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Decorator in that both modify behavior dynamically; however, filters focus more on data transformation than on adding responsibilities.

## [References and Credits](https://java-design-patterns.com/patterns/filterer/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3W8sn2W)
- [Kafka: The Definitive Guide: Real-Time Data and Stream Processing at Scale](https://amzn.to/49N3nRU)
- [Java Performance: The Definitive Guide](https://amzn.to/3vRW3qj)

---

## [behavioral/fluent-interface] Fluent Interface
> 官方文档: https://java-design-patterns.com/patterns/fluent-interface/

BehavioralAPI designCode simplificationDecouplingObject compositionReactiveAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/fluent-interface/#also-known-as)

- Fluent API
- Method Chaining

## [Intent of Fluent Interface Design Pattern](https://java-design-patterns.com/patterns/fluent-interface/#intent-of-fluent-interface-design-pattern)

The primary goal of the Fluent Interface pattern is to provide an easily readable and flowing API by chaining method calls, often referred to as method chaining. This approach is ideal for building complex objects step-by-step and improving the overall developer experience.

## [Detailed Explanation of Fluent Interface Pattern with Real-World Examples](https://java-design-patterns.com/patterns/fluent-interface/#detailed-explanation-of-fluent-interface-pattern-with-real-world-examples)

Real-world example

> Imagine you are at a coffee shop customizing your order step-by-step. This approach is similar to how the Fluent Interface design pattern works in Java, allowing you to chain method calls to build and configure objects sequentially. Instead of telling the barista everything at once, you specify each customization step-by-step in a way that flows naturally. For instance, you might say, "I'd like a large coffee, add two shots of espresso, no sugar, and top it with almond milk." This approach is similar to the Fluent Interface design pattern, where you chain together method calls to configure an object in a readable and intuitive manner. Just as you specify each part of your coffee order sequentially, a Fluent Interface allows you to chain method calls to build and configure objects step-by-step in code.

In plain words

> Fluent Interface pattern provides easily readable flowing interface to code.

Wikipedia says

> In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL).

Sequence diagram

![Fluent Interface sequence diagram](https://java-design-patterns.com/assets/img/fluent-interface-sequence-diagram.57e98bc4.png)

## [Programmatic Example of Fluent Interface Pattern in Java](https://java-design-patterns.com/patterns/fluent-interface/#programmatic-example-of-fluent-interface-pattern-in-java)

We need to select numbers based on different criteria from the list. It's a great chance to utilize fluent interface pattern to provide readable easy-to-use developer experience.

In this example two implementations of a `FluentIterable` interface are given.

```java
public interface FluentIterable<E> extends Iterable<E> {

  FluentIterable<E> filter(Predicate<? super E> predicate);

  Optional<E> first();

  FluentIterable<E> first(int count);

  Optional<E> last();

  FluentIterable<E> last(int count);

  <T> FluentIterable<T> map(Function<? super E, T> function);

  List<E> asList();

  static <E> List<E> copyToList(Iterable<E> iterable) {
    var copy = new ArrayList<E>();
    iterable.forEach(copy::add);
    return copy;
  }
}
```

The `SimpleFluentIterable` evaluates eagerly and would be too costly for real world applications.

```java
public class SimpleFluentIterable<E> implements FluentIterable<E> {
  // ...
}
```

The `LazyFluentIterable` is evaluated on termination.

```java
public class LazyFluentIterable<E> implements FluentIterable<E> {
  // ...
}
```

Their usage is demonstrated with a simple number list that is filtered, transformed and collected. The result is printed afterward.

```java
public static void main(String[] args) {

    var integerList = List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68);

    prettyPrint("The initial list contains: ", integerList);

    var firstFiveNegatives = SimpleFluentIterable
            .fromCopyOf(integerList)
            .filter(negatives())
            .first(3)
            .asList();
    prettyPrint("The first three negative values are: ", firstFiveNegatives);

    var lastTwoPositives = SimpleFluentIterable
            .fromCopyOf(integerList)
            .filter(positives())
            .last(2)
            .asList();
    prettyPrint("The last two positive values are: ", lastTwoPositives);

    SimpleFluentIterable
            .fromCopyOf(integerList)
            .filter(number -> number % 2 == 0)
            .first()
            .ifPresent(evenNumber -> LOGGER.info("The first even number is: {}", evenNumber));

    var transformedList = SimpleFluentIterable
            .fromCopyOf(integerList)
            .filter(negatives())
            .map(transformToString())
            .asList();
    prettyPrint("A string-mapped list of negative numbers contains: ", transformedList);

    var lastTwoOfFirstFourStringMapped = LazyFluentIterable
            .from(integerList)
            .filter(positives())
            .first(4)
            .last(2)
            .map(number -> "String[" + number + "]")
            .asList();
    prettyPrint("The lazy list contains the last two of the first four positive numbers "
            + "mapped to Strings: ", lastTwoOfFirstFourStringMapped);

    LazyFluentIterable
            .from(integerList)
            .filter(negatives())
            .first(2)
            .last()
            .ifPresent(number -> LOGGER.info("Last amongst first two negatives: {}", number));
}
```

Program output:

```
08:50:08.260 [main] INFO com.iluwatar.fluentinterface.app.App -- The initial list contains: 1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68.
08:50:08.265 [main] INFO com.iluwatar.fluentinterface.app.App -- The first three negative values are: -61, -22, -87.
08:50:08.265 [main] INFO com.iluwatar.fluentinterface.app.App -- The last two positive values are: 23, 2.
08:50:08.266 [main] INFO com.iluwatar.fluentinterface.app.App -- The first even number is: 14
08:50:08.267 [main] INFO com.iluwatar.fluentinterface.app.App -- A string-mapped list of negative numbers contains: String[-61], String[-22], String[-87], String[-82], String[-98], String[-68].
08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- The lazy list contains the last two of the first four positive numbers mapped to Strings: String[18], String[6].
08:50:08.270 [main] INFO com.iluwatar.fluentinterface.app.App -- Last amongst first two negatives: -22
```

## [When to Use the Fluent Interface Pattern in Java](https://java-design-patterns.com/patterns/fluent-interface/#when-to-use-the-fluent-interface-pattern-in-java)

Use the Fluent Interface Pattern in Java when

- Designing APIs that are heavily used and where readability of client code is of high importance.
- Building complex objects step-by-step, and there is a need to make the code more intuitive and less error-prone.
- Enhancing code clarity and reducing the boilerplate code, especially in configurations and object-building scenarios.

## [Fluent Interface Pattern Java Tutorials](https://java-design-patterns.com/patterns/fluent-interface/#fluent-interface-pattern-java-tutorials)

- [An Approach to Internal Domain-Specific Languages in Java (InfoQ)](http://www.infoq.com/articles/internal-dsls-java)

## [Real-World Applications of Fluent Interface Pattern in Java](https://java-design-patterns.com/patterns/fluent-interface/#real-world-applications-of-fluent-interface-pattern-in-java)

- [Java 8 Stream API](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html)
- [Google Guava FluentIterable](https://github.com/google/guava/wiki/FunctionalExplained)
- [JOOQ](http://www.jooq.org/doc/3.0/manual/getting-started/use-cases/jooq-as-a-standalone-sql-builder/)
- [Mockito](http://mockito.org/)
- [Java Hamcrest](http://code.google.com/p/hamcrest/wiki/Tutorial)
- Builders in libraries like Apache Camel for integration workflows.

## [Benefits and Trade-offs of Fluent Interface Pattern](https://java-design-patterns.com/patterns/fluent-interface/#benefits-and-trade-offs-of-fluent-interface-pattern)

Benefits:

- Adopting the Fluent Interface pattern in your Java projects can significantly enhance code readability and maintainability.
- Encourages building immutable objects since methods typically return new instances.
- Reduces the need for variables as the context is maintained in the chain.

Trade-offs:

- Can lead to less intuitive code for those unfamiliar with the pattern.
- Debugging can be challenging due to the chaining of method calls.
- Overuse can lead to complex and hard-to-maintain code structures.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/fluent-interface/#related-java-design-patterns)

- [Builder](https://java-design-patterns.com/patterns/builder/): Often implemented using a Fluent Interface to construct objects step-by-step. The Builder Pattern focuses on constructing complex objects, while Fluent Interface emphasizes the method chaining mechanism.
- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Fluent Interfaces can be seen as a specific utilization of the Chain of Responsibility, where each method in the chain handles a part of the task and then delegates to the next method.

## [References and Credits](https://java-design-patterns.com/patterns/fluent-interface/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3UrXkh2)
- [Domain Specific Languages](https://amzn.to/3R1UYDA)
- [Effective Java](https://amzn.to/4d4azvL)
- [Java Design Pattern Essentials](https://amzn.to/44bs6hG)
- [Fluent Interface (Martin Fowler)](http://www.martinfowler.com/bliki/FluentInterface.html)

---

## [behavioral/game-loop] Game Loop
> 官方文档: https://java-design-patterns.com/patterns/game-loop/

BehavioralConcurrencyEvent-drivenGame programmingPerformanceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/game-loop/#also-known-as)

- Game Cycle
- Main Game Loop

## [Intent of Game Loop Design Pattern](https://java-design-patterns.com/patterns/game-loop/#intent-of-game-loop-design-pattern)

The Game Loop design pattern is essential for creating smooth and interactive gaming experiences by facilitating continuous game execution. Each loop cycle processes input, updates the game state, and renders the game state to the screen, ensuring consistent performance across all hardware setups.

## [Detailed Explanation of Game Loop Pattern with Real-World Examples](https://java-design-patterns.com/patterns/game-loop/#detailed-explanation-of-game-loop-pattern-with-real-world-examples)

Real-world example

> A practical analogy of the Game Loop can be seen in an amusement park ride, like a roller coaster. Similar to how the ride operates in a loop, updating its state and ensuring smooth operation, the Game Loop continuously processes inputs and updates the game state for a seamless gaming experience. The roller coaster operates in a continuous loop, where the state of the ride (the position and speed of the coaster) is continuously updated while the ride is running. The control system of the roller coaster ensures that the cars move smoothly along the track, adjusting speeds, and handling the ride's safety systems in real-time. Just like the game loop, this control system repeatedly processes inputs (such as the current speed and position), updates the state, and triggers outputs (like adjusting the brakes or accelerating the cars) to maintain the desired operation throughout the duration of the ride.

In plain words

> Game Loop pattern ensures that game time progresses in equal speed in all different hardware setups.

Wikipedia says

> The central component of any game, from a programming standpoint, is the game loop. The game loop allows the game to run smoothly regardless of a user's input, or lack thereof.

Flowchart

![Game Loop flowchart](https://java-design-patterns.com/assets/img/game-loop-flowchart.890b0ea5.png)

## [Programmatic Example of Game Loop Pattern in Java](https://java-design-patterns.com/patterns/game-loop/#programmatic-example-of-game-loop-pattern-in-java)

In our Java example, we illustrate a simple game loop controlling a bullet's movement, updating its position, ensuring smooth rendering, and responding to user inputs. The Game Loop is the main process driving all game rendering threads, present in all modern games. It handles input processing, internal status updates, rendering, AI, and other processes. Starting with a simple `Bullet` class, we demonstrate the movement of bullets in our game, focusing on their 1-dimensional position for demonstration purposes.

```java
public class Bullet {

  private float position;

  public Bullet() {
    position = 0.0f;
  }

  public float getPosition() {
    return position;
  }

  public void setPosition(float position) {
    this.position = position;
  }
}
```

`GameController` is responsible for moving objects in the game, including the aforementioned bullet.

```java
public class GameController {

  protected final Bullet bullet;

  public GameController() {
    bullet = new Bullet();
  }

  public void moveBullet(float offset) {
    var currentPosition = bullet.getPosition();
    bullet.setPosition(currentPosition + offset);
  }

  public float getBulletPosition() {
    return bullet.getPosition();
  }
}
```

Now we introduce the game loop. Actually, in this demo we have 3 different game loops. Let's see the base class `GameLoop` first.

```java
public enum GameStatus {

  RUNNING, STOPPED
}

public abstract class GameLoop {

  protected final Logger logger = LoggerFactory.getLogger(this.getClass());

  protected volatile GameStatus status;

  protected GameController controller;

  private Thread gameThread;

  public GameLoop() {
    controller = new GameController();
    status = GameStatus.STOPPED;
  }

  public void run() {
    status = GameStatus.RUNNING;
    gameThread = new Thread(this::processGameLoop);
    gameThread.start();
  }

  public void stop() {
    status = GameStatus.STOPPED;
  }

  public boolean isGameRunning() {
    return status == GameStatus.RUNNING;
  }

  protected void processInput() {
    try {
      var lag = new Random().nextInt(200) + 50;
      Thread.sleep(lag);
    } catch (InterruptedException e) {
      logger.error(e.getMessage());
    }
  }

  protected void render() {
    var position = controller.getBulletPosition();
    logger.info("Current bullet position: " + position);
  }

  protected abstract void processGameLoop();
}
```

Here's the first game loop implementation, `FrameBasedGameLoop`:

```java
public class FrameBasedGameLoop extends GameLoop {

  @Override
  protected void processGameLoop() {
    while (isGameRunning()) {
      processInput();
      update();
      render();
    }
  }

  protected void update() {
    controller.moveBullet(0.5f);
  }
}
```

Here's the second game loop implementation, `FixedStepGameLoop`:

```java
public class FixedStepGameLoop extends GameLoop {

  /**
   * 20 ms per frame = 50 FPS.
   */
  private static final long MS_PER_FRAME = 20;

  @Override
  protected void processGameLoop() {
    var previousTime = System.currentTimeMillis();
    var lag = 0L;
    while (isGameRunning()) {
      var currentTime = System.currentTimeMillis();
      var elapsedTime = currentTime - previousTime;
      previousTime = currentTime;
      lag += elapsedTime;

      processInput();

      while (lag >= MS_PER_FRAME) {
        update();
        lag -= MS_PER_FRAME;
      }

      render();
    }
  }

  protected void update() {
    controller.moveBullet(0.5f * MS_PER_FRAME / 1000);
  }
}
```

And the third game loop implementation, `VariableStepGameLoop`:

```java
public class VariableStepGameLoop extends GameLoop {

  @Override
  protected void processGameLoop() {
    var lastFrameTime = System.currentTimeMillis();
    while (isGameRunning()) {
      processInput();
      var currentFrameTime = System.currentTimeMillis();
      var elapsedTime = currentFrameTime - lastFrameTime;
      update(elapsedTime);
      lastFrameTime = currentFrameTime;
      render();
    }
  }

  protected void update(Long elapsedTime) {
    controller.moveBullet(0.5f * elapsedTime / 1000);
  }

}
```

Finally, we show all the game loops in action.

```java
public static void main(String[] args) {

    try {
        LOGGER.info("Start frame-based game loop:");
        var frameBasedGameLoop = new FrameBasedGameLoop();
        frameBasedGameLoop.run();
        Thread.sleep(GAME_LOOP_DURATION_TIME);
        frameBasedGameLoop.stop();
        LOGGER.info("Stop frame-based game loop.");

        LOGGER.info("Start variable-step game loop:");
        var variableStepGameLoop = new VariableStepGameLoop();
        variableStepGameLoop.run();
        Thread.sleep(GAME_LOOP_DURATION_TIME);
        variableStepGameLoop.stop();
        LOGGER.info("Stop variable-step game loop.");

        LOGGER.info("Start fixed-step game loop:");
        var fixedStepGameLoop = new FixedStepGameLoop();
        fixedStepGameLoop.run();
        Thread.sleep(GAME_LOOP_DURATION_TIME);
        fixedStepGameLoop.stop();
        LOGGER.info("Stop variable-step game loop.");

    } catch (InterruptedException e) {
        LOGGER.error(e.getMessage());
    }
}
```

Program output:

```java
Start frame-based game loop:
Current bullet position: 0.5
Current bullet position: 1.0
Current bullet position: 1.5
Current bullet position: 2.0
Current bullet position: 2.5
Current bullet position: 3.0
Current bullet position: 3.5
Current bullet position: 4.0
Current bullet position: 4.5
Current bullet position: 5.0
Current bullet position: 5.5
Current bullet position: 6.0
Stop frame-based game loop.
Start variable-step game loop:
Current bullet position: 6.5
Current bullet position: 0.038
Current bullet position: 0.084
Current bullet position: 0.145
Current bullet position: 0.1805
Current bullet position: 0.28
Current bullet position: 0.32
Current bullet position: 0.42549998
Current bullet position: 0.52849996
Current bullet position: 0.57799995
Current bullet position: 0.63199997
Current bullet position: 0.672
Current bullet position: 0.778
Current bullet position: 0.848
Current bullet position: 0.8955
Current bullet position: 0.9635
Stop variable-step game loop.
Start fixed-step game loop:
Current bullet position: 0.0
Current bullet position: 1.086
Current bullet position: 0.059999995
Current bullet position: 0.12999998
Current bullet position: 0.24000004
Current bullet position: 0.33999994
Current bullet position: 0.36999992
Current bullet position: 0.43999985
Current bullet position: 0.5399998
Current bullet position: 0.65999967
Current bullet position: 0.68999964
Current bullet position: 0.7299996
Current bullet position: 0.79999954
Current bullet position: 0.89999944
Current bullet position: 0.98999935
Stop variable-step game loop.
```

## [When to Use the Game Loop Pattern in Java](https://java-design-patterns.com/patterns/game-loop/#when-to-use-the-game-loop-pattern-in-java)

The Game Loop pattern is perfect for real-time simulations and gaming where continuous state updates and smooth frame rates are critical.

## [Real-World Applications of Game Loop Pattern in Java](https://java-design-patterns.com/patterns/game-loop/#real-world-applications-of-game-loop-pattern-in-java)

- Video games, both 2D and 3D, across various platforms.
- Real-time simulations that require a steady frame rate for updating logic and rendering.

## [Benefits and Trade-offs of Game Loop Pattern](https://java-design-patterns.com/patterns/game-loop/#benefits-and-trade-offs-of-game-loop-pattern)

Benefits:

- Ensures the game progresses smoothly and deterministically.
- Facilitates synchronization between the game state, user input, and screen rendering.
- Provides a clear structure for the game developers to manage game dynamics and timing.

Trade-offs:

- Can lead to performance issues if the loop is not well-managed, especially in resource-intensive updates or rendering.
- Difficulty in managing varying frame rates across different hardware.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/game-loop/#related-java-design-patterns)

- [State](https://java-design-patterns.com/patterns/state/): Often used within a game loop to manage different states of the game (e.g., menu, playing, paused). The relationship lies in managing the state-specific behavior and transitions smoothly within the game loop.
- [Observer](https://java-design-patterns.com/patterns/observer/): Useful in a game loop for event handling, where game entities can subscribe to and react to events (e.g., collision, scoring).

## [References and Credits](https://java-design-patterns.com/patterns/game-loop/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/3K96fOn)
- [Game Engine Architecture, Third Edition](https://amzn.to/3VgB4av)
- [Real-Time Collision Detection](https://amzn.to/3W9Jj8T)
- [Game Programming Patterns - Game Loop](http://gameprogrammingpatterns.com/game-loop.html)

---

## [behavioral/health-check] Health Check
> 官方文档: https://java-design-patterns.com/patterns/health-check/

BehavioralFault toleranceMicroservicesMonitoringSystem healthAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/health-check/#also-known-as)

- Health Monitoring
- Service Health Check

## [Intent of Health Check Design Pattern](https://java-design-patterns.com/patterns/health-check/#intent-of-health-check-design-pattern)

The Health Check pattern in Java is designed to proactively monitor the health of individual software components or services, allowing for quick identification and remediation of issues that may affect overall system functionality in microservices architectures.

## [Detailed Explanation of Health Check Pattern with Real-World Examples](https://java-design-patterns.com/patterns/health-check/#detailed-explanation-of-health-check-pattern-with-real-world-examples)

Real-world example

> Consider a hospital where patient monitoring systems are used to ensure the health of patients. Each monitoring device periodically checks the vital signs of a patient and reports back to a central system. Similarly, in Java-based software systems, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If any device detects abnormal vital signs, it triggers an alert for immediate medical attention. Similarly, in software, a Health Check pattern allows each service to periodically report its status to a central monitoring system. If a service is found to be unhealthy, the system can take corrective actions such as alerting administrators, restarting the service, or redirecting traffic to healthy instances, thereby ensuring continuous and reliable operation.

In plain words

> The Health Check Pattern is like a regular doctor's visit for services in a microservices architecture. It helps in early detection of issues and ensures that services are healthy and available.

Sequence diagram

![Health Check sequence diagram](https://java-design-patterns.com/assets/img/health-check-sequence-diagram.ebaa8828.png)

## [Programmatic Example of Health Check Pattern in Java](https://java-design-patterns.com/patterns/health-check/#programmatic-example-of-health-check-pattern-in-java)

The Health Check design pattern is particularly useful in distributed systems where the health of individual components can affect the overall health of the system. Using Spring Boot Actuator, developers can easily implement health checks in Java applications.

In the provided code, we can see an example of the Health Check pattern in the `App` class and the use of Spring Boot's Actuator.

The `App` class is the entry point of the application. It starts a Spring Boot application which has health check capabilities built-in through the use of Spring Boot Actuator.

```java
@EnableCaching
@EnableScheduling
@SpringBootApplication
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}
```

Spring Boot Actuator provides several built-in health checks through its `/actuator/health` endpoint. For example, it can check the status of the database connection, disk space, and other important system parameters. You can also add custom health checks as needed.

To add a custom health check, you can create a class that implements the `HealthIndicator` interface and override its `health` method. Here is an example:

```java
@Component
public class CustomHealthCheck implements HealthIndicator {
    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down()
              .withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    public int check() {
        // Our logic to check health
        return 0;
    }
}
```

In this example, the `check` method contains the logic for the health check. If the health check fails, it returns a non-zero error code, and the `health` method builds a `DOWN` health status with the error code. If the health check passes, it returns a `UP` health status.

This is a basic example of the Health Check pattern, where health checks are built into the system and can be easily accessed and monitored.

## [When to Use the Health Check Pattern in Java](https://java-design-patterns.com/patterns/health-check/#when-to-use-the-health-check-pattern-in-java)

- Use when building Java microservices or distributed systems where it is crucial to monitor the health of each service.
- Suitable for scenarios where automated systems need to determine the operational status of services to perform load balancing, failover, or recovery operations.

## [Real-World Applications of Health Check Pattern in Java](https://java-design-patterns.com/patterns/health-check/#real-world-applications-of-health-check-pattern-in-java)

Known uses of the Health Check pattern in Java include

- Kubernetes liveness and readiness probes
- AWS elastic load balancing health checks
- Spring Boot Actuator integrations

## [Benefits and Trade-offs of Health Check Pattern](https://java-design-patterns.com/patterns/health-check/#benefits-and-trade-offs-of-health-check-pattern)

Benefits:

- Improved system reliability through early detection of failures.
- Enhanced system availability by allowing for automatic or manual recovery processes.
- Simplifies maintenance and operations by providing clear visibility into system health.

Trade-offs:

- Additional overhead for implementing and maintaining health check mechanisms.
- May introduce complexity in handling false positives and negatives in health status reporting.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/health-check/#related-java-design-patterns)

- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Both patterns enhance system resilience; while Health Check monitors health status, Circuit Breaker protects a system from repeated failures.
- [Observer](https://java-design-patterns.com/patterns/observer/): Health Check can be seen as a specific use case of the Observer pattern, where the subject being observed is the system’s health.

## [References and Credits](https://java-design-patterns.com/patterns/health-check/#references-and-credits)

- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
- [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF)
- [Pattern: Health Check API (Microservices.io)](https://microservices.io/patterns/observability/health-check-api.html)

---

## [behavioral/identity-map] Identity Map
> 官方文档: https://java-design-patterns.com/patterns/identity-map/

BehavioralData accessDecouplingEnterprise patternsObject mappingPersistencePerformanceAbout 4 min

* * *

## [Intent of Identity Map Design Pattern](https://java-design-patterns.com/patterns/identity-map/#intent-of-identity-map-design-pattern)

The Identity Map design pattern in Java aims to ensure that each object gets loaded only once by keeping every loaded object in a map, enhancing database performance and memory management.

## [Detailed Explanation of Identity Map Pattern with Real-World Examples](https://java-design-patterns.com/patterns/identity-map/#detailed-explanation-of-identity-map-pattern-with-real-world-examples)

Real-world example

> Imagine you are organizing a conference and have a registration desk where every attendee must check in. This scenario illustrates the Identity Map pattern in Java which prevents duplicate objects. To avoid unnecessary delays and confusion, each attendee's details are entered into a computer system the first time they check in. If the same attendee comes to the desk again, the system quickly retrieves their details without requiring them to re-submit the same information. This ensures each attendee's information is handled efficiently and consistently, similar to how the Identity Map pattern ensures that an object is loaded only once and reused throughout the application.

In plain words

> The Identity Map design pattern ensures that each unique object is loaded only once and reused from a central registry, preventing duplicate objects in an application's memory.

Wikipedia says

> In the design of DBMS, the identity map pattern is a database access design pattern used to improve performance by providing a context-specific, in-memory cache to prevent duplicate retrieval of the same object data from the database.

Sequence diagram

![Identity Map sequence diagram](https://java-design-patterns.com/assets/img/identity-map-sequence-diagram.4d5c630e.png)

## [Programmatic Example of Identity Map Pattern in Java](https://java-design-patterns.com/patterns/identity-map/#programmatic-example-of-identity-map-pattern-in-java)

For the purpose of this demonstration in Java programming, assume we have already created a database instance, showcasing the Identity Map pattern to avoid duplicate objects in memory.

Let's first look at the implementation of `Person` entity, and it's fields:

```java
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Getter
@Setter
@AllArgsConstructor
public final class Person implements Serializable {

    private static final long serialVersionUID = 1L;

    @EqualsAndHashCode.Include
    private int personNationalId;
    private String name;
    private long phoneNum;

    @Override
    public String toString() {
        return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum;
    }
}
```

The following is the implementation of the `PersonFinder` which is the entity that the user will utilize in order to search for a record in our database. It has the relevant DB attached to it. It also maintains an `IdentityMap` to store the recently read records.

```java
@Slf4j
@Getter
@Setter
public class PersonFinder {
    private static final long serialVersionUID = 1L;
    //  Access to the Identity Map
    private IdentityMap identityMap = new IdentityMap();
    private PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation();

    public Person getPerson(int key) {
        // Try to find person in the identity map
        Person person = this.identityMap.getPerson(key);
        if (person != null) {
            LOGGER.info("Person found in the Map");
            return person;
        } else {
            // Try to find person in the database
            person = this.db.find(key);
            if (person != null) {
                this.identityMap.addPerson(person);
                LOGGER.info("Person found in DB.");
                return person;
            }
            LOGGER.info("Person with this ID does not exist.");
            return null;
        }
    }
}
```

The identity map field in the above class is simply an abstraction of a hashMap with **personNationalId** as the keys and the corresponding person object as the value. Here is its implementation:

```java
@Slf4j
@Getter
public class IdentityMap {
    private Map<Integer, Person> personMap = new HashMap<>();

    public void addPerson(Person person) {
        if (!personMap.containsKey(person.getPersonNationalId())) {
            personMap.put(person.getPersonNationalId(), person);
        } else { // Ensure that addPerson does not update a record. This situation will never arise in our implementation. Added only for testing purposes.
            LOGGER.info("Key already in Map");
        }
    }

    public Person getPerson(int id) {
        Person person = personMap.get(id);
        if (person == null) {
            LOGGER.info("ID not in Map.");
        }
        return person;
    }

    public int size() {
        if (personMap == null) {
            return 0;
        }
        return personMap.size();
    }
}
```

Now, let's see how the identity map works in our `App`'s `main` function.

```java
public static void main(String[] args) {

    // Dummy Persons
    Person person1 = new Person(1, "John", 27304159);
    Person person2 = new Person(2, "Thomas", 42273631);
    Person person3 = new Person(3, "Arthur", 27489171);
    Person person4 = new Person(4, "Finn", 20499078);
    Person person5 = new Person(5, "Michael", 40599078);

    // Init database
    PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation();
    db.insert(person1);
    db.insert(person2);
    db.insert(person3);
    db.insert(person4);
    db.insert(person5);

    // Init a personFinder
    PersonFinder finder = new PersonFinder();
    finder.setDb(db);

    // Find persons in DataBase not the map.
    LOGGER.info(finder.getPerson(2).toString());
    LOGGER.info(finder.getPerson(4).toString());
    LOGGER.info(finder.getPerson(5).toString());
    // Find the person in the map.
    LOGGER.info(finder.getPerson(2).toString());
}
```

Running the example produces the following console output:

```
11:19:43.775 [main] INFO com.iluwatar.identitymap.IdentityMap -- ID not in Map.
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonDbSimulatorImplementation -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in DB.
11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631
11:19:43.780 [main] INFO com.iluwatar.identitymap.IdentityMap -- ID not in Map.
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonDbSimulatorImplementation -- Person ID is : 4 ; Person Name is : Finn ; Phone Number is :20499078
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in DB.
11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 4 ; Person Name is : Finn ; Phone Number is :20499078
11:19:43.780 [main] INFO com.iluwatar.identitymap.IdentityMap -- ID not in Map.
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonDbSimulatorImplementation -- Person ID is : 5 ; Person Name is : Michael ; Phone Number is :40599078
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in DB.
11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 5 ; Person Name is : Michael ; Phone Number is :40599078
11:19:43.780 [main] INFO com.iluwatar.identitymap.IdentityMap -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631
11:19:43.780 [main] INFO com.iluwatar.identitymap.PersonFinder -- Person found in the Map
11:19:43.780 [main] INFO com.iluwatar.identitymap.App -- Person ID is : 2 ; Person Name is : Thomas ; Phone Number is :42273631
```

## [When to Use the Identity Map Pattern in Java](https://java-design-patterns.com/patterns/identity-map/#when-to-use-the-identity-map-pattern-in-java)

The Identity Map design pattern is used in Java applications where multiple accesses to the same data occur within a single session or transaction, ensuring efficient object mapping and consistency.

## [Identity Map Pattern Java Tutorials](https://java-design-patterns.com/patterns/identity-map/#identity-map-pattern-java-tutorials)

- [Identity Map Pattern (Source Code Examples)](https://www.sourcecodeexamples.net/2018/04/identity-map-pattern.html)

## [Real-World Applications of Identity Map Pattern in Java](https://java-design-patterns.com/patterns/identity-map/#real-world-applications-of-identity-map-pattern-in-java)

- ORM (Object-Relational Mapping) frameworks in Java often implement Identity Maps to handle database interactions more efficiently, demonstrating the pattern’s importance in Java design patterns.
- Enterprise applications to maintain consistent data states across different business processes.

## [Benefits and Trade-offs of Identity Map Pattern](https://java-design-patterns.com/patterns/identity-map/#benefits-and-trade-offs-of-identity-map-pattern)

Benefits:

- Reduces memory usage by ensuring that only one copy of each object resides in memory.
- Prevents inconsistencies during updates, as all parts of the application refer to the same instance.
- Improves performance by avoiding repeated database reads for the same data.

Trade-offs:

- Increases complexity in object management and persistence logic.
- Can lead to stale data if not managed correctly, especially in concurrent environments.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/identity-map/#related-java-design-patterns)

- [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Separates persistence logic from domain logic. Identity Map can be used by a Data Mapper to ensure that each object is loaded only once, enhancing performance and data consistency.
- [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Coordinates the actions of multiple objects by keeping track of changes and handling transactional consistency. Identity Map is used within the Unit of Work to track the objects being affected by a transaction.

## [References and Credits](https://java-design-patterns.com/patterns/identity-map/#references-and-credits)

- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Java Persistence with Hibernate](https://amzn.to/4aUfyhd)
- [Pro Java EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework](https://amzn.to/49YQN24)

---

## [behavioral/interpreter] Interpreter 解释器
> 官方文档: https://java-design-patterns.com/patterns/interpreter/

BehavioralAbstractionData transformationDecouplingDomainGang of FourPolymorphismRuntimeAbout 4 min

* * *

## [Intent of Interpreter Design Pattern](https://java-design-patterns.com/patterns/interpreter/#intent-of-interpreter-design-pattern)

The Interpreter design pattern is used to define a grammatical representation for a language and provides an interpreter to handle this grammar. This pattern is useful in scenarios where a specific set of rules or grammar needs to be interpreted and acted upon, such as in arithmetic expressions or scripting languages.

## [Detailed Explanation of Interpreter Pattern with Real-World Examples](https://java-design-patterns.com/patterns/interpreter/#detailed-explanation-of-interpreter-pattern-with-real-world-examples)

Real-world example

> Consider a calculator application designed to interpret and calculate expressions entered by users. The application uses the Interpreter pattern in Java to parse and evaluate arithmetic expressions such as "5 + 3 \* 2". Here, the Interpreter translates each part of the expression into objects that represent numbers and operations. These objects follow a defined grammar that allows the application to understand and compute the result correctly based on the rules of arithmetic. Each element of the expression corresponds to a class in the program's structure, simplifying the parsing and evaluation process for any inputted arithmetic formula.

In plain words

> The Interpreter design pattern defines a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences in the language.

Wikipedia says

> In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client.

Sequence diagram

![Interpreter sequence diagram](https://java-design-patterns.com/assets/img/interpreter-sequence-diagram.3208aea3.png)

## [Programmatic Example of Interpreter Pattern in Java](https://java-design-patterns.com/patterns/interpreter/#programmatic-example-of-interpreter-pattern-in-java)

To be able to interpret basic math in Java, we need a hierarchy of expressions. The `Expression` class is the base, and concrete implementations like `NumberExpression` handle specific parts of the grammar. The Interpreter pattern in Java simplifies parsing and evaluating arithmetic expressions by translating them into a structured format that the application can process.

```java
public abstract class Expression {

    public abstract int interpret();

    @Override
    public abstract String toString();
}
```

The simplest of the expressions is the `NumberExpression` that contains only a single integer number.

```java
public class NumberExpression extends Expression {

    private final int number;

    public NumberExpression(int number) {
        this.number = number;
    }

    public NumberExpression(String s) {
        this.number = Integer.parseInt(s);
    }

    @Override
    public int interpret() {
        return number;
    }

    @Override
    public String toString() {
        return "number";
    }
}
```

The more complex expressions are operations such as `PlusExpression`, `MinusExpression`, and `MultiplyExpression`. Here's the first of them, the others are similar.

```java
public class PlusExpression extends Expression {

    private final Expression leftExpression;
    private final Expression rightExpression;

    public PlusExpression(Expression leftExpression, Expression rightExpression) {
        this.leftExpression = leftExpression;
        this.rightExpression = rightExpression;
    }

    @Override
    public int interpret() {
        return leftExpression.interpret() + rightExpression.interpret();
    }

    @Override
    public String toString() {
        return "+";
    }
}
```

Now, we are able to show the interpreter pattern in action parsing some simple math.

```java
@Slf4j
public class App {

    public static void main(String[] args) {

        // the halfling kids are learning some basic math at school
        // define the math string we want to parse
        final var tokenString = "4 3 2 - 1 + *";

        // the stack holds the parsed expressions
        var stack = new Stack<Expression>();

        // tokenize the string and go through them one by one
        var tokenList = tokenString.split(" ");
        for (var s : tokenList) {
            if (isOperator(s)) {
                // when an operator is encountered we expect that the numbers can be popped from the top of
                // the stack
                var rightExpression = stack.pop();
                var leftExpression = stack.pop();
                LOGGER.info("popped from stack left: {} right: {}",
                        leftExpression.interpret(), rightExpression.interpret());
                var operator = getOperatorInstance(s, leftExpression, rightExpression);
                LOGGER.info("operator: {}", operator);
                var result = operator.interpret();
                // the operation result is pushed on top of the stack
                var resultExpression = new NumberExpression(result);
                stack.push(resultExpression);
                LOGGER.info("push result to stack: {}", resultExpression.interpret());
            } else {
                // numbers are pushed on top of the stack
                var i = new NumberExpression(s);
                stack.push(i);
                LOGGER.info("push to stack: {}", i.interpret());
            }
        }
        // in the end, the final result lies on top of the stack
        LOGGER.info("result: {}", stack.pop().interpret());
    }

    public static boolean isOperator(String s) {
        return s.equals("+") || s.equals("-") || s.equals("*");
    }

    public static Expression getOperatorInstance(String s, Expression left, Expression right) {
        return switch (s) {
            case "+" -> new PlusExpression(left, right);
            case "-" -> new MinusExpression(left, right);
            default -> new MultiplyExpression(left, right);
        };
    }
}
```

Executing the program produces the following console output.

```
13:33:15.437 [main] INFO com.iluwatar.interpreter.App -- push to stack: 4
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push to stack: 3
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push to stack: 2
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- popped from stack left: 3 right: 2
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- operator: -
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push result to stack: 1
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push to stack: 1
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- popped from stack left: 1 right: 1
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- operator: +
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push result to stack: 2
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- popped from stack left: 4 right: 2
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- operator: *
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- push result to stack: 8
13:33:15.440 [main] INFO com.iluwatar.interpreter.App -- result: 8
```

## [When to Use the Interpreter Pattern in Java](https://java-design-patterns.com/patterns/interpreter/#when-to-use-the-interpreter-pattern-in-java)

Use the Interpreter design pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when

- The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time.
- Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

## [Real-World Applications of Interpreter Pattern in Java](https://java-design-patterns.com/patterns/interpreter/#real-world-applications-of-interpreter-pattern-in-java)

- [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)
- [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html)
- All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html)
- [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html)
- SQL parsers in various database management systems.

## [Benefits and Trade-offs of Interpreter Pattern](https://java-design-patterns.com/patterns/interpreter/#benefits-and-trade-offs-of-interpreter-pattern)

Benefits:

- Adds new operations to interpret expressions easily without changing the grammar or classes of data.
- Implements grammar directly in the language, making it easy to modify or extend.

Trade-offs:

- Can become complex and inefficient for large grammars.
- Each rule in the grammar results in a class, leading to a large number of classes for complex grammars.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/interpreter/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Often used together, where the Interpreter pattern leverages the Composite pattern to represent the grammar as a tree structure.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Useful for sharing state to reduce memory usage in the Interpreter pattern, particularly for interpreters that deal with repetitive elements in a language.

## [References and Credits](https://java-design-patterns.com/patterns/interpreter/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [behavioral/iterator] Iterator 迭代器
> 官方文档: https://java-design-patterns.com/patterns/iterator/

BehavioralData accessData transformationDecouplingGang of FourObject compositionPolymorphismAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/iterator/#also-known-as)

- Cursor

## [Intent of Iterator Design Pattern](https://java-design-patterns.com/patterns/iterator/#intent-of-iterator-design-pattern)

The Iterator Design Pattern in Java provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. This behavioral pattern is crucial for efficient collection traversal.

## [Detailed Explanation of Iterator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/iterator/#detailed-explanation-of-iterator-pattern-with-real-world-examples)

Real-world example

> Imagine visiting a library with a vast collection of books organized in different sections such as fiction, non-fiction, science, etc. Instead of searching through every shelf yourself, the librarian provides you with a specific guidebook or a digital catalog for each section. This guidebook acts as an "iterator," allowing you to go through the books section by section, or even skip to specific types of books, without needing to know how the books are organized on the shelves. Each guidebook handles the traversal through its section, providing a consistent and efficient way to access the books, much like how the Iterator design pattern offers a uniform method to traverse different data structures in a software application.

In plain words

> The Java Iterator Design Pattern provides a method to sequentially access elements of a collection without exposing its underlying structure. This pattern is widely used in Java programming for efficient data access.

Wikipedia says

> In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.

Sequence diagram

![Iterator sequence diagram](https://java-design-patterns.com/assets/img/iterator-sequence-diagram.c040c529.png)

## [Programmatic Example of Iterator Pattern in Java](https://java-design-patterns.com/patterns/iterator/#programmatic-example-of-iterator-pattern-in-java)

The main class in our Java Iterator Design Pattern example is the `TreasureChest` that contains items. This demonstrates how to implement and use iterators for efficient collection traversal in Java.

```java
public class TreasureChest {

  private final List<Item> items;

  public TreasureChest() {
    items = List.of(
        new Item(ItemType.POTION, "Potion of courage"),
        new Item(ItemType.RING, "Ring of shadows"),
        new Item(ItemType.POTION, "Potion of wisdom"),
        new Item(ItemType.POTION, "Potion of blood"),
        new Item(ItemType.WEAPON, "Sword of silver +1"),
        new Item(ItemType.POTION, "Potion of rust"),
        new Item(ItemType.POTION, "Potion of healing"),
        new Item(ItemType.RING, "Ring of armor"),
        new Item(ItemType.WEAPON, "Steel halberd"),
        new Item(ItemType.WEAPON, "Dagger of poison"));
  }

  public Iterator<Item> iterator(ItemType itemType) {
    return new TreasureChestItemIterator(this, itemType);
  }

  public List<Item> getItems() {
    return new ArrayList<>(items);
  }
}
```

Here's the `Item` class:

```java
public class Item {

  private ItemType type;
  private final String name;

  public Item(ItemType type, String name) {
    this.setType(type);
    this.name = name;
  }

  @Override
  public String toString() {
    return name;
  }

  public ItemType getType() {
    return type;
  }

  public final void setType(ItemType type) {
    this.type = type;
  }
}

public enum ItemType {

  ANY, WEAPON, RING, POTION

}
```

The `Iterator` interface is extremely simple.

```java
public interface Iterator<T> {

  boolean hasNext();

  T next();
}
```

In the following example, we demonstrate different kinds of iterators.

```java
@Slf4j
public class App {

    private static final TreasureChest TREASURE_CHEST = new TreasureChest();

    private static void demonstrateTreasureChestIteratorForType(ItemType itemType) {
        LOGGER.info("------------------------");
        LOGGER.info("Item Iterator for ItemType " + itemType + ": ");
        var itemIterator = TREASURE_CHEST.iterator(itemType);
        while (itemIterator.hasNext()) {
            LOGGER.info(itemIterator.next().toString());
        }
    }

    private static void demonstrateBstIterator() {
        LOGGER.info("------------------------");
        LOGGER.info("BST Iterator: ");
        var root = buildIntegerBst();
        var bstIterator = new BstIterator<>(root);
        while (bstIterator.hasNext()) {
            LOGGER.info("Next node: " + bstIterator.next().getVal());
        }
    }

    private static TreeNode<Integer> buildIntegerBst() {
        var root = new TreeNode<>(8);

        root.insert(3);
        root.insert(10);
        root.insert(1);
        root.insert(6);
        root.insert(14);
        root.insert(4);
        root.insert(7);
        root.insert(13);

        return root;
    }

    public static void main(String[] args) {
        demonstrateTreasureChestIteratorForType(RING);
        demonstrateTreasureChestIteratorForType(POTION);
        demonstrateTreasureChestIteratorForType(WEAPON);
        demonstrateTreasureChestIteratorForType(ANY);
        demonstrateBstIterator();
    }
}
```

Program output:

```
13:36:37.087 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType RING:
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of shadows
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of armor
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType POTION:
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of courage
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of wisdom
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of blood
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of rust
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of healing
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType WEAPON:
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Sword of silver +1
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Steel halberd
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Dagger of poison
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Item Iterator for ItemType ANY:
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of courage
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of shadows
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of wisdom
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of blood
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Sword of silver +1
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of rust
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Potion of healing
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Ring of armor
13:36:37.089 [main] INFO com.iluwatar.iterator.App -- Steel halberd
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Dagger of poison
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- ------------------------
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- BST Iterator:
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 1
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 3
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 4
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 6
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 7
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 8
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 10
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 13
13:36:37.090 [main] INFO com.iluwatar.iterator.App -- Next node: 14
```

## [When to Use the Iterator Pattern in Java](https://java-design-patterns.com/patterns/iterator/#when-to-use-the-iterator-pattern-in-java)

Use the Iterator design pattern in Java

- To access an aggregate object's contents without exposing its internal representation.
- To support multiple traversals of aggregate objects.
- To provide a uniform interface for traversing different aggregate structures.

## [Iterator Pattern Java Tutorials](https://java-design-patterns.com/patterns/iterator/#iterator-pattern-java-tutorials)

- [Java - How to Use Iterator? (TutorialsPoint)](http://www.tutorialspoint.com/java/java_using_iterator.htm)

## [Real-World Applications of Iterator Pattern in Java](https://java-design-patterns.com/patterns/iterator/#real-world-applications-of-iterator-pattern-in-java)

- Java Collections Framework utilizes iterators extensively to allow different ways to traverse through collections.
- Databases often use iterators to navigate through data records fetched through SQL queries.
- [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)
- [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html)

## [Benefits and Trade-offs of Iterator Pattern](https://java-design-patterns.com/patterns/iterator/#benefits-and-trade-offs-of-iterator-pattern)

Benefits:

- Reduces the coupling between data structures and algorithms used for iteration.
- Provides a uniform interface for iterating over various types of data structures, enhancing code reusability and flexibility.

Trade-offs:

- Overhead of using an iterator object may slightly reduce performance compared to direct traversal methods.
- Complex aggregate structures may require complex iterators that can be difficult to manage or extend.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/iterator/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Iterators are often used to traverse Composite trees.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Used to create appropriate iterators for different data structures.
- [Visitor](https://java-design-patterns.com/patterns/visitor/): Can be used with Iterator to apply operations over elements of an object structure.

## [References and Credits](https://java-design-patterns.com/patterns/iterator/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)

---

## [behavioral/mediator] Mediator 中介者
> 官方文档: https://java-design-patterns.com/patterns/mediator/

BehavioralDecouplingGang of FourMessagingObject compositionAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/mediator/#also-known-as)

- Controller

## [Intent of Mediator Design Pattern](https://java-design-patterns.com/patterns/mediator/#intent-of-mediator-design-pattern)

The Mediator design pattern is intended to reduce the complexity of communication between multiple objects or classes in a system. It achieves this by providing a centralized mediator class that handles the interactions between different classes, thus reducing their direct dependencies on each other.

## [Detailed Explanation of Mediator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/mediator/#detailed-explanation-of-mediator-pattern-with-real-world-examples)

Real-world example

> Imagine an air traffic control system at a busy airport, where the air traffic controller acts as a mediator. In this scenario, numerous airplanes wish to take off, land, or navigate around the airport's airspace. Instead of each pilot communicating directly with every other pilot, which could lead to confusion and potential accidents, all communication goes through the air traffic controller. The controller receives requests, processes them, and gives clear, organized instructions to each pilot. This centralized system reduces the complexity of communications and ensures safety and efficiency in managing the airport's operations. This is analogous to the Mediator design pattern in software, where a central mediator class handles and coordinates the interaction between different objects or systems.

In plain words

> Mediator decouples a set of classes by forcing their communications flow through a mediating object.

Wikipedia says

> In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior. In object-oriented programming, programs often consist of many classes. Business logic and computation are distributed among these classes. However, as more classes are added to a program, especially during maintenance and/or refactoring, the problem of communication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes. With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling.

Sequence diagram

![Mediator sequence diagram](https://java-design-patterns.com/assets/img/mediator-sequence-diagram.d7a5cb15.png)

## [Programmatic Example of Mediator Pattern in Java](https://java-design-patterns.com/patterns/mediator/#programmatic-example-of-mediator-pattern-in-java)

In this example, the mediator encapsulates how a set of objects interact. Instead of referring to each other directly, they use the mediator interface.

The party members `Rogue`, `Wizard`, `Hobbit`, and `Hunter` all inherit from the `PartyMemberBase`implementing the `PartyMember` interface.

```java
public interface PartyMember {

  void joinedParty(Party party);

  void partyAction(Action action);

  void act(Action action);
}

@Slf4j
public abstract class PartyMemberBase implements PartyMember {

  protected Party party;

  @Override
  public void joinedParty(Party party) {
    LOGGER.info("{} joins the party", this);
    this.party = party;
  }

  @Override
  public void partyAction(Action action) {
    LOGGER.info("{} {}", this, action.getDescription());
  }

  @Override
  public void act(Action action) {
    if (party != null) {
      LOGGER.info("{} {}", this, action);
      party.act(this, action);
    }
  }

  @Override
  public abstract String toString();
}

public class Rogue extends PartyMemberBase {

  @Override
  public String toString() {
    return "Rogue";
  }
}

// Wizard, Hobbit, and Hunter are implemented similarly
```

Our mediator system consists of `Party` interface and its implementation.

```java
public interface Party {

  void addMember(PartyMember member);

  void act(PartyMember actor, Action action);
}

public class PartyImpl implements Party {

  private final List<PartyMember> members;

  public PartyImpl() {
    members = new ArrayList<>();
  }

  @Override
  public void act(PartyMember actor, Action action) {
    for (var member : members) {
      if (!member.equals(actor)) {
        member.partyAction(action);
      }
    }
  }

  @Override
  public void addMember(PartyMember member) {
    members.add(member);
    member.joinedParty(this);
  }
}
```

Here's a demo showing the mediator pattern in action.

```java
public static void main(String[] args) {

    // create party and members
    Party party = new PartyImpl();
    var hobbit = new Hobbit();
    var wizard = new Wizard();
    var rogue = new Rogue();
    var hunter = new Hunter();

    // add party members
    party.addMember(hobbit);
    party.addMember(wizard);
    party.addMember(rogue);
    party.addMember(hunter);

    // perform actions -> the other party members
    // are notified by the party
    hobbit.act(Action.ENEMY);
    wizard.act(Action.TALE);
    rogue.act(Action.GOLD);
    hunter.act(Action.HUNT);
}
```

Here's the console output from running the example.

```
14:05:15.081 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit joins the party
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard joins the party
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue joins the party
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter joins the party
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit spotted enemies
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard runs for cover
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue runs for cover
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter runs for cover
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard tells a tale
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit comes to listen
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue comes to listen
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter comes to listen
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue found gold
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit takes his share of the gold
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard takes his share of the gold
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter takes his share of the gold
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hunter hunted a rabbit
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Hobbit arrives for dinner
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Wizard arrives for dinner
14:05:15.083 [main] INFO com.iluwatar.mediator.PartyMemberBase -- Rogue arrives for dinner
```

## [When to Use the Mediator Pattern in Java](https://java-design-patterns.com/patterns/mediator/#when-to-use-the-mediator-pattern-in-java)

Use the Mediator pattern when

- A set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand
- Reusing an object is difficult because it refers to and communicates with many other objects
- A behavior that's distributed between several classes should be customizable without a lot of subclassing

## [Real-World Applications of Mediator Pattern in Java](https://java-design-patterns.com/patterns/mediator/#real-world-applications-of-mediator-pattern-in-java)

- All scheduleXXX() methods of [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html)
- [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-)
- submit() and invokeXXX() methods of [java.util.concurrent.ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)
- scheduleXXX() methods of [java.util.concurrent.ScheduledExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html)
- [java.lang.reflect.Method#invoke()](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-)
- Java Message Service (JMS) uses mediators to handle message exchanges between clients and servers.
- JavaBeans property change support class (java.beans.PropertyChangeSupport) acts as a mediator by handling communication between beans regarding property changes.

## [Benefits and Trade-offs of Mediator Pattern](https://java-design-patterns.com/patterns/mediator/#benefits-and-trade-offs-of-mediator-pattern)

Benefits:

- Reduces coupling between components of a program, fostering better organization and easier maintenance.
- Centralizes control. The mediator pattern centralizes the control logic, making it easier to comprehend and manage.

Trade-offs:

- Mediator can become a god object coupled with all classes in the system, gaining too much responsibility and complexity.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/mediator/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Often used together, where the mediator pattern can use the observer pattern to notify various objects about state changes. Mediators effectively act as a channel of communication managed by an observer.
- [Facade](https://java-design-patterns.com/patterns/facade/): Mediator simplifies communication between components, similar to how a facade simplifies a subsystem interface, but a mediator’s colleagues can communicate back to the mediator.
- [Command](https://java-design-patterns.com/patterns/command/): Commands can be mediated as they are dispatched to their receivers, encapsulating a request as an object.

## [References and Credits](https://java-design-patterns.com/patterns/mediator/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)

---

## [behavioral/memento] Memento 备忘录
> 官方文档: https://java-design-patterns.com/patterns/memento/

BehavioralEncapsulationGang of FourMemory managementObject compositionState trackingUndoAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/memento/#also-known-as)

- Snapshot
- Token

## [Intent of Memento Design Pattern](https://java-design-patterns.com/patterns/memento/#intent-of-memento-design-pattern)

The Memento design pattern in Java allows developers to capture and restore an object's internal state without violating encapsulation.

## [Detailed Explanation of Memento Pattern with Real-World Examples](https://java-design-patterns.com/patterns/memento/#detailed-explanation-of-memento-pattern-with-real-world-examples)

Real-world example

> A text editor application can utilize the Memento design pattern in Java to enable undo and redo functionalities. By capturing the current state of a document as a memento each time a change is made, the application can easily restore the document to any previous state. The snapshots are stored in a history list. When the user clicks the undo button, the editor restores the document to the state saved in the most recent memento. This process allows users to revert to previous versions of their document without exposing or altering the internal data structures of the editor.

In plain words

> Memento pattern captures object internal state making it easy to store and restore objects in any point of time.

Wikipedia says

> The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

Sequence diagram

![Memento sequence diagram](https://java-design-patterns.com/assets/img/memento-sequence-diagram.fdcea0d6.png)

## [Programmatic Example of Memento Pattern in Java](https://java-design-patterns.com/patterns/memento/#programmatic-example-of-memento-pattern-in-java)

In our astrology application, we use the Memento pattern to capture and restore the state of star objects. Each state is saved as a memento, allowing us to revert to previous states as needed.

Let's first define the types of stars we are capable to handle.

```java
public enum StarType {
  SUN("sun"),
  RED_GIANT("red giant"),
  WHITE_DWARF("white dwarf"),
  SUPERNOVA("supernova"),
  DEAD("dead star");
  // ...
}
```

Next, let's jump straight to the essentials. Here's the `Star` class along with the mementos that we need to manipulate. Especially pay attention to `getMemento` and `setMemento` methods.

```java
public interface StarMemento {
}

public class Star {

    private StarType type;
    private int ageYears;
    private int massTons;

    public Star(StarType startType, int startAge, int startMass) {
        this.type = startType;
        this.ageYears = startAge;
        this.massTons = startMass;
    }

    public void timePasses() {
        ageYears *= 2;
        massTons *= 8;
        switch (type) {
            case RED_GIANT -> type = StarType.WHITE_DWARF;
            case SUN -> type = StarType.RED_GIANT;
            case SUPERNOVA -> type = StarType.DEAD;
            case WHITE_DWARF -> type = StarType.SUPERNOVA;
            case DEAD -> {
                ageYears *= 2;
                massTons = 0;
            }
            default -> {
            }
        }
    }

    StarMemento getMemento() {
        var state = new StarMementoInternal();
        state.setAgeYears(ageYears);
        state.setMassTons(massTons);
        state.setType(type);
        return state;
    }

    void setMemento(StarMemento memento) {
        var state = (StarMementoInternal) memento;
        this.type = state.getType();
        this.ageYears = state.getAgeYears();
        this.massTons = state.getMassTons();
    }

    @Override
    public String toString() {
        return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons);
    }

    private static class StarMementoInternal implements StarMemento {

        private StarType type;
        private int ageYears;
        private int massTons;

        // setters and getters ->
        // ...
    }
}
```

And finally here's how we use the mementos to store and restore star states.

```java
public static void main(String[] args) {
    var states = new Stack<StarMemento>();

    var star = new Star(StarType.SUN, 10000000, 500000);
    LOGGER.info(star.toString());
    states.add(star.getMemento());
    star.timePasses();
    LOGGER.info(star.toString());
    states.add(star.getMemento());
    star.timePasses();
    LOGGER.info(star.toString());
    states.add(star.getMemento());
    star.timePasses();
    LOGGER.info(star.toString());
    states.add(star.getMemento());
    star.timePasses();
    LOGGER.info(star.toString());
    while (!states.isEmpty()) {
        star.setMemento(states.pop());
        LOGGER.info(star.toString());
    }
}
```

Program output:

```
14:09:15.878 [main] INFO com.iluwatar.memento.App -- sun age: 10000000 years mass: 500000 tons
14:09:15.880 [main] INFO com.iluwatar.memento.App -- red giant age: 20000000 years mass: 4000000 tons
14:09:15.880 [main] INFO com.iluwatar.memento.App -- white dwarf age: 40000000 years mass: 32000000 tons
14:09:15.880 [main] INFO com.iluwatar.memento.App -- supernova age: 80000000 years mass: 256000000 tons
14:09:15.880 [main] INFO com.iluwatar.memento.App -- dead star age: 160000000 years mass: 2048000000 tons
14:09:15.880 [main] INFO com.iluwatar.memento.App -- supernova age: 80000000 years mass: 256000000 tons
14:09:15.880 [main] INFO com.iluwatar.memento.App -- white dwarf age: 40000000 years mass: 32000000 tons
14:09:15.881 [main] INFO com.iluwatar.memento.App -- red giant age: 20000000 years mass: 4000000 tons
14:09:15.881 [main] INFO com.iluwatar.memento.App -- sun age: 10000000 years mass: 500000 tons
```

## [When to Use the Memento Pattern in Java](https://java-design-patterns.com/patterns/memento/#when-to-use-the-memento-pattern-in-java)

Use the Memento pattern when

- You need to capture an object's state in Java and restore it later without exposing its internal structure. This is crucial for maintaining encapsulation and simplifying the management of object states.
- A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.

## [Real-World Applications of Memento Pattern in Java](https://java-design-patterns.com/patterns/memento/#real-world-applications-of-memento-pattern-in-java)

The Memento pattern is used in various Java applications, including the java.util.Date and java.util.Calendar classes, which can revert to previous states. It's also common in text editors and graphic editors for undo mechanisms.

## [Benefits and Trade-offs of Memento Pattern](https://java-design-patterns.com/patterns/memento/#benefits-and-trade-offs-of-memento-pattern)

Benefits:

- Preserves encapsulation boundaries.
- Simplifies the originator by removing the need to manage version history or undo functionality directly.

Trade-offs:

- Can be expensive in terms of memory if a large number of states are saved.
- Care must be taken to manage the lifecycle of mementos to avoid memory leaks.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/memento/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/): Often used together; commands store state for undoing operations in mementos.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Mementos may use prototyping to store the state.

## [References and Credits](https://java-design-patterns.com/patterns/memento/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)

---

## [behavioral/mute-idiom] Mute Idiom
> 官方文档: https://java-design-patterns.com/patterns/mute-idiom/

BehavioralContextDecouplingIdiomError handlingSynchronizationThread managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/mute-idiom/#also-known-as)

- Exception Suppression
- Quiet Exception

## [Intent of Mute Idiom Design Pattern](https://java-design-patterns.com/patterns/mute-idiom/#intent-of-mute-idiom-design-pattern)

The Mute Idiom in Java is a design pattern that simplifies error handling by suppressing non-critical exceptions. This approach is especially useful in multithreaded applications and complex control flow scenarios.

## [Detailed Explanation of Mute Idiom Pattern with Real-World Examples](https://java-design-patterns.com/patterns/mute-idiom/#detailed-explanation-of-mute-idiom-pattern-with-real-world-examples)

Real-world example

> A real-world analogy of the Mute Idiom is found in car door locking mechanisms, where non-critical exceptions (like an already locked door) are ignored, simplifying the system's logic. Similarly, in Java, the Mute Idiom focuses on essential operations, avoiding unnecessary exception handling.
>
> Imagine a car equipped with an automatic locking system that attempts to lock all doors when the car reaches a certain speed. In this system, if one of the doors is already locked, the system doesn't need to alert the driver or perform any special handling; it simply skips locking that door and continues with the others. The locking system "mutes" the handling of already locked doors, focusing only on those that need to be locked. This approach simplifies the logic and avoids unnecessary checks, similar to how the Mute Idiom in software development suppresses handling trivial exceptions.

In plain words

> The Mute Idiom design pattern suppresses the handling of trivial or non-critical exceptions to simplify code.

Flowchart

![Mute Idiom flowchart](https://java-design-patterns.com/assets/img/mute-idiom-flowchart.f31eeaaa.png)

## [Programmatic Example of Mute Idiom Pattern in Java](https://java-design-patterns.com/patterns/mute-idiom/#programmatic-example-of-mute-idiom-pattern-in-java)

In the following Java code example, we demonstrate the Mute Idiom by muting non-critical exceptions during the resource management process. This approach ensures error handling does not interrupt the main logic.

The Mute Idiom is a design pattern that is used to simplify error handling by muting exceptions that are deemed non-critical or expected in specific contexts. This pattern is particularly useful in multithreaded or complex control flow environments.

We have a `Resource` interface that has a `close` method which throws an `IOException`.

```java
public interface Resource extends AutoCloseable {
  @Override
  void close() throws IOException;
}
```

We also have an `App` class that uses this `Resource`. In the `App` class, we have a `useOfLoggedMute` method that demonstrates the use of the Mute Idiom. Here, we acquire a `Resource`, utilize it, and then attempt to close it. The closing of the resource is done in a `finally` block to ensure that it is executed regardless of whether an exception is thrown or not.

```java
public class App {
  // ...

  private static void useOfLoggedMute() {
    Optional<Resource> resource = Optional.empty();
    try {
      resource = Optional.of(acquireResource());
      utilizeResource(resource.get());
    } finally {
      resource.ifPresent(App::closeResource);
    }
  }

  // ...
}
```

The `closeResource` method is where the Mute Idiom is applied. We use the `Mute.loggedMute` method to suppress any `IOException` that might be thrown when closing the resource. This is done because the failure to close a resource is considered a non-critical issue that does not affect the overall logic or outcome of the program.

```java
public class App {
  // ...

  private static void closeResource(Resource resource) {
    Mute.loggedMute(resource::close);
  }

  // ...
}
```

In this way, the Mute Idiom allows us to simplify error handling by reducing boilerplate code for expected exceptions, enhancing code readability and maintainability, and allowing uninterrupted execution for non-critical exceptions.

## [When to Use the Mute Idiom Pattern in Java](https://java-design-patterns.com/patterns/mute-idiom/#when-to-use-the-mute-idiom-pattern-in-java)

The Mute Idiom is applicable in

- Scenarios where certain exceptions are predictable and do not affect the overall logic or outcome.
- Commonly used in logging, cleanup operations, or interacting with third-party APIs in Java.

## [Mute Idiom Pattern Java Tutorials](https://java-design-patterns.com/patterns/mute-idiom/#mute-idiom-pattern-java-tutorials)

- [The Mute Design Pattern (JOOQ)](http://blog.jooq.org/2016/02/18/the-mute-design-pattern/)

## [Real-World Applications of Mute Idiom Pattern in Java](https://java-design-patterns.com/patterns/mute-idiom/#real-world-applications-of-mute-idiom-pattern-in-java)

- Muting exceptions in background tasks or threads where interruption is expected.
- Handling known issues in third-party libraries where exceptions can be safely ignored.

## [Benefits and Trade-offs of Mute Idiom Pattern](https://java-design-patterns.com/patterns/mute-idiom/#benefits-and-trade-offs-of-mute-idiom-pattern)

Benefits:

Using the Mute Idiom

- Simplifies error handling by reducing boilerplate code for expected exceptions.
- Enhances code readability and maintainability.
- Allows uninterrupted execution for non-critical exceptions.

Trade-offs:

- Can lead to missed critical issues if overused or misapplied.
- Makes debugging harder if exceptions are muted indiscriminately.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/mute-idiom/#related-java-design-patterns)

- [Null Object](https://java-design-patterns.com/patterns/null-object/): Both aim to simplify error handling; Null Object avoids null checks while Mute Idiom avoids exception handling complexities.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to wrap functionality with additional error handling or muting behaviors.

## [References and Credits](https://java-design-patterns.com/patterns/mute-idiom/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)

---

## [behavioral/notification] Notification
> 官方文档: https://java-design-patterns.com/patterns/notification/

BehavioralAsynchronousDecouplingEvent-drivenMessagingPublish/subscribeAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/notification/#also-known-as)

- Event Listener

## [Intent of Notification Design Pattern](https://java-design-patterns.com/patterns/notification/#intent-of-notification-design-pattern)

The Notification design pattern in Java aims to facilitate asynchronous communication between different parts of a system by allowing objects to subscribe to specific events and receive updates asynchronously when those events occur.

## [Detailed Explanation of Notification Pattern with Real-World Examples](https://java-design-patterns.com/patterns/notification/#detailed-explanation-of-notification-pattern-with-real-world-examples)

Real-world example

> Consider a weather alert system as a real-world analogous example of the Notification design pattern. In this system, a weather station collects data on weather conditions like temperature, humidity, and storm alerts. Multiple subscribers, such as news agencies, smartphone weather apps, and emergency services, are interested in receiving updates about specific weather events, like severe storms or extreme temperatures.
>
> When the weather station detects a significant event, it publishes this information. All subscribed entities receive these updates automatically without the weather station needing to know the details of these subscribers. For instance, a news agency might use this information to update its weather report, while emergency services might use it to prepare for potential disasters. This system exemplifies the Notification pattern's ability to decouple the publisher (the weather station) from its subscribers and deliver timely updates efficiently.

In plain words

> The Notification design pattern enables an object to automatically notify a list of interested observers about changes or events without knowing the specifics of the subscribers.

Sequence diagram

![Notification sequence diagram](https://java-design-patterns.com/assets/img/notification-sequence-diagram.efe9bae6.png)

## [Programmatic Example of Notification Pattern in Java](https://java-design-patterns.com/patterns/notification/#programmatic-example-of-notification-pattern-in-java)

The Java Notification pattern is used to capture information passed between layers, validate the information, and return any errors to the presentation layer if needed. It reduces coupling between the producer and consumer of events, enhances flexibility and reusability of components, and allows for dynamic event subscription and unsubscription.

In this example, we'll use a form submission scenario to demonstrate the Notification pattern. The form is used to register a worker with their name, occupation, and date of birth. The form data is passed to the domain layer for validation, and any errors are returned to the presentation layer.

Here's the `RegisterWorkerForm` class, which acts as our presentation layer. It takes the worker's details as input and submits the form.

```java
class RegisterWorkerForm {

    private RegisterWorkerForm registerWorkerForm;

    RegisterWorkerForm(String name, String occupation, LocalDate dateOfBirth) {
        // Initialize the form with the worker's details
    }

    void submit() {
        // Submit the form
        // If there are any errors, they will be captured in the worker's notification
    }
}
```

The `RegisterWorker` class acts as our domain layer. It validates the worker's details and returns any errors through the `RegisterWorkerDto`.

```java
class RegisterWorker {

    RegisterWorker(String name, String occupation, LocalDate dateOfBirth) {
        // Validate the worker's details
        // If there are any errors, add them to the notification
    }
}
```

Finally, the `App` class is where the form is created and submitted.

```java
public class App {

  public static void main(String[] args) {
    var form = new RegisterWorkerForm("John Doe", "Engineer", LocalDate.of(1990, 1, 1));
    form.submit();
  }
}
```

In this example, if the worker's details are invalid (e.g. the name is empty), the `RegisterWorker` class will add an error to the notification. The `RegisterWorkerForm` class can then check the notification for any errors after submission. This demonstrates the Notification pattern, where information is passed between layers and any errors are returned to the presentation layer.

The form then processes the submission and returns these error messages to the user, showing our notification worked.

Example output:

```java
18:10:00.075 [main] INFO com.iluwatar.RegisterWorkerForm - Error 1: Name is missing: ""
18:10:00.079 [main] INFO com.iluwatar.RegisterWorkerForm - Error 2: Occupation is missing: ""
18:10:00.079 [main] INFO com.iluwatar.RegisterWorkerForm - Error 4: Worker registered must be over 18: "2016-07-13"
18:10:00.080 [main] INFO com.iluwatar.RegisterWorkerForm - Not registered, see errors
```

## [When to Use the Notification Pattern in Java](https://java-design-patterns.com/patterns/notification/#when-to-use-the-notification-pattern-in-java)

- When a change to one object requires changing others, and you don’t know how many objects need to be changed.
- When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
- When a system component must be notified of events without making assumptions about the system’s other components.

## [Real-World Applications of Notification Pattern in Java](https://java-design-patterns.com/patterns/notification/#real-world-applications-of-notification-pattern-in-java)

- GUI frameworks where user actions trigger responses in the application.
- Notification systems in large-scale distributed systems.
- Event management in microservices architecture.

## [Benefits and Trade-offs of Notification Pattern](https://java-design-patterns.com/patterns/notification/#benefits-and-trade-offs-of-notification-pattern)

Benefits:

- Reduces coupling between the producer and consumer of events.
- Enhances flexibility and reusability of components.
- Allows for dynamic subscription and unsubscription to events.

Trade-offs:

- Can lead to a complex system if not managed well, due to the dynamic nature of subscriptions.
- Debugging can be challenging due to the asynchronous and decoupled nature of events.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/notification/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/): Can be used to encapsulate a request as an object, often used in conjunction with notifications to decouple the sender and receiver.
- [Mediator](https://java-design-patterns.com/patterns/mediator/): Facilitates centralized communication between objects, whereas the Notification pattern is more decentralized.
- [Observer](https://java-design-patterns.com/patterns/observer/): A foundational pattern for the Notification pattern, focusing on one-to-many dependency relationships.

## [References and Credits](https://java-design-patterns.com/patterns/notification/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui)
- [Notification Pattern (Martin Fowler)](https://martinfowler.com/eaaDev/Notification.html)

---

## [behavioral/null-object] Null Object 空对象
> 官方文档: https://java-design-patterns.com/patterns/null-object/

BehavioralCode simplificationDecouplingPolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/null-object/#also-known-as)

- Active Nothing
- Stub

## [Intent of Null Object Design Pattern](https://java-design-patterns.com/patterns/null-object/#intent-of-null-object-design-pattern)

The Null Object Pattern is an essential Java design pattern that provides a seamless way to handle absent objects without performing null checks, streamlining your Java applications.

## [Detailed Explanation of Null Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/null-object/#detailed-explanation-of-null-object-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Null Object pattern can be found in the context of customer service. Imagine a customer service system where there are different types of support representatives: human agents and automated bots. When a customer request is received, the system can assign it to a human agent or, if no agents are available, to an automated bot. If neither human agents nor automated bots are available, the system assigns the request to a "Null Representative."
>
> The Null Representative is a placeholder that does nothing but ensures that the system doesn't crash or raise errors due to the absence of a support representative. It provides default responses like "Your request is being processed" without any actual processing, thereby maintaining system stability and avoiding the need for null checks throughout the codebase.

In plain words

> Null Object pattern handles "empty" objects gracefully.

Wikipedia says

> In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).

Sequence diagram

![Null Object sequence diagram](https://java-design-patterns.com/assets/img/null-object-sequence-diagram.daa63a96.png)

## [Programmatic Example of Null Object in Java](https://java-design-patterns.com/patterns/null-object/#programmatic-example-of-null-object-in-java)

By implementing the Null Object Pattern, Java developers can ensure that their applications handle 'empty' objects more gracefully, enhancing code stability and readability.

We are building a binary tree from nodes. There are ordinary nodes and "empty" nodes. Traversing the tree normally should not cause errors, so we use null object pattern where necessary.

Here's the definition of `Node` interface.

```java
public interface Node {

  String getName();

  int getTreeSize();

  Node getLeft();

  Node getRight();

  void walk();
}
```

We have two implementations of `Node`. The normal implementation `NodeImpl` and `NullNode` for empty nodes.

```java
@Slf4j
public class NodeImpl implements Node {

  private final String name;
  private final Node left;
  private final Node right;

  public NodeImpl(String name, Node left, Node right) {
    this.name = name;
    this.left = left;
    this.right = right;
  }

  @Override
  public int getTreeSize() {
    return 1 + left.getTreeSize() + right.getTreeSize();
  }

  @Override
  public Node getLeft() {
    return left;
  }

  @Override
  public Node getRight() {
    return right;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public void walk() {
    LOGGER.info(name);
    if (left.getTreeSize() > 0) {
      left.walk();
    }
    if (right.getTreeSize() > 0) {
      right.walk();
    }
  }
}

public final class NullNode implements Node {

  private static final NullNode instance = new NullNode();

  private NullNode() {
  }

  public static NullNode getInstance() {
    return instance;
  }

  @Override
  public int getTreeSize() {
    return 0;
  }

  @Override
  public Node getLeft() {
    return null;
  }

  @Override
  public Node getRight() {
    return null;
  }

  @Override
  public String getName() {
    return null;
  }

  @Override
  public void walk() {
    // Do nothing
  }
}
```

Then we can construct and traverse the binary tree without errors as follows.

```java
var root = new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()), NullNode.getInstance()),
        new NodeImpl("12", NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance())));
root.walk();
```

Program output:

```
1
11
111
12
122
```

## [When to Use the Null Object Pattern in Java](https://java-design-patterns.com/patterns/null-object/#when-to-use-the-null-object-pattern-in-java)

- When you need to provide a default behavior in place of a null object.
- To simplify the client code by eliminating null checks.
- When a default action is preferable to handling a null reference.

## [Real-World Applications of Null Object Pattern in Java](https://java-design-patterns.com/patterns/null-object/#real-world-applications-of-null-object-pattern-in-java)

- Commonly used in logging systems, the Null object helps prevent NullPointerExceptions, making it a critical pattern for reliable Java software development.
- Collections that use a NullIterator to handle empty collections gracefully.
- GUI systems where a NullComponent can be used to represent a component that does nothing.

## [Benefits and Trade-offs of Null Object Pattern](https://java-design-patterns.com/patterns/null-object/#benefits-and-trade-offs-of-null-object-pattern)

Benefits:

- Eliminates the need for null checks, reducing the risk of NullPointerException.
- Simplifies the client code and enhances readability.
- Promotes the use of polymorphism by handling default behavior through a common interface.

Trade-offs:

- May introduce additional classes, potentially increasing the overall complexity of the system.
- The default behavior might mask potential issues that would otherwise be caught by explicit null handling.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/null-object/#related-java-design-patterns)

- [Strategy](https://java-design-patterns.com/patterns/strategy/): Null Object can be seen as a special case of the Strategy Pattern where the strategy is to do nothing.
- [State](https://java-design-patterns.com/patterns/state/): Similar in that both patterns can handle different states or behaviors; Null Object is like a state that does nothing.
- [Factory](https://java-design-patterns.com/patterns/factory/): Often used to provide Null Objects in place of actual objects.

## [References and Credits](https://java-design-patterns.com/patterns/null-object/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Pattern Languages of Program Design 3](https://amzn.to/3UZkRF6)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)
- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3UJ7etA)

---

## [behavioral/observer] Observer 观察者
> 官方文档: https://java-design-patterns.com/patterns/observer/

BehavioralDecouplingEvent-drivenGang of FourPublish/subscribeAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/observer/#also-known-as)

- Dependents

## [Intent of Observer Design Pattern](https://java-design-patterns.com/patterns/observer/#intent-of-observer-design-pattern)

The Observer pattern in Java defines a one-to-many relationship between objects, ensuring that when one object updates its state, all dependent observers are notified and updated automatically, enhancing system responsiveness and modularity.

## [Detailed Explanation of Observer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/observer/#detailed-explanation-of-observer-pattern-with-real-world-examples)

Real-world example

> In a real-world example, consider a news agency system where the agency (subject) publishes news articles, and multiple news outlets (observers) subscribe to receive updates. Whenever the news agency publishes a new article, it automatically notifies all the subscribed news outlets. These outlets can then update their platforms (like websites, TV broadcasts, or newspapers) with the latest news. This ensures that all subscribers get the latest information without the news agency needing to know the specifics of each outlet's update process. This decouples the news agency from the subscribers, promoting flexibility and modularity in how updates are handled.

In plain words

> Implement the Observer interface to actively monitor and respond to state changes in Java applications, improving event-driven programming efficiency.

Wikipedia says

> The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Sequence diagram

![Observer sequence diagram](https://java-design-patterns.com/assets/img/observer-sequence-diagram.260c6162.png)

## [Programmatic Example of Observer Pattern in Java](https://java-design-patterns.com/patterns/observer/#programmatic-example-of-observer-pattern-in-java)

In a land far away live the races of hobbits and orcs. Both of them are mostly outdoors, so they closely follow the weather changes. One could say that they are constantly observing the weather.

Let's first introduce the `WeatherObserver` interface and our races, `Orcs` and `Hobbits`.

```java
public interface WeatherObserver {

  void update(WeatherType currentWeather);
}

@Slf4j
public class Orcs implements WeatherObserver {

  @Override
  public void update(WeatherType currentWeather) {
    LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
  }
}

@Slf4j
public class Hobbits implements WeatherObserver {

  @Override
  public void update(WeatherType currentWeather) {
    switch (currentWeather) {
      LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
    }
  }
}
```

Then here's the `Weather` that is constantly changing.

```java
@Slf4j
public class Weather {

  private WeatherType currentWeather;
  private final List<WeatherObserver> observers;

  public Weather() {
    observers = new ArrayList<>();
    currentWeather = WeatherType.SUNNY;
  }

  public void addObserver(WeatherObserver obs) {
    observers.add(obs);
  }

  public void removeObserver(WeatherObserver obs) {
    observers.remove(obs);
  }

  /**
   * Makes time pass for weather.
   */
  public void timePasses() {
    var enumValues = WeatherType.values();
    currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
    LOGGER.info("The weather changed to {}.", currentWeather);
    notifyObservers();
  }

  private void notifyObservers() {
    for (var obs : observers) {
      obs.update(currentWeather);
    }
  }
}
```

Here's the full example in action.

```java
  public static void main(String[] args) {

    var weather = new Weather();
    weather.addObserver(new Orcs());
    weather.addObserver(new Hobbits());

    weather.timePasses();
    weather.timePasses();
    weather.timePasses();
    weather.timePasses();

    // Generic observer inspired by Java Generics and Collections by Naftalin & Wadler
    LOGGER.info("--Running generic version--");
    var genericWeather = new GenWeather();
    genericWeather.addObserver(new GenOrcs());
    genericWeather.addObserver(new GenHobbits());

    genericWeather.timePasses();
    genericWeather.timePasses();
    genericWeather.timePasses();
    genericWeather.timePasses();
  }
```

Program output:

```
21:28:08.310 [main] INFO com.iluwatar.observer.Weather -- The weather changed to rainy.
21:28:08.312 [main] INFO com.iluwatar.observer.Orcs -- The orcs are facing Rainy weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Hobbits -- The hobbits are facing Rainy weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Weather -- The weather changed to windy.
21:28:08.312 [main] INFO com.iluwatar.observer.Orcs -- The orcs are facing Windy weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Hobbits -- The hobbits are facing Windy weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Weather -- The weather changed to cold.
21:28:08.312 [main] INFO com.iluwatar.observer.Orcs -- The orcs are facing Cold weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Hobbits -- The hobbits are facing Cold weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Weather -- The weather changed to sunny.
21:28:08.312 [main] INFO com.iluwatar.observer.Orcs -- The orcs are facing Sunny weather now
21:28:08.312 [main] INFO com.iluwatar.observer.Hobbits -- The hobbits are facing Sunny weather now
21:28:08.312 [main] INFO com.iluwatar.observer.App -- --Running generic version--
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenWeather -- The weather changed to rainy.
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenOrcs -- The orcs are facing Rainy weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenHobbits -- The hobbits are facing Rainy weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenWeather -- The weather changed to windy.
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenOrcs -- The orcs are facing Windy weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenHobbits -- The hobbits are facing Windy weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenWeather -- The weather changed to cold.
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenOrcs -- The orcs are facing Cold weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenHobbits -- The hobbits are facing Cold weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenWeather -- The weather changed to sunny.
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenOrcs -- The orcs are facing Sunny weather now
21:28:08.313 [main] INFO com.iluwatar.observer.generic.GenHobbits -- The hobbits are facing Sunny weather now
```

## [When to Use the Observer Pattern in Java](https://java-design-patterns.com/patterns/observer/#when-to-use-the-observer-pattern-in-java)

Use the Observer pattern in any of the following situations:

- When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
- When a change to one object requires changing others, and you don't know how many objects need to be changed.
- When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.

## [Real-World Applications of Observer Pattern in Java](https://java-design-patterns.com/patterns/observer/#real-world-applications-of-observer-pattern-in-java)

- [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html)
- [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html)
- [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html)
- [RxJava](https://github.com/ReactiveX/RxJava)
- Model-View-Controller (MVC) frameworks.
- Event handling systems.

## [Benefits and Trade-offs of Observer Pattern](https://java-design-patterns.com/patterns/observer/#benefits-and-trade-offs-of-observer-pattern)

Benefits:

- This Java design pattern promotes loose coupling, allowing the subject and its observers to interact without tight dependencies, facilitating easier maintenance and scalability.
- Allows dynamic subscription and unsubscription of observers.

Trade-offs:

- Can lead to memory leaks if observers are not properly deregistered.
- The order of notification is not specified, leading to potential unexpected behavior.
- Potential for performance issues with a large number of observers.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/observer/#related-java-design-patterns)

- [Mediator](https://java-design-patterns.com/patterns/mediator/): Encapsulates how a set of objects interact, which can be used to reduce the direct dependencies among objects.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used with the Observer pattern to ensure a single instance of the subject.

## [References and Credits](https://java-design-patterns.com/patterns/observer/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Generics and Collections](https://amzn.to/3VhOBxp)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [behavioral/partial-response] Partial Response
> 官方文档: https://java-design-patterns.com/patterns/partial-response/

BehavioralAPI designAsynchronousClient-serverDecouplingPerformanceScalabilityWeb developmentAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/partial-response/#also-known-as)

- Incremental Response
- Partial Result

## [Intent of Partial Response Design Pattern](https://java-design-patterns.com/patterns/partial-response/#intent-of-partial-response-design-pattern)

To enable an application to return a partial response to a client, improving perceived performance and enabling the client to start processing parts of the data before the entire response is available.

## [Detailed Explanation of Partial Response Pattern with Real-World Examples](https://java-design-patterns.com/patterns/partial-response/#detailed-explanation-of-partial-response-pattern-with-real-world-examples)

Real-world example

> Imagine a restaurant where a customer orders a multi-course meal. Instead of waiting until all courses are prepared before serving, the restaurant brings out each dish as soon as it's ready. This allows the customer to start enjoying the meal without delay, improves the dining experience, and optimizes the kitchen's workflow by letting them prepare and serve courses incrementally. Similarly, in software, the Partial Response design pattern delivers portions of data as they become available, allowing the client to begin processing immediately and improving overall performance and responsiveness.

In plain words

> The Partial Response design pattern allows a system to send portions of data to the client as they become available, enabling the client to start processing the data before the complete response is received.

Sequence diagram

![Partial Response sequence diagram](https://java-design-patterns.com/assets/img/partial-response-sequence-diagram.1b827648.png)

## [Programmatic Example of Partial Response Pattern in Java](https://java-design-patterns.com/patterns/partial-response/#programmatic-example-of-partial-response-pattern-in-java)

The Partial Response design pattern allows clients to specify which fields of a resource they need. This pattern is useful for reducing the amount of data transferred over the network and allowing clients to start processing data sooner.

The programmatic example shows a simple video streaming application.

`Video` class represents a video object with several fields.

```java
public class Video {
    private String id;
    private String title;
    private String description;
    private String url;

    // Getters and setters...
}
```

`FieldJsonMapper` utility class converts video objects to JSON, including only the requested fields. Method `mapFields` takes a `Video` object and a set of field names. It creates a JSON object including only the specified fields. The `ObjectMapper` from Jackson library is used to build the JSON object.

```java
public class FieldJsonMapper {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static ObjectNode mapFields(Video video, Set<String> fields) {
        ObjectNode node = mapper.createObjectNode();

        if (fields.contains("id")) {
            node.put("id", video.getId());
        }
        if (fields.contains("title")) {
            node.put("title", video.getTitle());
        }
        if (fields.contains("description")) {
            node.put("description", video.getDescription());
        }
        if (fields.contains("url")) {
            node.put("url", video.getUrl());
        }

        return node;
    }
}
```

`VideoResource` class handles HTTP requests and returns only the requested fields of the video data.

- The `VideoResource` class is a RESTful resource handling HTTP GET requests.
- The `getVideo` method fetches a `Video` by its ID and processes the `fields` query parameter.
- It splits the `fields` parameter into a set of field names, uses `FieldJsonMapper` to include only those fields in the response, and returns the partial JSON response.

```java
@Path("/videos")
public class VideoResource {
    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getVideo(@PathParam("id") String id, @QueryParam("fields") String fieldsParam) {
        Video video = findVideoById(id); // Assume this method fetches the video by ID

        Set<String> fields = new HashSet<>(Arrays.asList(fieldsParam.split(",")));
        ObjectNode responseNode = FieldJsonMapper.mapFields(video, fields);

        return Response.ok(responseNode.toString()).build();
    }

    private Video findVideoById(String id) {
        // Dummy data for demonstration purposes
        Video video = new Video();
        video.setId(id);
        video.setTitle("Sample Video");
        video.setDescription("This is a sample video.");
        video.setUrl("http://example.com/sample-video");

        return video;
    }
}
```

`App` class initializes the web server and registers the `VideoResource`.

- The `App` class sets up the server using Jersey.
- It registers the `VideoResource` class, which will handle incoming HTTP requests.
- The server listens on `http://localhost:8080/`.

```java
public class App {
    public static void main(String[] args) {
        ResourceConfig config = new ResourceConfig();
        config.register(VideoResource.class);
        SimpleContainerFactory.create("http://localhost:8080/", config);
    }
}
```

To summarize, in this example:

- The `Video` class defines the video data structure.
- The `FieldJsonMapper` class helps create JSON responses including only the requested fields.
- The `VideoResource` class processes client requests, fetching the necessary video data and returning partial responses based on the specified fields.
- The `App` class configures and starts the web server.

By implementing the Partial Response design pattern, clients can request only the necessary data, enhancing performance and reducing bandwidth usage.

## [When to Use the Partial Response Pattern in Java](https://java-design-patterns.com/patterns/partial-response/#when-to-use-the-partial-response-pattern-in-java)

Use the Partial Response pattern when

- Utilize the Partial Response pattern when dealing with large data sets or APIs that require improved load time and performance.
- When it’s beneficial for the client to begin processing the data as it arrives rather than waiting for the complete response.
- In APIs where different clients might need different subsets of data, allowing them to specify what they need.

## [Real-World Applications of Partial Response Pattern in Java](https://java-design-patterns.com/patterns/partial-response/#real-world-applications-of-partial-response-pattern-in-java)

This pattern is widely adopted in

- RESTful APIs allowing clients to specify fields they want using query parameters.
- Streaming large datasets where initial parts of the data can be sent immediately (e.g., video streaming).
- GraphQL queries where clients can request only specific fields to be returned.

## [Benefits and Trade-offs of Partial Response Pattern](https://java-design-patterns.com/patterns/partial-response/#benefits-and-trade-offs-of-partial-response-pattern)

Benefits:

- Improved Performance: Reduces wait time for the client by allowing it to start processing data as soon as it begins to arrive.
- Resource Optimization: Decreases server load and bandwidth usage by sending only the required data.
- Scalability: Enhances system scalability by handling large datasets more efficiently and reducing the likelihood of timeouts.

Trade-offs:

- Complexity: Increases the complexity of both client and server implementations to handle partial responses properly.
- Error Handling: May complicate error handling and recovery if only parts of the data are received correctly.
- State Management: Requires careful management of state, especially if the partial responses are to be processed incrementally.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/partial-response/#related-java-design-patterns)

- Asynchronous Messaging: Often used together with asynchronous messaging patterns to handle partial responses without blocking the client.
- [Caching](https://java-design-patterns.com/patterns/caching/): Can be combined with caching patterns to store partial responses and avoid redundant data transfers.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): The proxy can intercept requests and manage partial responses, providing a buffer between the client and server.

## [References and Credits](https://java-design-patterns.com/patterns/partial-response/#references-and-credits)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/4dKEwBa)
- [RESTful Web APIs: Services for a Changing World](https://amzn.to/3wG4fu3)

---

## [behavioral/pipeline] Pipeline
> 官方文档: https://java-design-patterns.com/patterns/pipeline/

BehavioralAPI designData processingDecouplingExtensibilityFunctional decompositionScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/pipeline/#also-known-as)

- Chain of Operations
- Processing Pipeline

## [Intent of Pipeline Design Pattern](https://java-design-patterns.com/patterns/pipeline/#intent-of-pipeline-design-pattern)

The Pipeline design pattern in Java is engineered to facilitate data processing across discrete stages, enhancing modular development and operational efficiency.

## [Detailed Explanation of Pipeline Pattern with Real-World Examples](https://java-design-patterns.com/patterns/pipeline/#detailed-explanation-of-pipeline-pattern-with-real-world-examples)

Real-world example

> A practical example of the Java Pipeline design pattern can be seen in assembly lines, such as those in car manufacturing, illustrating its efficiency and scalability.
>
> In this analogy, the car manufacturing process is divided into several discrete stages, each stage handling a specific part of the car assembly. For example:
>
> 1. **Chassis Assembly:** The base frame of the car is assembled.
> 2. **Engine Installation:** The engine is installed onto the chassis.
> 3. **Painting:** The car is painted.
> 4. **Interior Assembly:** The interior, including seats and dashboard, is installed.
> 5. **Quality Control:** The finished car is inspected for defects.
>
> In the Java Pipeline pattern, each stage functions independently and sequentially, ensuring smooth data flow and easy modifications. The output of one stage (e.g., a partially assembled car) becomes the input for the next stage. This modular approach allows for easy maintenance, scalability (e.g., adding more workers to a stage), and flexibility (e.g., replacing a stage with a more advanced version). Just like in a software pipeline, changes in one stage do not affect the others, facilitating continuous improvements and efficient production.

In plain words

> Pipeline pattern is an assembly line where partial results are passed from one stage to another.

Wikipedia says

> In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a physical pipeline.

Flowchart

![Pipeline flowchart](https://java-design-patterns.com/assets/img/pipeline-flowchart.bccaf849.png)

## [Programmatic Example of Pipeline Pattern in Java](https://java-design-patterns.com/patterns/pipeline/#programmatic-example-of-pipeline-pattern-in-java)

Let's create a string processing pipeline example. The stages of our pipeline are called `Handler`s.

```java
interface Handler<I, O> {
    O process(I input);
}
```

In our string processing example we have 3 different concrete `Handler`s.

```java
class RemoveAlphabetsHandler implements Handler<String, String> {
  // ...
}

class RemoveDigitsHandler implements Handler<String, String> {
  // ...
}

class ConvertToCharArrayHandler implements Handler<String, char[]> {
  // ...
}
```

Here is the `Pipeline` that will gather and execute the handlers one by one.

```java
class Pipeline<I, O> {

    private final Handler<I, O> currentHandler;

    Pipeline(Handler<I, O> currentHandler) {
        this.currentHandler = currentHandler;
    }

    <K> Pipeline<I, K> addHandler(Handler<O, K> newHandler) {
        return new Pipeline<>(input -> newHandler.process(currentHandler.process(input)));
    }

    O execute(I input) {
        return currentHandler.process(input);
    }
}
```

And here's the `Pipeline` in action processing the string.

```java
public static void main(String[] args) {
    LOGGER.info("Creating pipeline");
    var filters = new Pipeline<>(new RemoveAlphabetsHandler())
            .addHandler(new RemoveDigitsHandler())
            .addHandler(new ConvertToCharArrayHandler());
    var input = "GoYankees123!";
    LOGGER.info("Executing pipeline with input: {}", input);
    var output = filters.execute(input);
    LOGGER.info("Pipeline output: {}", output);
}
```

Console output:

```
07:34:27.069 [main] INFO com.iluwatar.pipeline.App -- Creating pipeline
07:34:27.072 [main] INFO com.iluwatar.pipeline.App -- Executing pipeline with input: GoYankees123!
07:34:27.074 [main] INFO com.iluwatar.pipeline.RemoveAlphabetsHandler -- Current handler: class com.iluwatar.pipeline.RemoveAlphabetsHandler, input is GoYankees123! of type class java.lang.String, output is 123!, of type class java.lang.String
07:34:27.075 [main] INFO com.iluwatar.pipeline.RemoveDigitsHandler -- Current handler: class com.iluwatar.pipeline.RemoveDigitsHandler, input is 123! of type class java.lang.String, output is !, of type class java.lang.String
07:34:27.075 [main] INFO com.iluwatar.pipeline.ConvertToCharArrayHandler -- Current handler: class com.iluwatar.pipeline.ConvertToCharArrayHandler, input is ! of type class java.lang.String, output is [!], of type class [Ljava.lang.Character;\
07:34:27.075 [main] INFO com.iluwatar.pipeline.App -- Pipeline output: [!]\
```\
\
## [When to Use the Pipeline Pattern in Java](https://java-design-patterns.com/patterns/pipeline/#when-to-use-the-pipeline-pattern-in-java)\
\
Use the Pipeline pattern when you want to\
\
- When you need to process data in a sequence of stages.\
- When each stage of processing is independent and can be easily replaced or reordered.\
- When you want to improve the scalability and maintainability of data processing code.\
\
## [Pipeline Pattern Java Tutorials](https://java-design-patterns.com/patterns/pipeline/#pipeline-pattern-java-tutorials)\
\
- [The Pipeline design pattern (in Java) (Medium)](https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21)\
- [The Pipeline Pattern — for fun and profit (Aaron Weatherall)](https://medium.com/@aaronweatherall/the-pipeline-pattern-for-fun-and-profit-9b5f43a98130)\
- [Pipelines (Microsoft)](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff963548(v=pandp.10))\
\
## [Real-World Applications of Pipeline Pattern in Java](https://java-design-patterns.com/patterns/pipeline/#real-world-applications-of-pipeline-pattern-in-java)\
\
- Data transformation and ETL (Extract, Transform, Load) processes.\
- Compilers for processing source code through various stages such as lexical analysis, syntax analysis, semantic analysis, and code generation.\
- Image processing applications where multiple filters are applied sequentially.\
- Logging frameworks where messages pass through multiple handlers for formatting, filtering, and output.\
\
## [Benefits and Trade-offs of Pipeline Pattern](https://java-design-patterns.com/patterns/pipeline/#benefits-and-trade-offs-of-pipeline-pattern)\
\
Benefits:\
\
- Decoupling: Each stage of the pipeline is a separate component, making the system more modular and easier to maintain.\
- Reusability: Individual stages can be reused in different pipelines.\
- Extensibility: New stages can be added without modifying existing ones.\
- Scalability: Pipelines can be parallelized by running different stages on different processors or threads.\
\
Trade-offs:\
\
- Complexity: Managing the flow of data through multiple stages can introduce complexity.\
- Performance Overhead: Each stage introduces some performance overhead due to context switching and data transfer between stages.\
- Debugging Difficulty: Debugging pipelines can be more challenging since the data flows through multiple components.\
\
## [Related Java Design Patterns](https://java-design-patterns.com/patterns/pipeline/#related-java-design-patterns)\
\
- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Both patterns involve passing data through a series of handlers, but in Chain of Responsibility, handlers can decide not to pass the data further.\
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Both patterns involve adding behavior dynamically, but Decorator wraps additional behavior around objects, whereas Pipeline processes data in discrete steps.\
- [Composite](https://java-design-patterns.com/patterns/composite/): Like Pipeline, Composite also involves hierarchical processing, but Composite is more about part-whole hierarchies.\
\
## [References and Credits](https://java-design-patterns.com/patterns/pipeline/#references-and-credits)\
\
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)\
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)\
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [behavioral/property] Property
> 官方文档: https://java-design-patterns.com/patterns/property/

BehavioralAbstractionEncapsulationInterfaceObject compositionPolymorphismAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/property/#also-known-as)

- Dynamic Properties
- Property Bag

## [Intent of Property Design Pattern](https://java-design-patterns.com/patterns/property/#intent-of-property-design-pattern)

The Property design pattern in Java allows dynamic addition, removal, or modification of object properties, offering a flexible solution for developers to customize object attributes at runtime.

## [Detailed Explanation of Property Pattern with Real-World Examples](https://java-design-patterns.com/patterns/property/#detailed-explanation-of-property-pattern-with-real-world-examples)

Real-world example

> Imagine a custom burger ordering system at a restaurant. Each burger starts with a basic configuration (bun, patty), but customers can add or remove various ingredients (cheese, lettuce, tomato, sauces) as they wish. The restaurant's ordering system uses the Property design pattern to handle this flexibility. Each burger object dynamically updates its list of properties (ingredients) based on customer choices, allowing for a wide variety of custom burgers without needing a fixed class structure for every possible combination. This ensures the system can adapt to any new ingredient without altering the core burger class.

In plain words

> Define and manage a dynamic set of properties for an object, allowing customization without altering its structure.

Sequence diagram

![Property sequence diagram](https://java-design-patterns.com/assets/img/property-sequence-diagram.6145574e.png)

## [Programmatic Example of Property Pattern in Java](https://java-design-patterns.com/patterns/property/#programmatic-example-of-property-pattern-in-java)

The Property design pattern, also known as Prototype inheritance, is a pattern that allows objects to be created from other objects, forming object hierarchies. This pattern is particularly useful when you want to create a new object that is a slight variation of an existing object.

In the given code, the Property pattern is used to create different types of characters, each with their own unique properties.

```java
// The Character class represents a character in a game. It has a type and a set of properties.
public class Character {
  private Type type;
  private Map<Stats, Integer> properties;

  // The Character can be created with a type and a prototype. The new character will have the same properties as the prototype.
  public Character(Type type, Character prototype) {
    this.type = type;
    this.properties = new HashMap<>(prototype.properties);
  }

  // Properties can be added or modified using the set method.
  public void set(Stats stat, int value) {
    properties.put(stat, value);
  }

  // Properties can be removed using the remove method.
  public void remove(Stats stat) {
    properties.remove(stat);
  }

  // The has method checks if a property is present.
  public boolean has(Stats stat) {
    return properties.containsKey(stat);
  }

  // The get method retrieves the value of a property.
  public Integer get(Stats stat) {
    return properties.get(stat);
  }
}

// The Stats enum represents the different properties a character can have.
public enum Stats {
  STRENGTH, AGILITY, ARMOR, ATTACK_POWER, INTELLECT, SPIRIT, RAGE, ENERGY
}

// The Type enum represents the different types of characters.
public enum Type {
  MAGE, WARRIOR, ROGUE
}
```

In the `main` method, we create a prototype character and then create different types of characters based on the prototype:

```java
public static void main(String[] args) {
  // Create a prototype character with default properties
  var charProto = new Character();
  charProto.set(Stats.STRENGTH, 10);
  charProto.set(Stats.AGILITY, 10);
  charProto.set(Stats.ARMOR, 10);
  charProto.set(Stats.ATTACK_POWER, 10);

  // Create a mage character based on the prototype and add mage-specific properties
  var mageProto = new Character(Type.MAGE, charProto);
  mageProto.set(Stats.INTELLECT, 15);
  mageProto.set(Stats.SPIRIT, 10);

  // Create a warrior character based on the prototype and add warrior-specific properties
  var warProto = new Character(Type.WARRIOR, charProto);
  warProto.set(Stats.RAGE, 15);
  warProto.set(Stats.ARMOR, 15); // boost default armor for warrior

  // Create a rogue character based on the prototype and add rogue-specific properties
  var rogueProto = new Character(Type.ROGUE, charProto);
  rogueProto.set(Stats.ENERGY, 15);
  rogueProto.set(Stats.AGILITY, 15); // boost default agility for rogue

  // Create specific characters based on the prototypes
  var mag = new Character("Player_1", mageProto);
  var warrior = new Character("Player_2", warProto);
  var rogue = new Character("Player_3", rogueProto);
}
```

Program output:

```
08:27:52.567 [main] INFO com.iluwatar.property.App -- Player: Player_1
Character type: MAGE
Stats:
  - AGILITY:10
  - STRENGTH:10
  - ATTACK_POWER:10
  - ARMOR:8
  - INTELLECT:15
  - SPIRIT:10

08:27:52.569 [main] INFO com.iluwatar.property.App -- Player: Player_2
Character type: WARRIOR
Stats:
  - AGILITY:10
  - STRENGTH:10
  - ATTACK_POWER:10
  - ARMOR:15
  - RAGE:15

08:27:52.569 [main] INFO com.iluwatar.property.App -- Player: Player_3
Character type: ROGUE
Stats:
  - AGILITY:15
  - STRENGTH:10
  - ATTACK_POWER:10
  - ARMOR:10
  - ENERGY:15

08:27:52.569 [main] INFO com.iluwatar.property.App -- Player: Player_4
Character type: ROGUE
Stats:
  - AGILITY:15
  - STRENGTH:10
  - ATTACK_POWER:12
  - ARMOR:10
  - ENERGY:15
```

This way, we can easily create new characters with different properties without having to create a new class for each type of character.

## [When to Use the Property Pattern in Java](https://java-design-patterns.com/patterns/property/#when-to-use-the-property-pattern-in-java)

Use the Property pattern when

- When you need to manage a flexible set of properties without altering the class structure.
- When properties need to be added or removed dynamically at runtime.
- When different instances of a class need different properties.

## [Real-World Applications of Property Pattern in Java](https://java-design-patterns.com/patterns/property/#real-world-applications-of-property-pattern-in-java)

- Configurations in applications where different entities require different sets of configurable parameters.
- Game development where game entities (like characters or objects) need various attributes that can change during gameplay.
- User profile management systems where user profiles can have dynamic attributes.

## [Benefits and Trade-offs of Property Pattern](https://java-design-patterns.com/patterns/property/#benefits-and-trade-offs-of-property-pattern)

Benefits:

Employing the Property design pattern enhances

- Flexibility: Allows for the dynamic addition, removal, and modification of properties.
- Decoupling: Reduces dependencies between classes and their properties.
- Ease of Use: Simplifies the management of properties in large systems.

Trade-offs:

- Performance Overhead: Dynamic property management can introduce runtime overhead.
- Complexity: May increase the complexity of the code, making it harder to maintain and understand.
- Type Safety: Reduces type safety since properties are often managed as generic key-value pairs.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/property/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Composite allows a tree structure of objects where each node can be a complex or simple object. Property pattern can be seen as a flattened version, managing properties without hierarchy.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Both patterns enhance an object's behavior, but the Property pattern focuses on adding properties dynamically, while the Decorator adds responsibilities.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Like the Property pattern, the Strategy pattern allows dynamic behavior changes, but Strategy is about changing the algorithm used by an object.

## [References and Credits](https://java-design-patterns.com/patterns/property/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)

---

## [behavioral/rate-limiting-pattern] Rate Limiting
> 官方文档: https://java-design-patterns.com/patterns/rate-limiting-pattern/

BehavioralResilienceSystem Overload ProtectionAPI ThrottlingConcurrencyCloud PatternsAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/rate-limiting-pattern/#also-known-as)

- Throttling
- Request Limiting
- API Rate Limiting

* * *

## [Intent of Rate Limiting Design Pattern](https://java-design-patterns.com/patterns/rate-limiting-pattern/#intent-of-rate-limiting-design-pattern)

To regulate the number of requests sent to a service in a specific time window, avoiding resource exhaustion and ensuring system stability. This is especially useful in distributed and cloud-native architectures.

* * *

## [Detailed Explanation of Rate Limiting with Real-World Examples](https://java-design-patterns.com/patterns/rate-limiting-pattern/#detailed-explanation-of-rate-limiting-with-real-world-examples)

### [Real-world example](https://java-design-patterns.com/patterns/rate-limiting-pattern/#real-world-example)

Imagine you're entering a concert hall that only allows 50 people per minute. If too many fans arrive at once, the gate staff slows down entry, allowing only a few at a time. This prevents overcrowding and ensures safety. Similarly, the rate limiter controls how many requests are processed to avoid overloading a server.

### [In plain words](https://java-design-patterns.com/patterns/rate-limiting-pattern/#in-plain-words)

Regulate the number of requests a system handles within a time frame to protect availability and performance.

### [AWS says](https://java-design-patterns.com/patterns/rate-limiting-pattern/#aws-says)

> "API Gateway limits the steady-state rate and burst rate of requests that it allows for each method in your REST APIs. When request rates exceed these limits, API Gateway begins to throttle requests."

— [API Gateway quotas and important notes - AWS Documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html)

* * *

## [Architecture Diagram](https://java-design-patterns.com/patterns/rate-limiting-pattern/#architecture-diagram)

![UML Class Diagram](https://java-design-patterns.com/assets/img/UMLClassDiagram.6b225226.png)

This UML shows the key components:

- `RateLimiter` interface
- `TokenBucketRateLimiter`, `FixedWindowRateLimiter`, `AdaptiveRateLimiter`
- Supporting exception classes
- `FindCustomerRequest` as a rate-limited operation

* * *

## [Flowcharts](https://java-design-patterns.com/patterns/rate-limiting-pattern/#flowcharts)

### [1\. Token Bucket Strategy](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_1-token-bucket-strategy)

![Token Bucket Rate Limiter](https://java-design-patterns.com/assets/img/TokenBucketRateLimiter.9465a777.png)

### [2\. Fixed Window Strategy](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_2-fixed-window-strategy)

![Fixed Window Rate Limiter](https://java-design-patterns.com/assets/img/FixedWindowRateLimiter.8f8cf4ae.png)

### [3\. Adaptive Rate Limiting Strategy](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_3-adaptive-rate-limiting-strategy)

![Adaptive Rate Limiter](https://java-design-patterns.com/assets/img/AdaptiveRateLimiter.623bdcbd.png)

* * *

### [Programmatic Example of Rate Limiter Pattern in Java](https://java-design-patterns.com/patterns/rate-limiting-pattern/#programmatic-example-of-rate-limiter-pattern-in-java)

The **Rate Limiter** design pattern helps protect systems from overload by restricting the number of operations that can be performed in a given time window. It is especially useful when accessing shared resources, APIs, or services that are sensitive to spikes in traffic.

This implementation demonstrates three strategies for rate limiting:

- **Token Bucket Rate Limiter**
- **Fixed Window Rate Limiter**
- **Adaptive Rate Limiter**

Let’s walk through the key components.

* * *

#### [1\. Token Bucket Rate Limiter](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_1-token-bucket-rate-limiter)

The token bucket allows short bursts followed by a steady rate. Tokens are added periodically and requests are only allowed if a token is available.

```java
public class TokenBucketRateLimiter implements RateLimiter {
  private final int capacity;
  private final int refillRate;
  private final ConcurrentHashMap<String, TokenBucket> buckets = new ConcurrentHashMap<>();
  private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

  public TokenBucketRateLimiter(int capacity, int refillRate) {
    this.capacity = capacity;
    this.refillRate = refillRate;
    scheduler.scheduleAtFixedRate(this::refillBuckets, 1, 1, TimeUnit.SECONDS);
  }

  @Override
  public void check(String serviceName, String operationName) throws RateLimitException {
    String key = serviceName + ":" + operationName;
    TokenBucket bucket = buckets.computeIfAbsent(key, k -> new TokenBucket(capacity));
    if (!bucket.tryConsume()) {
      throw new ThrottlingException(serviceName, operationName, 1000);
    }
  }

  private void refillBuckets() {
    buckets.forEach((k, b) -> b.refill(refillRate));
  }

  private static class TokenBucket {
    private final int capacity;
    private final AtomicInteger tokens;

    TokenBucket(int capacity) {
      this.capacity = capacity;
      this.tokens = new AtomicInteger(capacity);
    }

    boolean tryConsume() {
      while (true) {
        int current = tokens.get();
        if (current <= 0) return false;
        if (tokens.compareAndSet(current, current - 1)) return true;
      }
    }

    void refill(int amount) {
      tokens.getAndUpdate(current -> Math.min(current + amount, capacity));
    }
  }
}
```

* * *

#### [2\. Fixed Window Rate Limiter](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_2-fixed-window-rate-limiter)

This strategy uses a simple counter within a fixed time window.

```java
public class FixedWindowRateLimiter implements RateLimiter {
  private final int limit;
  private final long windowMillis;
  private final ConcurrentHashMap<String, WindowCounter> counters = new ConcurrentHashMap<>();

  public FixedWindowRateLimiter(int limit, long windowSeconds) {
    this.limit = limit;
    this.windowMillis = TimeUnit.SECONDS.toMillis(windowSeconds);
  }

  @Override
  public synchronized void check(String serviceName, String operationName) throws RateLimitException {
    String key = serviceName + ":" + operationName;
    WindowCounter counter = counters.computeIfAbsent(key, k -> new WindowCounter());

    if (!counter.tryIncrement()) {
      throw new RateLimitException("Rate limit exceeded for " + key, windowMillis);
    }
  }

  private class WindowCounter {
    private AtomicInteger count = new AtomicInteger(0);
    private volatile long windowStart = System.currentTimeMillis();

    synchronized boolean tryIncrement() {
      long now = System.currentTimeMillis();
      if (now - windowStart > windowMillis) {
        count.set(0);
        windowStart = now;
      }
      return count.incrementAndGet() <= limit;
    }
  }
}
```

* * *

#### [3\. Adaptive Rate Limiter](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_3-adaptive-rate-limiter)

This version adjusts the rate based on system health, reducing the rate when throttling occurs and recovering periodically.

```java
public class AdaptiveRateLimiter implements RateLimiter {
  private final int initialLimit;
  private final int maxLimit;
  private final AtomicInteger currentLimit;
  private final ConcurrentHashMap<String, RateLimiter> limiters = new ConcurrentHashMap<>();
  private final ScheduledExecutorService healthChecker = Executors.newScheduledThreadPool(1);

  public AdaptiveRateLimiter(int initialLimit, int maxLimit) {
    this.initialLimit = initialLimit;
    this.maxLimit = maxLimit;
    this.currentLimit = new AtomicInteger(initialLimit);
    healthChecker.scheduleAtFixedRate(this::adjustLimits, 10, 10, TimeUnit.SECONDS);
  }

  @Override
  public void check(String serviceName, String operationName) throws RateLimitException {
    String key = serviceName + ":" + operationName;
    int current = currentLimit.get();
    RateLimiter limiter = limiters.computeIfAbsent(key, k -> new TokenBucketRateLimiter(current, current));

    try {
      limiter.check(serviceName, operationName);
    } catch (RateLimitException e) {
      currentLimit.updateAndGet(curr -> Math.max(initialLimit, curr / 2));
      throw e;
    }
  }

  private void adjustLimits() {
    currentLimit.updateAndGet(curr -> Math.min(maxLimit, curr + (initialLimit / 2)));
  }
}
```

* * *

#### [4\. Simulated Demo Using All Limiters](https://java-design-patterns.com/patterns/rate-limiting-pattern/#_4-simulated-demo-using-all-limiters)

```java
public final class App {
  public static void main(String[] args) {
    TokenBucketRateLimiter tb = new TokenBucketRateLimiter(2, 1);
    FixedWindowRateLimiter fw = new FixedWindowRateLimiter(3, 1);
    AdaptiveRateLimiter ar = new AdaptiveRateLimiter(2, 6);

    ExecutorService executor = Executors.newFixedThreadPool(3);
    for (int i = 1; i <= 3; i++) {
      executor.submit(createClientTask(i, tb, fw, ar));
    }
  }

  private static Runnable createClientTask(int clientId, RateLimiter tb, RateLimiter fw, RateLimiter ar) {
    return () -> {
      String[] services = {"s3", "dynamodb", "lambda"};
      String[] operations = {"GetObject", "PutObject", "Query", "Scan", "PutItem", "Invoke", "ListFunctions"};
      Random random = new Random();

      while (true) {
        String service = services[random.nextInt(services.length)];
        String operation = operations[random.nextInt(operations.length)];
        try {
          switch (service) {
            case "s3" -> tb.check(service, operation);
            case "dynamodb" -> fw.check(service, operation);
            case "lambda" -> ar.check(service, operation);
          }
          System.out.printf("Client %d: %s.%s - ALLOWED%n", clientId, service, operation);
        } catch (RateLimitException e) {
          System.out.printf("Client %d: %s.%s - THROTTLED%n", clientId, service, operation);
        }

        try {
          Thread.sleep(30 + random.nextInt(50));
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
    };
  }
}
```

* * *

This example highlights how the Rate Limiter pattern supports various throttling techniques and how they respond under simulated traffic pressure, making it invaluable for building scalable, resilient systems.

## [When to Use Rate Limiting](https://java-design-patterns.com/patterns/rate-limiting-pattern/#when-to-use-rate-limiting)

- APIs receiving unpredictable traffic
- Shared cloud resources (e.g., DB, compute)
- Services requiring fair client usage
- Preventing DoS or abuse

* * *

## [Real-World Applications](https://java-design-patterns.com/patterns/rate-limiting-pattern/#real-world-applications)

- **AWS API Gateway**
- **Google Cloud Functions**
- **Netflix Zuul API Gateway**
- **Stripe API Throttling**

* * *

## [Benefits and Trade-offs](https://java-design-patterns.com/patterns/rate-limiting-pattern/#benefits-and-trade-offs)

### [Benefits](https://java-design-patterns.com/patterns/rate-limiting-pattern/#benefits)

- Protects backend from overload
- Fair distribution of resources
- Better user experience under load

### [Trade-offs](https://java-design-patterns.com/patterns/rate-limiting-pattern/#trade-offs)

- May delay valid requests
- Requires tuning of limits
- Could create bottlenecks if misused

* * *

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/rate-limiting-pattern/#related-java-design-patterns)

- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/)
- [Retry](https://java-design-patterns.com/patterns/retry/)
- [Throttling Queue](https://java-design-patterns.com/patterns/throttling/)

* * *

## [References and Credits](https://java-design-patterns.com/patterns/rate-limiting-pattern/#references-and-credits)

- [Microsoft Cloud Design Patterns](https://learn.microsoft.com/en-us/azure/architecture/patterns/throttling)
- [AWS API Gateway Throttling](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html)
- _Designing Data-Intensive Applications_ by Martin Kleppmann
- [Resilience4j](https://resilience4j.readme.io/)
- Java Design Patterns Project: [java-design-patterns](https://github.com/iluwatar/java-design-patterns)

---

## [behavioral/specification] Specification
> 官方文档: https://java-design-patterns.com/patterns/specification/

BehavioralBusinessDomainEncapsulationEnterprise patternsExtensibilityAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/specification/#also-known-as)

- Filter
- Criteria

## [Intent of Specification Design Pattern](https://java-design-patterns.com/patterns/specification/#intent-of-specification-design-pattern)

Encapsulate business rules and criteria that an object must satisfy to enable checking these rules in various parts of the application.

## [Detailed Explanation of Specification Pattern with Real-World Examples](https://java-design-patterns.com/patterns/specification/#detailed-explanation-of-specification-pattern-with-real-world-examples)

Real-world example

> Imagine you are organizing a conference and need to filter attendees based on specific criteria such as registration status, payment completion, and session interests.
>
> Using the Specification design pattern, you would create separate specifications for each criterion (e.g., "IsRegistered", "HasPaid", "IsInterestedInSessionX"). These specifications can be combined dynamically to filter attendees who meet all the required criteria, such as those who are registered, have completed their payment, and are interested in a particular session. This approach allows for flexible and reusable business rules, ensuring that the filtering logic can be easily adjusted as needed without changing the underlying attendee objects.

In plain words

> The Specification design pattern in Java enables the efficient encapsulation and reuse of business rules, offering a flexible and dynamic way to combine criteria for robust software development

Wikipedia says

> In computer programming, the specification pattern is a particular software design pattern, whereby business rules can be recombined by chaining the business rules together using boolean logic.

Flowchart

![Specification Pattern flowchart](https://java-design-patterns.com/assets/img/specification-flowchart.db05b17f.png)

## [Programmatic Example of Specification Pattern in Java](https://java-design-patterns.com/patterns/specification/#programmatic-example-of-specification-pattern-in-java)

Let's consider a creature pool example. We have a collection of creatures with specific properties. These properties might belong to a predefined, limited set (represented by enums like `Size`, `Movement`, and `Color`) or they might be continuous values (e.g., the mass of a `Creature`). In cases with continuous values, it's better to use a "parameterized specification," where the property value is provided as an argument when the `Creature` is instantiated, allowing for greater flexibility. Additionally, predefined and/or parameterized properties can be combined using boolean logic, offering almost limitless selection possibilities (this is known as a "composite specification," explained further below). The advantages and disadvantages of each approach are detailed in the table at the end of this document.

First, here is interface `Creature`.

```java
public interface Creature {
    String getName();

    Size getSize();

    Movement getMovement();

    Color getColor();

    Mass getMass();
}
```

And `Dragon` implementation looks like this.

```java
public class Dragon extends AbstractCreature {

  public Dragon() {
    super("Dragon", Size.LARGE, Movement.FLYING, Color.RED, new Mass(39300.0));
  }
}
```

Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use `MovementSelector`. The snippet also shows the base class `AbstractSelector`.

```java
public abstract class AbstractSelector<T> implements Predicate<T> {

    public AbstractSelector<T> and(AbstractSelector<T> other) {
        return new ConjunctionSelector<>(this, other);
    }

    public AbstractSelector<T> or(AbstractSelector<T> other) {
        return new DisjunctionSelector<>(this, other);
    }

    public AbstractSelector<T> not() {
        return new NegationSelector<>(this);
    }
}
```

```java
public class MovementSelector extends AbstractSelector<Creature> {

  private final Movement movement;

  public MovementSelector(Movement m) {
    this.movement = m;
  }

  @Override
  public boolean test(Creature t) {
    return t.getMovement().equals(movement);
  }
}
```

On the other hand, when selecting creatures heavier than a chosen amount, we use `MassGreaterThanSelector`.

```java
public class MassGreaterThanSelector extends AbstractSelector<Creature> {

  private final Mass mass;

  public MassGreaterThanSelector(double mass) {
    this.mass = new Mass(mass);
  }

  @Override
  public boolean test(Creature t) {
    return t.getMass().greaterThan(mass);
  }
}
```

With these building blocks in place, we can perform some searches.

```java
@Slf4j
public class App {

  public static void main(String[] args) {
    // initialize creatures list
    var creatures = List.of(
        new Goblin(),
        new Octopus(),
        new Dragon(),
        new Shark(),
        new Troll(),
        new KillerBee()
    );
    // so-called "hard-coded" specification
    LOGGER.info("Demonstrating hard-coded specification :");
    // find all walking creatures
    LOGGER.info("Find all walking creatures");
    print(creatures, new MovementSelector(Movement.WALKING));
    // find all dark creatures
    LOGGER.info("Find all dark creatures");
    print(creatures, new ColorSelector(Color.DARK));
    LOGGER.info("\n");
    // so-called "parameterized" specification
    LOGGER.info("Demonstrating parameterized specification :");
    // find all creatures heavier than 500kg
    LOGGER.info("Find all creatures heavier than 600kg");
    print(creatures, new MassGreaterThanSelector(600.0));
    // find all creatures heavier than 500kg
    LOGGER.info("Find all creatures lighter than or weighing exactly 500kg");
    print(creatures, new MassSmallerThanOrEqSelector(500.0));
    LOGGER.info("\n");
    // so-called "composite" specification
    LOGGER.info("Demonstrating composite specification :");
    // find all red and flying creatures
    LOGGER.info("Find all red and flying creatures");
    var redAndFlying = new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING));
    print(creatures, redAndFlying);
    // find all creatures dark or red, non-swimming, and heavier than or equal to 400kg
    LOGGER.info("Find all scary creatures");
    var scaryCreaturesSelector = new ColorSelector(Color.DARK)
        .or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not())
        .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0)));
    print(creatures, scaryCreaturesSelector);
  }

  private static void print(List<? extends Creature> creatures, Predicate<Creature> selector) {
    creatures.stream().filter(selector).map(Objects::toString).forEach(LOGGER::info);
  }
}
```

Console output:

```
12:49:24.808 [main] INFO com.iluwatar.specification.app.App -- Demonstrating hard-coded specification :
12:49:24.810 [main] INFO com.iluwatar.specification.app.App -- Find all walking creatures
12:49:24.812 [main] INFO com.iluwatar.specification.app.App -- Goblin [size=small, movement=walking, color=green, mass=30.0kg]
12:49:24.812 [main] INFO com.iluwatar.specification.app.App -- Troll [size=large, movement=walking, color=dark, mass=4000.0kg]
12:49:24.812 [main] INFO com.iluwatar.specification.app.App -- Find all dark creatures
12:49:24.815 [main] INFO com.iluwatar.specification.app.App -- Octopus [size=normal, movement=swimming, color=dark, mass=12.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Troll [size=large, movement=walking, color=dark, mass=4000.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App --

12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Demonstrating parameterized specification :
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Find all creatures heavier than 600kg
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Dragon [size=large, movement=flying, color=red, mass=39300.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Troll [size=large, movement=walking, color=dark, mass=4000.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Find all creatures lighter than or weighing exactly 500kg
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Goblin [size=small, movement=walking, color=green, mass=30.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Octopus [size=normal, movement=swimming, color=dark, mass=12.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Shark [size=normal, movement=swimming, color=light, mass=500.0kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- KillerBee [size=small, movement=flying, color=light, mass=6.7kg]
12:49:24.816 [main] INFO com.iluwatar.specification.app.App --

12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Demonstrating composite specification :
12:49:24.816 [main] INFO com.iluwatar.specification.app.App -- Find all red and flying creatures
12:49:24.817 [main] INFO com.iluwatar.specification.app.App -- Dragon [size=large, movement=flying, color=red, mass=39300.0kg]
12:49:24.817 [main] INFO com.iluwatar.specification.app.App -- Find all scary creatures
12:49:24.818 [main] INFO com.iluwatar.specification.app.App -- Dragon [size=large, movement=flying, color=red, mass=39300.0kg]
12:49:24.818 [main] INFO com.iluwatar.specification.app.App -- Troll [size=large, movement=walking, color=dark, mass=4000.0kg]
```

Adopting the Specification pattern significantly enhances the flexibility and reusability of business rules within Java applications, contributing to more maintainable code.

## [When to Use the Specification Pattern in Java](https://java-design-patterns.com/patterns/specification/#when-to-use-the-specification-pattern-in-java)

Apply the Java Specification pattern when

- You need to filter objects based on different criteria.
- The filtering criteria can change dynamically.
- Ideal for use cases involving complex business rules that must be reused across different parts of an application.

## [Real-World Applications of Specification Pattern in Java](https://java-design-patterns.com/patterns/specification/#real-world-applications-of-specification-pattern-in-java)

- Validating user inputs in enterprise applications.
- Filtering search results in e-commerce applications.
- Business rule validation in domain-driven design (DDD).

## [Benefits and Trade-offs of Specification Pattern](https://java-design-patterns.com/patterns/specification/#benefits-and-trade-offs-of-specification-pattern)

Benefits:

- Enhances the flexibility and reusability of business rules.
- Promotes [single responsibility principle](https://java-design-patterns.com/principles/#single-responsibility-principle) by separating business rules from the entities.
- Facilitates unit testing of business rules.

Trade-offs:

- Can lead to a proliferation of small classes, increasing complexity.
- Might introduce performance overhead due to the dynamic checking of specifications.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/specification/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): Often used together with Specification to combine multiple specifications.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add additional criteria to a specification dynamically.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns involve encapsulating a family of algorithms. Strategy encapsulates different strategies or algorithms, while Specification encapsulates business rules.

## [References and Credits](https://java-design-patterns.com/patterns/specification/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Specifications (Martin Fowler)](http://martinfowler.com/apsupp/spec.pdf)

---

## [behavioral/state] State 状态
> 官方文档: https://java-design-patterns.com/patterns/state/

BehavioralDecouplingGang of FourState trackingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/state/#also-known-as)

- Objects for States

## [Intent of State Design Pattern](https://java-design-patterns.com/patterns/state/#intent-of-state-design-pattern)

Enable an object to alter its behavior dynamically as its internal state changes, optimizing Java application responsiveness.

## [Detailed Explanation of State Pattern with Real-World Examples](https://java-design-patterns.com/patterns/state/#detailed-explanation-of-state-pattern-with-real-world-examples)

Real-world example

> Imagine a traffic light system at an intersection. The traffic light can be in one of three states: Green, Yellow, or Red. Depending on the current state, the traffic light's behavior changes:
>
> 1. **Green State**: Cars are allowed to pass through the intersection.
> 2. **Yellow State**: Cars are warned that the light will soon turn red, so they should prepare to stop.
> 3. **Red State**: Cars must stop and wait for the light to turn green.
>
> In this scenario, the traffic light uses the State design pattern. Each state (Green, Yellow, Red) is represented by a different object that defines what happens in that particular state. The traffic light (context) delegates the behavior to the current state object. When the state changes (e.g., from Green to Yellow), the traffic light updates its state object and changes its behavior accordingly.

In plain words

> State pattern allows an object to change its behavior.

Wikipedia says

> The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.

Flowchart

![State flowchart](https://java-design-patterns.com/assets/img/state-flowchart.099ecdf6.png)

## [Programmatic Example of State Pattern in Java](https://java-design-patterns.com/patterns/state/#programmatic-example-of-state-pattern-in-java)

In our programmatic example there is a mammoth with alternating moods.

First, here is the state interface and its concrete implementations.

```java
public interface State {

  void onEnterState();

  void observe();
}
```

```java
@Slf4j
public class PeacefulState implements State {

  private final Mammoth mammoth;

  public PeacefulState(Mammoth mammoth) {
    this.mammoth = mammoth;
  }

  @Override
  public void observe() {
    LOGGER.info("{} is calm and peaceful.", mammoth);
  }

  @Override
  public void onEnterState() {
    LOGGER.info("{} calms down.", mammoth);
  }
}
```

```java
@Slf4j
public class AngryState implements State {

  private final Mammoth mammoth;

  public AngryState(Mammoth mammoth) {
    this.mammoth = mammoth;
  }

  @Override
  public void observe() {
    LOGGER.info("{} is furious!", mammoth);
  }

  @Override
  public void onEnterState() {
    LOGGER.info("{} gets angry!", mammoth);
  }
}
```

And here is the mammoth containing the state. The state changes via calls to `timePasses` method.

```java
public class Mammoth {

  private State state;

  public Mammoth() {
    state = new PeacefulState(this);
  }

  public void timePasses() {
    if (state.getClass().equals(PeacefulState.class)) {
      changeStateTo(new AngryState(this));
    } else {
      changeStateTo(new PeacefulState(this));
    }
  }

  private void changeStateTo(State newState) {
    this.state = newState;
    this.state.onEnterState();
  }

  @Override
  public String toString() {
    return "The mammoth";
  }

  public void observe() {
    this.state.observe();
  }
}
```

Here is the full example of how the mammoth behaves over time.

```java
public static void main(String[] args) {

    var mammoth = new Mammoth();
    mammoth.observe();
    mammoth.timePasses();
    mammoth.observe();
    mammoth.timePasses();
    mammoth.observe();
}
```

Program output:

```java
    The mammoth gets angry!
    The mammoth is furious!
    The mammoth calms down.
    The mammoth is calm and peaceful.
```

## [When to Use the State Pattern in Java](https://java-design-patterns.com/patterns/state/#when-to-use-the-state-pattern-in-java)

- An object's behavior depends on its state, and it must change its behavior at runtime depending on that state.
- Operations have large, multipart conditional statements that depend on the object's state.

## [Real-World Applications of State Pattern in Java](https://java-design-patterns.com/patterns/state/#real-world-applications-of-state-pattern-in-java)

- `java.util.Iterator` in Java's Collections Framework uses different states for iteration.
- TCP connection classes in network programming often implement states like `Established`, `Listen`, and `Closed`.

## [Benefits and Trade-offs of State Pattern](https://java-design-patterns.com/patterns/state/#benefits-and-trade-offs-of-state-pattern)

Benefits:

- Localizes state-specific behavior and partitions behavior for different states.
- Makes state transitions explicit.
- Reusable State objects can be efficiently shared among various contexts in Java, enhancing memory management and performance.

Trade-offs:

- Can result in a large number of classes for states.
- Context class can become complicated with the state transition logic.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/state/#related-java-design-patterns)

- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): State objects may be shared between different contexts.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): State objects are often singletons.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Both patterns have similar structures, but the State pattern's implementations depend on the context’s state.

## [References and Credits](https://java-design-patterns.com/patterns/state/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [behavioral/strategy] Strategy 策略
> 官方文档: https://java-design-patterns.com/patterns/strategy/

BehavioralDecouplingExtensibilityGang of FourInterfacePolymorphismAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/strategy/#also-known-as)

- Policy

## [Intent of Strategy Design Pattern](https://java-design-patterns.com/patterns/strategy/#intent-of-strategy-design-pattern)

Define a family of algorithms in Java, encapsulate each one, and make them interchangeable to enhance software development using the Strategy design pattern. Strategy lets the algorithm vary independently of the clients that use it.

## [Detailed Explanation of Strategy Pattern with Real-World Examples](https://java-design-patterns.com/patterns/strategy/#detailed-explanation-of-strategy-pattern-with-real-world-examples)

Real-world example

> A practical real-world example of the Strategy design pattern in Java is evident in car navigation systems, where algorithm flexibility is paramount. Different navigation algorithms (such as shortest route, fastest route, and scenic route) can be used to determine the best path from one location to another. Each algorithm encapsulates a specific strategy for calculating the route. The user (client) can switch between these algorithms based on their preferences without changing the navigation system itself. This allows for flexible and interchangeable navigation strategies within the same system.

In plain words

> Strategy pattern allows choosing the best-suited algorithm at runtime.

Wikipedia says

> In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime.

Flowchart

![Strategy flowchart](https://java-design-patterns.com/assets/img/strategy-flowchart.e9ac7d35.png)

## [Programmatic Example of Strategy Pattern in Java](https://java-design-patterns.com/patterns/strategy/#programmatic-example-of-strategy-pattern-in-java)

Slaying dragons is a dangerous job. With experience, it becomes easier. Veteran dragonslayers have developed different fighting strategies against different types of dragons.

Let's explore how to implement the `DragonSlayingStrategy` interface in Java, demonstrating various Strategy pattern applications.

```java
@FunctionalInterface
public interface DragonSlayingStrategy {

  void execute();
}
```

```java
@Slf4j
public class MeleeStrategy implements DragonSlayingStrategy {

  @Override
  public void execute() {
    LOGGER.info("With your Excalibur you sever the dragon's head!");
  }
}
```

```java
@Slf4j
public class ProjectileStrategy implements DragonSlayingStrategy {

  @Override
  public void execute() {
    LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
  }
}
```

```java
@Slf4j
public class SpellStrategy implements DragonSlayingStrategy {

  @Override
  public void execute() {
    LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
  }
}
```

And here is the mighty `DragonSlayer`, who can pick his fighting strategy based on the opponent.

```java
public class DragonSlayer {

  private DragonSlayingStrategy strategy;

  public DragonSlayer(DragonSlayingStrategy strategy) {
    this.strategy = strategy;
  }

  public void changeStrategy(DragonSlayingStrategy strategy) {
    this.strategy = strategy;
  }

  public void goToBattle() {
    strategy.execute();
  }
}
```

Finally, here's the `DragonSlayer` in action.

```java
@Slf4j
public class App {

  private static final String RED_DRAGON_EMERGES = "Red dragon emerges.";
  private static final String GREEN_DRAGON_SPOTTED = "Green dragon spotted ahead!";
  private static final String BLACK_DRAGON_LANDS = "Black dragon lands before you.";

  public static void main(String[] args) {
    // GoF Strategy pattern
    LOGGER.info(GREEN_DRAGON_SPOTTED);
    var dragonSlayer = new DragonSlayer(new MeleeStrategy());
    dragonSlayer.goToBattle();
    LOGGER.info(RED_DRAGON_EMERGES);
    dragonSlayer.changeStrategy(new ProjectileStrategy());
    dragonSlayer.goToBattle();
    LOGGER.info(BLACK_DRAGON_LANDS);
    dragonSlayer.changeStrategy(new SpellStrategy());
    dragonSlayer.goToBattle();

    // Java 8 functional implementation Strategy pattern
    LOGGER.info(GREEN_DRAGON_SPOTTED);
    dragonSlayer = new DragonSlayer(
        () -> LOGGER.info("With your Excalibur you sever the dragon's head!"));
    dragonSlayer.goToBattle();
    LOGGER.info(RED_DRAGON_EMERGES);
    dragonSlayer.changeStrategy(() -> LOGGER.info(
        "You shoot the dragon with the magical crossbow and it falls dead on the ground!"));
    dragonSlayer.goToBattle();
    LOGGER.info(BLACK_DRAGON_LANDS);
    dragonSlayer.changeStrategy(() -> LOGGER.info(
        "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
    dragonSlayer.goToBattle();

    // Java 8 lambda implementation with enum Strategy pattern
    LOGGER.info(GREEN_DRAGON_SPOTTED);
    dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MELEE_STRATEGY);
    dragonSlayer.goToBattle();
    LOGGER.info(RED_DRAGON_EMERGES);
    dragonSlayer.changeStrategy(LambdaStrategy.Strategy.PROJECTILE_STRATEGY);
    dragonSlayer.goToBattle();
    LOGGER.info(BLACK_DRAGON_LANDS);
    dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SPELL_STRATEGY);
    dragonSlayer.goToBattle();
  }
}
```

Program output:

```
13:06:36.631 [main] INFO com.iluwatar.strategy.App -- Green dragon spotted ahead!
13:06:36.634 [main] INFO com.iluwatar.strategy.MeleeStrategy -- With your Excalibur you sever the dragon's head!
13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Red dragon emerges.
13:06:36.634 [main] INFO com.iluwatar.strategy.ProjectileStrategy -- You shoot the dragon with the magical crossbow and it falls dead on the ground!
13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Black dragon lands before you.
13:06:36.634 [main] INFO com.iluwatar.strategy.SpellStrategy -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Green dragon spotted ahead!
13:06:36.634 [main] INFO com.iluwatar.strategy.App -- With your Excalibur you sever the dragon's head!
13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Red dragon emerges.
13:06:36.635 [main] INFO com.iluwatar.strategy.App -- You shoot the dragon with the magical crossbow and it falls dead on the ground!
13:06:36.635 [main] INFO com.iluwatar.strategy.App -- Black dragon lands before you.
13:06:36.635 [main] INFO com.iluwatar.strategy.App -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
13:06:36.635 [main] INFO com.iluwatar.strategy.App -- Green dragon spotted ahead!
13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- With your Excalibur you sever the dragon's head!
13:06:36.637 [main] INFO com.iluwatar.strategy.App -- Red dragon emerges.
13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- You shoot the dragon with the magical crossbow and it falls dead on the ground!
13:06:36.637 [main] INFO com.iluwatar.strategy.App -- Black dragon lands before you.
13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
```

## [When to Use the Strategy Pattern in Java](https://java-design-patterns.com/patterns/strategy/#when-to-use-the-strategy-pattern-in-java)

Use the Strategy pattern when:

- You need to use different variants of an algorithm within an object and want to switch algorithms at runtime.
- There are multiple related classes that differ only in their behavior.
- An algorithm uses data that clients shouldn't know about.
- A class defines many behaviors and these appear as multiple conditional statements in its operations.

## [Strategy Pattern Java Tutorials](https://java-design-patterns.com/patterns/strategy/#strategy-pattern-java-tutorials)

- [Strategy Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/strategy-design-pattern-in-java-example-tutorial)

## [Real-World Applications of Strategy Pattern in Java](https://java-design-patterns.com/patterns/strategy/#real-world-applications-of-strategy-pattern-in-java)

- Java's `java.util.Comparator` interface is a common example of the Strategy pattern.
- In GUI frameworks, layout managers (such as those in Java's AWT and Swing) are strategies.

## [Benefits and Trade-offs of Strategy Pattern](https://java-design-patterns.com/patterns/strategy/#benefits-and-trade-offs-of-strategy-pattern)

Benefits:

- Families of related algorithms are reused.
- An alternative to subclassing for extending behavior.
- Avoids conditional statements for selecting desired behavior.
- Allows clients to choose algorithm implementation.

Trade-offs:

- Clients must be aware of different Strategies.
- Increase in the number of objects.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/strategy/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): Enhances an object without changing its interface but is more concerned with responsibilities than algorithms.
- [State](https://java-design-patterns.com/patterns/state/): Similar in structure but used to represent state-dependent behavior rather than interchangeable algorithms.

## [References and Credits](https://java-design-patterns.com/patterns/strategy/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Functional Programming in Java](https://amzn.to/3JUIc5Q)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [behavioral/subclass-sandbox] Subclass Sandbox
> 官方文档: https://java-design-patterns.com/patterns/subclass-sandbox/

BehavioralAbstractionCode simplificationDecouplingExtensibilityGame programmingPolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/subclass-sandbox/#also-known-as)

- Hook Method

## [Intent of Subclass Sandbox Design Pattern](https://java-design-patterns.com/patterns/subclass-sandbox/#intent-of-subclass-sandbox-design-pattern)

The Subclass Sandbox design pattern in Java allows subclasses to alter the core behavior of a class by providing specific implementations of certain methods while keeping the overall structure unchanged.

## [Detailed Explanation of Subclass Sandbox Pattern with Real-World Examples](https://java-design-patterns.com/patterns/subclass-sandbox/#detailed-explanation-of-subclass-sandbox-pattern-with-real-world-examples)

Real-world example

> Imagine a cooking class where the instructor provides a standard recipe structure, including steps like "prepare ingredients," "cook," and "serve." Each student follows this structure but can customize specific steps to create their unique dish. For example, one student might choose to prepare a salad, while another might prepare a stir-fry, both adhering to the same overarching recipe format. This way, the instructor ensures that all dishes are made following a consistent process, but students have the flexibility to personalize the key parts of their recipes. This mirrors the Subclass Sandbox pattern, where the core structure is defined by the superclass, and specific behaviors are customized in subclasses.

In plain words

> The Subclass Sandbox pattern allows subclasses to customize specific behaviors within a predefined algorithm structure provided by the superclass.

[gameprogrammingpatterns.com](https://gameprogrammingpatterns.com/) says

> A base class defines an abstract sandbox method and several provided operations. Marking them protected makes it clear that they are for use by derived classes. Each derived sandboxed subclass implements the sandbox method using the provided operations.

Flowchart

![Subclass Sandbox flowchart](https://java-design-patterns.com/assets/img/subclass-sandbox-flowchart.3e77c3c2.png)

## [Programmatic Example of Subclass Sandbox Pattern in Java](https://java-design-patterns.com/patterns/subclass-sandbox/#programmatic-example-of-subclass-sandbox-pattern-in-java)

Using the Subclass Sandbox pattern, developers can create distinct functionalities within Java applications, enhancing game development and software design.

Suppose you want to create various superpowers in a game, where each superpower needs to move with a sound effect and spawn particles. Should you create many classes with similar methods or derive them from a base class? The Subclass Sandbox pattern enables you to handle this efficiently by deriving these classes from a common base class.

We start with the base class `Superpower`. It contains an abstract sandbox method `active` and some provided operations.

```java
public abstract class Superpower {

  protected Logger logger;

  protected abstract void activate();

  protected void move(double x, double y, double z) {
    logger.info("Move to ( " + x + ", " + y + ", " + z + " )");
  }

  protected void playSound(String soundName, int volume) {
    logger.info("Play " + soundName + " with volume " + volume);
  }

  protected void spawnParticles(String particleType, int count) {
    logger.info("Spawn " + count + " particle with type " + particleType);
  }
}
```

Next, we are able to create derived sandboxed subclass that implements the sandbox method using the provided operations. Here is the first power:

```java
public class SkyLaunch extends Superpower {

  public SkyLaunch() {
    super();
    logger = LoggerFactory.getLogger(SkyLaunch.class);
  }

  @Override
  protected void activate() {
    move(0, 0, 20);
    playSound("SKYLAUNCH_SOUND", 1);
    spawnParticles("SKYLAUNCH_PARTICLE", 100);
  }
}
```

Here is the second power.

```java
public class GroundDive extends Superpower {

  public GroundDive() {
    super();
    logger = LoggerFactory.getLogger(GroundDive.class);
  }

  @Override
  protected void activate() {
    move(0, 0, -20);
    playSound("GROUNDDIVE_SOUND", 5);
    spawnParticles("GROUNDDIVE_PARTICLE", 20);
  }
}
```

Finally, here are the superpowers in active.

```java
public static void main(String[] args) {
    LOGGER.info("Use superpower: sky launch");
    var skyLaunch = new SkyLaunch();
    skyLaunch.activate();
    LOGGER.info("Use superpower: ground dive");
    var groundDive = new GroundDive();
    groundDive.activate();
}
```

Program output:

```
13:10:23.177 [main] INFO com.iluwatar.subclasssandbox.App -- Use superpower: sky launch
13:10:23.179 [main] INFO com.iluwatar.subclasssandbox.SkyLaunch -- Move to ( 0.0, 0.0, 20.0 )
13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.SkyLaunch -- Play SKYLAUNCH_SOUND with volume 1
13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.SkyLaunch -- Spawn 100 particle with type SKYLAUNCH_PARTICLE
13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.App -- Use superpower: ground dive
13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.GroundDive -- Move to ( 0.0, 0.0, -20.0 )
13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.GroundDive -- Play GROUNDDIVE_SOUND with volume 5
13:10:23.180 [main] INFO com.iluwatar.subclasssandbox.GroundDive -- Spawn 20 particle with type GROUNDDIVE_PARTICLE
```

## [When to Use the Subclass Sandbox Pattern in Java](https://java-design-patterns.com/patterns/subclass-sandbox/#when-to-use-the-subclass-sandbox-pattern-in-java)

- Use when you want to create a framework that allows users to define their own behaviors by extending classes.
- Applicable in scenarios where you need to enforce a specific algorithm structure while allowing certain steps to be overridden.

## [Real-World Applications of Subclass Sandbox Pattern in Java](https://java-design-patterns.com/patterns/subclass-sandbox/#real-world-applications-of-subclass-sandbox-pattern-in-java)

- Template method pattern in GUI frameworks where the framework provides the structure and the subclasses implement the specifics.
- Game development where the core game loop is defined, but specific behaviors are provided by subclassing.
- Java libraries like the `AbstractList` where core methods are defined and certain behaviors can be customized by extending classes.

## [Benefits and Trade-offs of Subclass Sandbox Pattern](https://java-design-patterns.com/patterns/subclass-sandbox/#benefits-and-trade-offs-of-subclass-sandbox-pattern)

Benefits:

The Subclass Sandbox pattern in Java

- Encourages code reuse by allowing shared code in the superclass.
- Simplifies the addition of new behaviors through subclassing.
- Enhances code readability and maintainability by separating the algorithm's structure from specific implementations.

Trade-offs:

- Can lead to a large number of subclasses.
- Requires careful design to ensure that the base class is flexible enough for various extensions.
- Increases complexity in understanding the code flow due to multiple layers of inheritance.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/subclass-sandbox/#related-java-design-patterns)

- [Strategy](https://java-design-patterns.com/patterns/strategy/): Both involve interchangeable behaviors, but Strategy pattern uses composition over inheritance.
- [Template Method](https://java-design-patterns.com/patterns/template-method/): Similar in enforcing a structure where certain steps can be overridden by subclasses.

## [References and Credits](https://java-design-patterns.com/patterns/subclass-sandbox/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Game Programming Patterns](https://amzn.to/3K96fOn)
- [Subclass Sandbox (Game Programming Patterns)](https://gameprogrammingpatterns.com/subclass-sandbox.html)

---

## [behavioral/template-method] Template Method 模板方法
> 官方文档: https://java-design-patterns.com/patterns/template-method/

BehavioralAbstractionCode simplificationDecouplingExtensibilityGang of FourInheritanceObject compositionPolymorphismReusabilityAbout 4 min

* * *

## [Intent of Template method Design Pattern](https://java-design-patterns.com/patterns/template-method/#intent-of-template-method-design-pattern)

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

## [Detailed Explanation of Template method Pattern with Real-World Examples](https://java-design-patterns.com/patterns/template-method/#detailed-explanation-of-template-method-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Template Method pattern can be seen in the preparation of a cup of tea or coffee. The overall process (algorithm) is the same: boil water, brew the beverage, pour into cup, and add condiments. However, the specific steps of brewing the beverage differ. For tea, you steep the tea leaves in hot water, while for coffee, you brew ground coffee beans. The Template Method pattern encapsulates the invariant steps of the process (boiling water, pouring, adding condiments) in a base class, while allowing subclasses to define the specific brewing steps, thus ensuring the overall structure of making a hot drink is consistent while allowing customization where needed.

In plain words

> The Java Template Method pattern outlines the core steps in the parent class, allowing child classes to tailor detailed implementations, enhancing code reusability and design flexibility in Java programming.

Wikipedia says

> In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.

Sequence diagram

![Template Method Pattern Sequence Diagram](https://java-design-patterns.com/assets/img/template-method-sequence-diagram.52048078.png)

## [Programmatic Example of Template Method Pattern in Java](https://java-design-patterns.com/patterns/template-method/#programmatic-example-of-template-method-pattern-in-java)

Our programmatic example is about thieves and stealing. The general steps in stealing an item are the same. First, you pick the target, next you confuse him somehow and finally, you steal the item. However, there are many ways to implement these steps.

Let's first introduce the template method class `StealingMethod` along with its concrete implementations `SubtleMethod` and `HitAndRunMethod`. To make sure that subclasses don’t override the template method, the template method (in our case method `steal`) should be declared `final`, otherwise the skeleton defined in the base class could be overridden in subclasses.

```java
@Slf4j
public abstract class StealingMethod {

  protected abstract String pickTarget();

  protected abstract void confuseTarget(String target);

  protected abstract void stealTheItem(String target);

  public final void steal() {
    var target = pickTarget();
    LOGGER.info("The target has been chosen as {}.", target);
    confuseTarget(target);
    stealTheItem(target);
  }
}
```

```java
@Slf4j
public class SubtleMethod extends StealingMethod {

  @Override
  protected String pickTarget() {
    return "shop keeper";
  }

  @Override
  protected void confuseTarget(String target) {
    LOGGER.info("Approach the {} with tears running and hug him!", target);
  }

  @Override
  protected void stealTheItem(String target) {
    LOGGER.info("While in close contact grab the {}'s wallet.", target);
  }
}
```

```java
@Slf4j
public class HitAndRunMethod extends StealingMethod {

  @Override
  protected String pickTarget() {
    return "old goblin woman";
  }

  @Override
  protected void confuseTarget(String target) {
    LOGGER.info("Approach the {} from behind.", target);
  }

  @Override
  protected void stealTheItem(String target) {
    LOGGER.info("Grab the handbag and run away fast!");
  }
}
```

Here's the halfling thief class containing the template method.

```java
public class HalflingThief {

  private StealingMethod method;

  public HalflingThief(StealingMethod method) {
    this.method = method;
  }

  public void steal() {
    method.steal();
  }

  public void changeMethod(StealingMethod method) {
    this.method = method;
  }
}
```

And finally, we show how the halfling thief utilizes the different stealing methods.

```java
public static void main(String[] args) {
    var thief = new HalflingThief(new HitAndRunMethod());
    thief.steal();
    thief.changeMethod(new SubtleMethod());
    thief.steal();
}
```

The program output:

```
11:06:01.721 [main] INFO com.iluwatar.templatemethod.StealingMethod -- The target has been chosen as old goblin woman.
11:06:01.723 [main] INFO com.iluwatar.templatemethod.HitAndRunMethod -- Approach the old goblin woman from behind.
11:06:01.723 [main] INFO com.iluwatar.templatemethod.HitAndRunMethod -- Grab the handbag and run away fast!
11:06:01.723 [main] INFO com.iluwatar.templatemethod.StealingMethod -- The target has been chosen as shop keeper.
11:06:01.723 [main] INFO com.iluwatar.templatemethod.SubtleMethod -- Approach the shop keeper with tears running and hug him!
11:06:01.723 [main] INFO com.iluwatar.templatemethod.SubtleMethod -- While in close contact grab the shop keeper's wallet.
```

## [When to Use the Template method Pattern in Java](https://java-design-patterns.com/patterns/template-method/#when-to-use-the-template-method-pattern-in-java)

The Template Method pattern should be used

- To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary
- When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize" as described by Opdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations
- To control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points

## [Template method Pattern Java Tutorials](https://java-design-patterns.com/patterns/template-method/#template-method-pattern-java-tutorials)

- [Template Method Design Pattern In Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/template-method-design-pattern-in-java)

## [Real-World Applications of Template method Pattern in Java](https://java-design-patterns.com/patterns/template-method/#real-world-applications-of-template-method-pattern-in-java)

- Java's AbstractList and AbstractSet classes in the Collections Framework use the Template Method pattern to define common algorithms for list and set operations.
- Frameworks like JUnit use Template Method to define the setup and teardown process in test cases.

## [Benefits and Trade-offs of Template method Pattern](https://java-design-patterns.com/patterns/template-method/#benefits-and-trade-offs-of-template-method-pattern)

Benefits:

- Promotes code reuse by defining invariant parts of an algorithm in a base class.
- Simplifies code maintenance by encapsulating common behavior in one place.
- Enhances flexibility by allowing subclasses to override specific steps of an algorithm.

Trade-offs:

- Can lead to an increase in the number of classes, making the system more complex.
- Requires careful design to ensure that the steps exposed to subclasses are useful and meaningful.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/template-method/#related-java-design-patterns)

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Often used with Template Method to create objects needed for specific steps of the algorithm.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): While Template Method defines the skeleton of an algorithm and lets subclasses implement specific steps, the Strategy Pattern defines a family of algorithms and makes them interchangeable.
- [Subclass Sandbox](https://java-design-patterns.com/patterns/subclass-sandbox/): Complements Template Method by ensuring that subclasses can safely override specific steps of an algorithm without causing unintended side effects.

## [References and Credits](https://java-design-patterns.com/patterns/template-method/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

## [behavioral/templateview] Template View
> 官方文档: https://java-design-patterns.com/patterns/templateview/

BehavioralAbstractionCode simplificationDecouplingExtensibilityGang of FourInheritancePolymorphismReusabilityAbout 2 min

* * *

## [Intent of Template View Design Pattern](https://java-design-patterns.com/patterns/templateview/#intent-of-template-view-design-pattern)

Separate the structure and static parts of a webpage (or view) from its dynamic content. Template View ensures a consistent layout while allowing flexibility for different types of views.

## [Detailed Explanation of Template View Pattern with Real-World Examples](https://java-design-patterns.com/patterns/templateview/#detailed-explanation-of-template-view-pattern-with-real-world-examples)

Real-World Example

> Think of a blog website where each post page follows the same layout with a header, footer, and main content area. While the header and footer remain consistent, the main content differs for each blog post. The Template View pattern encapsulates the shared layout (header and footer) in a base class while delegating the rendering of the main content to subclasses.

In Plain Words

> The Template View pattern provides a way to define a consistent layout in a base class while letting subclasses implement the specific, dynamic content for different views.

Wikipedia Says

> While not a classic Gang of Four pattern, Template View aligns closely with the Template Method pattern, applied specifically to rendering webpages or views. It defines a skeleton for rendering, delegating dynamic parts to subclasses while keeping the structure consistent.

Flowchart

![Template View Pattern Flowchart](https://java-design-patterns.com/assets/img/template-view-flowchart.287bff9b.png)

## [Programmatic Example of Template View Pattern in Java](https://java-design-patterns.com/patterns/templateview/#programmatic-example-of-template-view-pattern-in-java)

Our example involves rendering different types of views (`HomePageView` and `ContactPageView`) with a common structure consisting of a header, dynamic content, and a footer.

### [The Abstract Base Class: TemplateView](https://java-design-patterns.com/patterns/templateview/#the-abstract-base-class-templateview)

The `TemplateView` class defines the skeleton for rendering a view. Subclasses provide implementations for rendering dynamic content.

```java
@Slf4j
public abstract class TemplateView {

  public final void render() {
    printHeader();
    renderDynamicContent();
    printFooter();
  }

  protected void printHeader() {
    LOGGER.info("Rendering header...");
  }

  protected abstract void renderDynamicContent();

  protected void printFooter() {
    LOGGER.info("Rendering footer...");
  }
}
```

### [Concrete Class: HomePageView](https://java-design-patterns.com/patterns/templateview/#concrete-class-homepageview)

```java
@Slf4j
public class HomePageView extends TemplateView {

  @Override
  protected void renderDynamicContent() {
    LOGGER.info("Welcome to the Home Page!");
  }
}
```

### [Concrete Class: ContactPageView](https://java-design-patterns.com/patterns/templateview/#concrete-class-contactpageview)

```java
@Slf4j
public class ContactPageView extends TemplateView {

  @Override
  protected void renderDynamicContent() {
    LOGGER.info("Contact us at: contact@example.com");
  }
}
```

### [Application Class: App](https://java-design-patterns.com/patterns/templateview/#application-class-app)

The `App` class demonstrates rendering different views using the Template View pattern.

```java
@Slf4j
public class App {

  public static void main(String[] args) {
    TemplateView homePage = new HomePageView();
    LOGGER.info("Rendering HomePage:");
    homePage.render();

    TemplateView contactPage = new ContactPageView();
    LOGGER.info("\nRendering ContactPage:");
    contactPage.render();
  }
}
```

## [Output of the Program](https://java-design-patterns.com/patterns/templateview/#output-of-the-program)

```lessrendering
Rendering header...
Welcome to the Home Page!
Rendering footer...

Rendering ContactPage:
Rendering header...
Contact us at: contact@example.com
Rendering footer...
```

## [When to Use the Template View Pattern in Java](https://java-design-patterns.com/patterns/templateview/#when-to-use-the-template-view-pattern-in-java)

- When you want to enforce a consistent structure for rendering views while allowing flexibility in dynamic content.
- When you need to separate the static layout (header, footer) from the dynamic parts of a view (main content).
- To enhance code reusability and reduce duplication in rendering logic.

## [Benefits and Trade-offs of Template View Pattern](https://java-design-patterns.com/patterns/templateview/#benefits-and-trade-offs-of-template-view-pattern)

**Benefits:**

- Code Reusability: Centralizes shared layout logic in the base class.
- Maintainability: Reduces duplication, making updates easier.
- Flexibility: Allows subclasses to customize dynamic content.

**Trade-offs:**

- Increased Number of Classes: Requires creating separate classes for each type of view.
- Design Overhead: Might be overkill for simple applications with few views.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/templateview/#related-java-design-patterns)

- [Template Method](https://java-design-patterns.com/patterns/template-method/): A similar pattern focusing on defining a skeleton algorithm, allowing subclasses to implement specific steps.
- [Strategy Pattern](https://java-design-patterns.com/patterns/strategy/): Offers flexibility in choosing dynamic behaviors at runtime instead of hardcoding them in subclasses.
- [Decorator Pattern](https://java-design-patterns.com/patterns/decorator/): Can complement Template View for dynamically adding responsibilities to views.

## [Real World Applications of Template View Pattern](https://java-design-patterns.com/patterns/templateview/#real-world-applications-of-template-view-pattern)

- Web frameworks like Spring MVC and Django use this concept to render views consistently.
- CMS platforms like WordPress follow this pattern for theme templates, separating layout from content.

## [References and Credits](https://java-design-patterns.com/patterns/templateview/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)
- [Template Method Pattern](https://refactoring.guru/design-patterns/template-method)
- [Basics of Django: Model-View-Template (MVT) Architecture](https://angelogentileiii.medium.com/basics-of-django-model-view-template-mvt-architecture-8585aecffbf6)

---

## [behavioral/update-method] Update Method
> 官方文档: https://java-design-patterns.com/patterns/update-method/

BehavioralAbstractionData processingDecouplingEvent-drivenGame programmingPolymorphismAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/update-method/#also-known-as)

- Update Mechanism

## [Intent of Update Method Design Pattern](https://java-design-patterns.com/patterns/update-method/#intent-of-update-method-design-pattern)

The Update Method pattern in Java simulates a collection of independent objects by telling each to process one frame of behavior at a time.

## [Detailed Explanation of Update Method Pattern with Real-World Examples](https://java-design-patterns.com/patterns/update-method/#detailed-explanation-of-update-method-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Update Method design pattern is a weather monitoring system. In this system, multiple display devices (such as a mobile app, a website widget, and a wall-mounted digital display) need to show the current weather conditions. These displays subscribe to updates from a central weather station, which collects data from various sensors (temperature, humidity, wind speed, etc.). When the weather station detects new data, it triggers an update method that pushes the new information to all subscribed display devices, ensuring they all show the latest weather conditions simultaneously. This ensures that all displays are synchronized and updated without the need for each device to independently check for updates.

In plain words

> The Update Method design pattern processes system object behavior one frame at a time

[gameprogrammingpatterns.com](http://gameprogrammingpatterns.com/) says

> The game world maintains a collection of objects. Each object implements an update method that simulates one frame of the object’s behavior. Each frame, the game updates every object in the collection.

Sequence diagram

![Update Method Sequence Diagram](https://java-design-patterns.com/assets/img/update-method-sequence-diagram.433893ce.png)

## [Programmatic Example of Update Method Pattern in Java](https://java-design-patterns.com/patterns/update-method/#programmatic-example-of-update-method-pattern-in-java)

The Update Method design pattern is a behavioral pattern that simulates a collection of independent game or application objects by telling each to process one frame of behavior at a time. This pattern is commonly used in game development, where each object in the game world needs to be updated once per frame.

The `World` class represents the game world. It maintains a list of entities (`List<Entity> entities`) and a boolean flag (`isRunning`) to indicate whether the game is running.

```java
public class World {

  protected List<Entity> entities;
  protected volatile boolean isRunning;

  public World() {
    entities = new ArrayList<>();
    isRunning = false;
  }
  // Other properties and methods...
}
```

The `gameLoop` method is the main game loop. It continuously processes user input, updates the game state, and renders the next frame as long as the game is running.

```java
private void gameLoop() {
  while (isRunning) {
    processInput();
    update();
    render();
  }
}
```

The `processInput` method simulates handling user input. In this case, it simply introduces a random time lag to simulate real-life game situations.

```java
private void processInput() {
  try {
    int lag = new SecureRandom().nextInt(200) + 50;
    Thread.sleep(lag);
  } catch (InterruptedException e) {
    LOGGER.error(e.getMessage());
    Thread.currentThread().interrupt();
  }
}
```

The `update` method is where the Update Method pattern is implemented. It iterates over all entities in the game world and calls their `update` method, allowing each entity to process one frame of behavior.

```java
private void update() {
  for (var entity : entities) {
    entity.update();
  }
}
```

The `render` method is responsible for rendering the next frame. In this example, it does nothing as it's not related to the pattern.

```java
private void render() {
  // Does Nothing
}
```

The `run` and `stop` methods are used to start and stop the game loop.

```java
public void run() {
  LOGGER.info("Start game.");
  isRunning = true;
  var thread = new Thread(this::gameLoop);
  thread.start();
}

public void stop() {
  LOGGER.info("Stop game.");
  isRunning = false;
}
```

The `addEntity` method is used to add new entities to the game world.

```java
public void addEntity(Entity entity) {
  entities.add(entity);
}
```

In the `App` class, we can see how the `World` class and its methods are used to create a game world, add entities to it, and start the game loop.

```java
@Slf4j
public class App {

    private static final int GAME_RUNNING_TIME = 2000;

    public static void main(String[] args) {
        try {
            var world = new World();
            var skeleton1 = new Skeleton(1, 10);
            var skeleton2 = new Skeleton(2, 70);
            var statue = new Statue(3, 20);
            world.addEntity(skeleton1);
            world.addEntity(skeleton2);
            world.addEntity(statue);
            world.run();
            Thread.sleep(GAME_RUNNING_TIME);
            world.stop();
        } catch (InterruptedException e) {
            LOGGER.error(e.getMessage());
        }
    }
}
```

Console output:

```
14:46:33.181 [main] INFO com.iluwatar.updatemethod.World -- Start game.
14:46:33.280 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 11.
14:46:33.281 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 71.
14:46:33.452 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 12.
14:46:33.452 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 72.
14:46:33.621 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 13.
14:46:33.621 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 73.
14:46:33.793 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 14.
14:46:33.793 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 74.
14:46:33.885 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 15.
14:46:33.885 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 75.
14:46:34.113 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 16.
14:46:34.113 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 76.
14:46:34.324 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 17.
14:46:34.324 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 77.
14:46:34.574 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 18.
14:46:34.575 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 78.
14:46:34.730 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 19.
14:46:34.731 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 79.
14:46:34.803 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 20.
14:46:34.803 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 80.
14:46:34.979 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 21.
14:46:34.979 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 81.
14:46:35.045 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 22.
14:46:35.046 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 82.
14:46:35.187 [main] INFO com.iluwatar.updatemethod.World -- Stop game.
14:46:35.288 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 23.
14:46:35.289 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 83.
```

This is a basic implementation of the Update Method pattern. In a real-world application, the `Entity` class would likely have additional methods and properties, and the `update` method would contain more complex logic to simulate the entity's behavior.

## [When to Use the Update Method Pattern in Java](https://java-design-patterns.com/patterns/update-method/#when-to-use-the-update-method-pattern-in-java)

Update Method works well when:

- Typically applied in scenarios where multiple objects need synchronous updates without the overhead of manual synchronization, making it a go-to for advanced Java developers.
- The application has a number of objects or systems that need to run simultaneously.
- Each object’s behavior is mostly independent of the others.
- The objects need to be simulated over time.

## [Real-World Applications of Update Method Pattern in Java](https://java-design-patterns.com/patterns/update-method/#real-world-applications-of-update-method-pattern-in-java)

- Real-time games and data processing applications where world objects need to be updated once per frame.

## [Benefits and Trade-offs of Update Method Pattern](https://java-design-patterns.com/patterns/update-method/#benefits-and-trade-offs-of-update-method-pattern)

Benefits:

- Each entity encapsulates its own behavior
- Makes it easy to add and remove entities
- Keeps the main loop uncluttered

Trade-offs:

- Increases complexity due to yielding control every frame
- The state needs to be stored to enable resuming updates after each frame
- Entities are simulated each frame, but they are not truly concurrent

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/update-method/#related-java-design-patterns)

- [Component](https://java-design-patterns.com/patterns/component/): Often used in game development to allow entities to be composed of various components, each potentially having its own update method.
- [Game Loop](https://java-design-patterns.com/patterns/game-loop/): Continuously updates game state and renders the game, which may include the Update Method for various game objects.

## [References and Credits](https://java-design-patterns.com/patterns/update-method/#references-and-credits)

- [Game Programming Patterns](https://amzn.to/3wLTbvr)
- [Game Programming Patterns - Update Method](http://gameprogrammingpatterns.com/update-method.html)

---

## [behavioral/visitor] Visitor 访问者
> 官方文档: https://java-design-patterns.com/patterns/visitor/

BehavioralDecouplingExtensibilityGang of FourObject compositionPolymorphismAbout 4 min

* * *

## [Intent of Visitor Design Pattern](https://java-design-patterns.com/patterns/visitor/#intent-of-visitor-design-pattern)

To represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

## [Detailed Explanation of Visitor Pattern with Real-World Examples](https://java-design-patterns.com/patterns/visitor/#detailed-explanation-of-visitor-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Visitor design pattern can be seen in a museum tour guide system. Imagine a museum where visitors can take guided tours to learn about different types of exhibits, such as paintings, sculptures, and historical artifacts. Each exhibit type requires a different explanation, which is provided by specialized tour guides.
>
> In this scenario, the exhibits are like the elements in the Visitor pattern, and the tour guides are like the visitors. The museum structure remains unchanged, but new guides with new types of tours (operations) can be added without modifying the exhibits themselves. Each guide (visitor) implements a specific way to interact with the exhibits, providing detailed explanations according to their specialization, thereby separating the operations from the objects they operate on.

In plain words

> The Java Visitor pattern defines operations that can be performed on nodes of various data structures, enhancing Java application extensibility.

Wikipedia says

> In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures.

Sequence diagram

![Visitor sequence diagram](https://java-design-patterns.com/assets/img/visitor-sequence-diagram.9806c061.png)

## [Programmatic Example of Visitor Pattern in Java](https://java-design-patterns.com/patterns/visitor/#programmatic-example-of-visitor-pattern-in-java)

Consider a tree structure with army units. Commander has two sergeants under it and each sergeant has three soldiers under them. Given that the hierarchy implements the visitor pattern, we can easily create new objects that interact with the commander, sergeants, soldiers, or all of them.

Given the army unit example from above, we first have the `Unit` and `UnitVisitor` base types.

```java
public abstract class Unit {

  private final Unit[] children;

  public Unit(Unit... children) {
    this.children = children;
  }

  public void accept(UnitVisitor visitor) {
    Arrays.stream(children).forEach(child -> child.accept(visitor));
  }
}
```

```java
public interface UnitVisitor {

  void visit(Soldier soldier);

  void visit(Sergeant sergeant);

  void visit(Commander commander);
}
```

Then we have the concrete units `Commander`, `Sergeant`, and `Soldier`.

```java
public class Commander extends Unit {

  public Commander(Unit... children) {
    super(children);
  }

  @Override
  public void accept(UnitVisitor visitor) {
    visitor.visit(this);
    super.accept(visitor);
  }

  @Override
  public String toString() {
    return "commander";
  }
}
```

```java
public class Sergeant extends Unit {

  public Sergeant(Unit... children) {
    super(children);
  }

  @Override
  public void accept(UnitVisitor visitor) {
    visitor.visit(this);
    super.accept(visitor);
  }

  @Override
  public String toString() {
    return "sergeant";
  }
}
```

```java
public class Soldier extends Unit {

  public Soldier(Unit... children) {
    super(children);
  }

  @Override
  public void accept(UnitVisitor visitor) {
    visitor.visit(this);
    super.accept(visitor);
  }

  @Override
  public String toString() {
    return "soldier";
  }
}
```

Here are the concrete visitors `CommanderVisitor`, `SergeantVisitor`, and `SoldierVisitor`.

```java
@Slf4j
public class CommanderVisitor implements UnitVisitor {

  @Override
  public void visit(Soldier soldier) {
    // Do nothing
  }

  @Override
  public void visit(Sergeant sergeant) {
    // Do nothing
  }

  @Override
  public void visit(Commander commander) {
    LOGGER.info("Good to see you {}", commander);
  }
}
```

```java
@Slf4j
public class SergeantVisitor implements UnitVisitor {

  @Override
  public void visit(Soldier soldier) {
    // Do nothing
  }

  @Override
  public void visit(Sergeant sergeant) {
    LOGGER.info("Hello {}", sergeant);
  }

  @Override
  public void visit(Commander commander) {
    // Do nothing
  }
}
```

```java
@Slf4j
public class SoldierVisitor implements UnitVisitor {

  @Override
  public void visit(Soldier soldier) {
    LOGGER.info("Greetings {}", soldier);
  }

  @Override
  public void visit(Sergeant sergeant) {
    // Do nothing
  }

  @Override
  public void visit(Commander commander) {
    // Do nothing
  }
}
```

Finally, we can show the power of visitors in action.

```java
public static void main(String[] args) {

    var commander = new Commander(
            new Sergeant(new Soldier(), new Soldier(), new Soldier()),
            new Sergeant(new Soldier(), new Soldier(), new Soldier())
    );
    commander.accept(new SoldierVisitor());
    commander.accept(new SergeantVisitor());
    commander.accept(new CommanderVisitor());
}
```

Program output:

```
14:58:06.115 [main] INFO com.iluwatar.visitor.SoldierVisitor -- Greetings soldier
14:58:06.118 [main] INFO com.iluwatar.visitor.SoldierVisitor -- Greetings soldier
14:58:06.118 [main] INFO com.iluwatar.visitor.SoldierVisitor -- Greetings soldier
14:58:06.118 [main] INFO com.iluwatar.visitor.SoldierVisitor -- Greetings soldier
14:58:06.118 [main] INFO com.iluwatar.visitor.SoldierVisitor -- Greetings soldier
14:58:06.118 [main] INFO com.iluwatar.visitor.SoldierVisitor -- Greetings soldier
14:58:06.118 [main] INFO com.iluwatar.visitor.SergeantVisitor -- Hello sergeant
14:58:06.118 [main] INFO com.iluwatar.visitor.SergeantVisitor -- Hello sergeant
14:58:06.118 [main] INFO com.iluwatar.visitor.CommanderVisitor -- Good to see you commander
```

## [When to Use the Visitor Pattern in Java](https://java-design-patterns.com/patterns/visitor/#when-to-use-the-visitor-pattern-in-java)

Use the Visitor pattern when

- Implement the Visitor design pattern in Java when you need to efficiently perform operations across groups of similar objects without modifying their classes, and you want to avoid polluting their classes with this operation.
- Use it when a class structure is stable, but you need to perform new operations on the structure without changing it.
- It's beneficial when the set of classes are fixed and only the operations need to be extended.

## [Visitor Pattern Java Tutorials](https://java-design-patterns.com/patterns/visitor/#visitor-pattern-java-tutorials)

- [Visitor (Refactoring Guru)](https://refactoring.guru/design-patterns/visitor)
- [Visitor Pattern Tutorial with Java Examples (DZone)](https://dzone.com/articles/design-patterns-visitor)
- [Visitor Design Pattern (Sourcemaking)](https://sourcemaking.com/design_patterns/visitor)

## [Real-World Applications of Visitor Pattern in Java](https://java-design-patterns.com/patterns/visitor/#real-world-applications-of-visitor-pattern-in-java)

- Compiler design, where the Visitor pattern can be used for operations like pretty printing, semantic checks, etc.
- Abstract Syntax Tree (AST) processing.
- Document structure processing (e.g., HTML, XML).
- [Apache Wicket](https://github.com/apache/wicket) component tree, see [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java)
- [javax.lang.model.element.AnnotationValue](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValue.html) and [AnnotationValueVisitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/AnnotationValueVisitor.html)
- [javax.lang.model.element.Element](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/Element.html) and [Element Visitor](http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/ElementVisitor.html)
- [java.nio.file.FileVisitor](http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileVisitor.html)

## [Benefits and Trade-offs of Visitor Pattern](https://java-design-patterns.com/patterns/visitor/#benefits-and-trade-offs-of-visitor-pattern)

Benefits:

- Simplifies adding new operations: Adding a new operation is straightforward because you can add a new visitor without changing existing code.
- Single Responsibility Principle: The Visitor pattern allows you to move related behavior into one class.
- Open/Closed Principle: Elements can stay closed to modification while visitors are open to extension.

Trade-offs:

- Adding new element classes: If you need to add new types of elements, you'll need to change both the visitor interface and all of its concrete visitors.
- Circular dependencies: In complex systems, this pattern can introduce circular dependencies between visitor and element classes.
- Breaking encapsulation: Visitor pattern requires that the element classes expose enough details to allow the visitor to do its job, potentially breaking encapsulation.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/visitor/#related-java-design-patterns)

- [Composite](https://java-design-patterns.com/patterns/composite/): The Visitor pattern is often used in conjunction with the Composite pattern, where the visitor can perform operations over a composite structure.
- [Interpreter](https://java-design-patterns.com/patterns/interpreter/): Visitors can be used to implement the non-terminal expressions in the Interpreter pattern.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Visitor can be considered a way of making strategies work on objects that they were not designed to operate on.

## [References and Credits](https://java-design-patterns.com/patterns/visitor/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)

---

<!-- ============================================ -->
<!-- Architectural 架构模式 (25 个) -->
<!-- ============================================ -->

## [architectural/bloc] Bloc
> 官方文档: https://java-design-patterns.com/patterns/bloc/

ArchitecturalAbstractionData bindingDecouplingEvent-drivenPresentationReactiveReusabilityState trackingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/bloc/#also-known-as)

- Business Logic Component
- Business Logic Controller

## [Intent of the Bloc Pattern](https://java-design-patterns.com/patterns/bloc/#intent-of-the-bloc-pattern)

The Bloc pattern manages the state of an object and allows for dynamically notifying interested listeners about state changes. It separates state management logic from the rest of the application, improving code organization and flexibility.

## [Detailed explanation of the Bloc pattern with real-World examples](https://java-design-patterns.com/patterns/bloc/#detailed-explanation-of-the-bloc-pattern-with-real-world-examples)

Real-world example

> Consider a digital counter application where multiple parts of the UI need to be updated whenever the counter changes. For example, a label displaying the counter value and an activity log showing changes. Instead of directly modifying these UI components, the Bloc pattern manages the counter state and notifies all registered listeners about the state change. Listeners can dynamically subscribe or unsubscribe from receiving updates.

In plain words

> The Bloc pattern manages a single state object and dynamically notifies registered listeners whenever the state changes.

Wikipedia says

> While not a formalized "Gang of Four" design pattern, Bloc is widely used in state-driven applications. It centralizes state management and propagates state changes to registered observers, following principles of separation of concerns.

Sequence diagram

![Bloc sequence diagram](https://java-design-patterns.com/assets/img/bloc-sequence-diagram.fb21707f.png)

## [Programmatic Example of the Bloc Pattern in Java](https://java-design-patterns.com/patterns/bloc/#programmatic-example-of-the-bloc-pattern-in-java)

This example demonstrates how to implement the Bloc pattern using Java and Swing. The pattern separates the state of the application from UI components, and provides a reactive, event-driven approach to managing updates.

Core components of the Bloc Pattern include a `State` object, a `Bloc` class responsible for managing and updating that state, and interfaces (`StateListener` and `ListenerManager`) for subscribing to changes.

The `State` class represents the application's data at any given time.

```java
public record State(int value) {}
```

The `ListenerManager` interface declares methods to add and remove listeners, as well as retrieve them.

```java
public interface ListenerManager<T> {
  void addListener(StateListener<T> listener);
  void removeListener(StateListener<T> listener);
  List<StateListener<T>> getListeners();
}
```

The `StateListener` interface defines how a listener reacts to state changes.

```java
public interface StateListener<T> {
  void onStateChange(T state);
}
```

The `Bloc` class maintains the current state and notifies listeners of updates. It provides `increment` and `decrement` methods to update state and automatically notify registered listeners.

```java
public class Bloc implements ListenerManager<State> {

  private State currentState;
  private final List<StateListener<State>> listeners = new ArrayList<>();

  public Bloc() {
    this.currentState = new State(0);
  }

  @Override
  public void addListener(StateListener<State> listener) {
    listeners.add(listener);
    listener.onStateChange(currentState);
  }

  @Override
  public void removeListener(StateListener<State> listener) {
    listeners.remove(listener);
  }

  @Override
  public List<StateListener<State>> getListeners() {
    return Collections.unmodifiableList(listeners);
  }

  private void emitState(State newState) {
    currentState = newState;
    for (StateListener<State> listener : listeners) {
      listener.onStateChange(currentState);
    }
  }

  public void increment() {
    emitState(new State(currentState.value() + 1));
  }

  public void decrement() {
    emitState(new State(currentState.value() - 1));
  }
}
```

This class demonstrates how to integrate the Bloc pattern with a simple Swing GUI. It sets up a counter, buttons to change the state, and a toggle to enable or disable the listener dynamically.

```java
public class Main {
  public static void main(String[] args) {
    BlocUi blocUi = new BlocUi();
    blocUi.createAndShowUi();
  }
}

public class BlocUi {

  public void createAndShowUi() {
    final Bloc bloc = new Bloc();

    JFrame frame = new JFrame("BloC example");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(400, 300);

    JLabel counterLabel = new JLabel("Counter: 0", SwingConstants.CENTER);
    counterLabel.setFont(new Font("Arial", Font.BOLD, 20));

    JButton decrementButton = new JButton("Decrement");
    JButton toggleListenerButton = new JButton("Disable Listener");
    JButton incrementButton = new JButton("Increment");

    frame.setLayout(new BorderLayout());
    frame.add(counterLabel, BorderLayout.CENTER);
    frame.add(incrementButton, BorderLayout.NORTH);
    frame.add(decrementButton, BorderLayout.SOUTH);
    frame.add(toggleListenerButton, BorderLayout.EAST);

    StateListener<State> stateListener = state -> counterLabel.setText("Counter: " + state.value());

    bloc.addListener(stateListener);

    toggleListenerButton.addActionListener(
            e -> {
              if (bloc.getListeners().contains(stateListener)) {
                bloc.removeListener(stateListener);
                toggleListenerButton.setText("Enable Listener");
              } else {
                bloc.addListener(stateListener);
                toggleListenerButton.setText("Disable Listener");
              }
            });

    incrementButton.addActionListener(e -> bloc.increment());
    decrementButton.addActionListener(e -> bloc.decrement());

    frame.setVisible(true);
  }
}
```

### [Program Output](https://java-design-patterns.com/patterns/bloc/#program-output)

- **On Increment**

`Counter: 1`

- **On Decrement**

`Counter: 0`

- **Dynamic Listener Toggle**

  - Listener disabled: Counter stops updating.
  - Listener enabled: Counter updates again.

## [When to Use the Bloc Pattern](https://java-design-patterns.com/patterns/bloc/#when-to-use-the-bloc-pattern)

Use the Bloc pattern when:

- When you want a clean separation of business logic and UI in Java applications
- When you need a reactive approach to updating UI based on state changes
- When you want to avoid coupling controllers or presenters directly to data manipulation
- When multiple UI elements need access to the same business logic

## [Real-World Applications of Bloc Pattern](https://java-design-patterns.com/patterns/bloc/#real-world-applications-of-bloc-pattern)

- Java-based desktop applications that require real-time UI updates
- Backend-driven Java frameworks that separate service layers from presentation
- Cross-platform applications where the logic must remain consistent regardless of the UI technology

## [Benefits and Trade-offs of Bloc Pattern](https://java-design-patterns.com/patterns/bloc/#benefits-and-trade-offs-of-bloc-pattern)

Benefits:

- Simplifies UI components by removing direct business logic
- Improves testability by isolating state and behavior
- Encourages code reuse by centralizing data flows
- Enhances maintainability through clear separation of concerns

Trade-offs:

- May introduce additional boilerplate code for managing streams or observers
- Requires careful design to avoid a monolithic “god” component
- Demands consistent reactive programming practices to be effective

## [Related Patterns](https://java-design-patterns.com/patterns/bloc/#related-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Bloc is a specialized implementation of the Observer pattern.
- [Mediator](https://java-design-patterns.com/patterns/mediator/): Orchestrates interactions among multiple objects through a central component
- [MVC](https://java-design-patterns.com/patterns/model-view-controller/): Shares the idea of separating concerns between layers

## [References and Credits](https://java-design-patterns.com/patterns/bloc/#references-and-credits)

- [Bloc architecture(bloclibrary.dev)](https://bloclibrary.dev/architecture/)
- [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Event-Driven Programming in Java (Oracle)](https://www.oracle.com/java/)
- [Java Swing Documentation (Oracle)](https://docs.oracle.com/javase/tutorial/uiswing/)

---

## [architectural/clean-architecture] Clean Architecture
> 官方文档: https://java-design-patterns.com/patterns/clean-architecture/

ArchitecturalArchitectureDecouplingDomainInversion of controlLayered architectureModularityTestingAbout 4 min

* * *

## [Intent of Clean Architecture.](https://java-design-patterns.com/patterns/clean-architecture/#intent-of-clean-architecture)

To organize the system so that the core business logic remains independent from external concerns and frameworks.

## [Detailed Explanation of Clean Architecture Pattern with Real-World Examples](https://java-design-patterns.com/patterns/clean-architecture/#detailed-explanation-of-clean-architecture-pattern-with-real-world-examples)

Real-world example

> Imagine a large pizza chain with multiple ordering channels—web, mobile app, phone calls, and in-store kiosks. The core “pizza domain” logic (calculating prices, preparing orders, managing loyalty points) is kept entirely separate from the user interfaces and storage mechanisms. As a result, the chain can add or change the ordering channel (for example, introducing a chatbot or swapping out the database) without altering the fundamental pizza-ordering rules, thanks to the layered boundaries and strict dependency rules of Clean Architecture.

In plain words

> Clean Architecture is a software design approach that isolates the core business logic from external concerns (like databases, frameworks, or UI) through strict layering and clear boundaries, ensuring that changes in one layer don't ripple through the entire system.

Wikipedia says

> The clean architecture proposed by Robert C. Martin in 2012 combines the principles of the hexagonal architecture, the onion architecture and several other variants. It provides additional levels of detail of the component, which are presented as concentric rings. It isolates adapters and interfaces (user interface, databases, external systems, devices) in the outer rings of the architecture and leaves the inner rings for use cases and entities. The clean architecture uses the principle of dependency inversion with the strict rule that dependencies shall only exist between an outer ring to an inner ring and never the contrary.

Mind map

![Clean Architecture Mind Map](https://java-design-patterns.com/assets/img/clean-architecture-mind-map.a82f7f55.png)

Flowchart

![Clean Architecture Flowchart](https://java-design-patterns.com/assets/img/clean-architecture-flowchart.96d63165.png)

## [Programmatic Example of Clean Architecture Pattern](https://java-design-patterns.com/patterns/clean-architecture/#programmatic-example-of-clean-architecture-pattern)

First, we define the core domain entities: `Product`, `Order`, and `Cart`. These classes capture the fundamental business logic and state.

```java
public class Product {
    private String id;
    private String name;
    private double price;

    public Product(String id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
}
```

```java
public class Cart {
    private Product product;
    private int quantity;

    public CartItem(Product product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }

    public double getTotalPrice() {
        return product.getPrice() * quantity;
    }
}
```

```java
public class Order {
    private String orderId;
    private List<CartItem> items;
    private double totalPrice;

    public Order(String orderId, List<CartItem> items) {
        this.orderId = orderId;
        this.items = items;
        this.totalPrice = items.stream().mapToDouble(CartItem::getTotalPrice).sum();
    }
}
```

The repository interfaces are created to abstract data operations for each domain object, allowing us to switch out storage or persistence mechanisms without changing higher-level logic.

```java
public interface CartRepository {
    void addItemToCart(String userId, Product product, int quantity);
    void removeItemFromCart(String userId, String productId);
    List<Cart> getItemsInCart(String userId);
    double calculateTotal(String userId);
    void clearCart(String userId);
}
```

```java
public interface ProductRepository {
    Product getProductById(String productId);
}
```

```java
public interface OrderRepository {
    void saveOrder(Order order);
}
```

The in-memory data store implementations use simple collections to hold state. They demonstrate how easily we can replace or extend the data layer (e.g., swapping in a database) without affecting the domain logic.

```java
public class InMemoryCartRepository implements CartRepository {
  private final Map<String, List<Cart>> userCarts = new HashMap<>();

  @Override
  public void addItemToCart(String userId, Product product, int quantity) {
    List<Cart> cart = userCarts.getOrDefault(userId, new ArrayList<>());
    cart.add(new Cart(product, quantity));
    userCarts.put(userId, cart);
  }

  @Override
  public void removeItemFromCart(String userId, String productId) {
    List<Cart> cart = userCarts.get(userId);
    if (cart != null) {
      cart.removeIf(item -> item.getProduct().getId().equals(productId));
    }
  }

  @Override
  public List<Cart> getItemsInCart(String userId) {
    return userCarts.getOrDefault(userId, new ArrayList<>());
  }

  @Override
  public double calculateTotal(String userId) {
    return userCarts.getOrDefault(userId, new ArrayList<>())
        .stream()
        .mapToDouble(Cart::getTotalPrice)
        .sum();
  }

  @Override
  public void clearCart(String userId) {
    userCarts.remove(userId);
  }
}
```

```java
public class InMemoryOrderRepository implements OrderRepository {
    private final List<Order> orders = new ArrayList<>();

    @Override
    public void saveOrder(Order order) {
        orders.add(order);
    }
}
```

```java
public class InMemoryProductRepository implements ProductRepository {
    private final Map<String, Product> products = new HashMap<>();

    public InMemoryProductRepository() {
        products.put("1", new Product("1", "Laptop", 1000.0));
        products.put("2", new Product("2", "Smartphone", 500.0));
    }

    @Override
    public Product getProductById(String productId) {
        return products.get(productId);
    }
}
```

The order controller coordinates the checkout process by using the use-case or service layer (`ShoppingCartService`).

```java
public class OrderController{
  private final ShoppingCartService shoppingCartUseCase;

  public OrderController(ShoppingCartService shoppingCartUseCase) {
    this.shoppingCartUseCase = shoppingCartUseCase;
  }

  public Order checkout(String userId) {
    return shoppingCartUseCase.checkout(userId);
  }
}
```

The cart controller focuses on cart-related actions like adding or removing items and calculating totals.

```java
public class CartController {
  private final ShoppingCartService shoppingCartUseCase;

  public CartController(ShoppingCartService shoppingCartUseCase) {
    this.shoppingCartUseCase = shoppingCartUseCase;
  }

  public void addItemToCart(String userId, String productId, int quantity) {
    shoppingCartUseCase.addItemToCart(userId, productId, quantity);
  }

  public void removeItemFromCart(String userId, String productId) {
    shoppingCartUseCase.removeItemFromCart(userId, productId);
  }

  public double calculateTotal(String userId) {
    return shoppingCartUseCase.calculateTotal(userId);
  }
}
```

The clean architecture in action. In the `main` method, we wire up everything, simulating a typical user flow: items are added to the cart, the total is calculated, and finally an order is placed.

```java
public static void main(String[] args) {

    ProductRepository productRepository = new InMemoryProductRepository();
    CartRepository cartRepository = new InMemoryCartRepository();
    OrderRepository orderRepository = new InMemoryOrderRepository();

    ShoppingCartService shoppingCartUseCase =
        new ShoppingCartService(productRepository, cartRepository, orderRepository);

    CartController cartController = new CartController(shoppingCartUseCase);
    OrderController orderController = new OrderController(shoppingCartUseCase);

    String userId = "user123";
    cartController.addItemToCart(userId, "1", 1);
    cartController.addItemToCart(userId, "2", 2);

    System.out.println("Total: $" + cartController.calculateTotal(userId));

    Order order = orderController.checkout(userId);
    System.out.println(
        "Order placed! Order ID: " + order.getOrderId() + ", Total: $" + order.getTotalPrice());
  }
```

The output of the code.

```md
Total: $2000.0
Order placed! Order ID: ORDER-1743349969254, Total: $2000.0
```

## [When to Use the Clean Architecture Pattern in Java](https://java-design-patterns.com/patterns/clean-architecture/#when-to-use-the-clean-architecture-pattern-in-java)

- When you want to keep business rules independent of UI, database, or any other external agency
- When you need a high level of maintainability and testability in large Java applications
- When you aim to enforce clear boundaries among application layers

## [Real-World Applications of Clean Architecture Pattern in Java](https://java-design-patterns.com/patterns/clean-architecture/#real-world-applications-of-clean-architecture-pattern-in-java)

- Large-scale enterprise systems in finance and insurance domains
- Microservices-based architectures that prioritize decoupling and modular design
- Java systems requiring stringent separation of concerns and domain-centered design

## [Benefits and Trade-offs of Clean Architecture Pattern](https://java-design-patterns.com/patterns/clean-architecture/#benefits-and-trade-offs-of-clean-architecture-pattern)

Benefits:

- High maintainability by isolating core logic from infrastructure details
- Enhanced testability through clear boundaries around the domain model
- Flexibility in replacing or upgrading external components without affecting core logic

Trade-Offs:

- Initial complexity from enforcing strict layers and boundaries
- Potential overhead in smaller projects not requiring such rigid separation
- Requires disciplined team adherence to architecture rules

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/clean-architecture/#related-java-design-patterns)

- [Dependency Injection](https://java-design-patterns.com/patterns/dependency-injection/): Facilitates decoupling layers by injecting dependencies rather than hard-coding them
- [Layered Architecture](https://java-design-patterns.com/patterns/layered-architecture/): Both separate concerns into distinct tiers but Clean Architecture emphasizes strict dependency rules
- [Hexagonal Architecture](https://java-design-patterns.com/patterns/hexagonal-architecture/): Similar focus on isolating core logic with ports and adapters

## [References and Credits](https://java-design-patterns.com/patterns/clean-architecture/#references-and-credits)

- [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR)
- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3wRnjp5)
- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)

---

## [architectural/command-query-responsibility-segregation] Command Query Responsibility Segregation
> 官方文档: https://java-design-patterns.com/patterns/command-query-responsibility-segregation/

ArchitecturalEvent-drivenPerformanceScalabilityAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#also-known-as)

- CQRS

## [Intent of Command Query Responsibility Segregation Design Pattern](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#intent-of-command-query-responsibility-segregation-design-pattern)

Command Query Responsibility Segregation (CQRS) aims to segregate the operations that modify the state of an application (commands) from the operations that read the state (queries). This separation enhances scalability, performance, and maintainability in complex software systems.

## [Detailed Explanation of Command Query Responsibility Segregation Pattern with Real-World Examples](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#detailed-explanation-of-command-query-responsibility-segregation-pattern-with-real-world-examples)

Real-world example

> Imagine a modern library where the tasks of borrowing and returning books (commands) are handled at the front desk, while the task of searching for books and reading them (queries) happens in the reading area. The front desk optimizes for transaction efficiency and record-keeping, ensuring books are properly checked in and out. Meanwhile, the reading area is optimized for comfort and accessibility, making it easy for readers to find and engage with the books. This separation improves the library's overall efficiency and user experience, much like the CQRS pattern enhances a software system's performance and maintainability.

In plain words

> The CQRS design pattern separates the actions of modifying data (commands) from the actions of retrieving data (queries) to enhance performance, scalability, and maintainability in software systems. By implementing CQRS, you can optimize your system's read and write operations independently, allowing for more efficient data handling and improved overall system performance.

Microsoft's documentation says

> CQRS separates reads and writes into different models, using commands to update data, and queries to read data.

Architecture diagram

![CQRS Architecture Diagram](https://java-design-patterns.com/assets/img/cqrs-architecture-diagram.ddb9e663.png)

## [Programmatic Example of CQRS Pattern in Java](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#programmatic-example-of-cqrs-pattern-in-java)

One way to implement the Command Query Responsibility Segregation (CQRS) pattern is to separate the read and write operations into different services.

Let's see the code implementation first and explain how it works afterward.

```java
public static void main(String[] args) {

    // Create Authors and Books using CommandService
    var commands = new CommandServiceImpl();

    commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com");
    commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com");
    commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com");

    commands.bookAddedToAuthor("Domain-Driven Design", 60.08, AppConstants.E_EVANS);
    commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH);
    commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH);
    commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH);
    commands.bookAddedToAuthor("Patterns of Enterprise"
            + " Application Architecture", 54.01, AppConstants.M_FOWLER);
    commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER);
    commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans");

    // Query the database using QueryService
    var queries = new QueryServiceImpl();

    var nullAuthor = queries.getAuthorByUsername("username");
    var evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
    var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
    var authorsCount = queries.getAuthorsCount();
    var dddBook = queries.getBook("Domain-Driven Design");
    var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);

    LOGGER.info("Author username : {}", nullAuthor);
    LOGGER.info("Author evans : {}", evans);
    LOGGER.info("jBloch number of books : {}", blochBooksCount);
    LOGGER.info("Number of authors : {}", authorsCount);
    LOGGER.info("DDD book : {}", dddBook);
    LOGGER.info("jBloch books : {}", blochBooks);

    HibernateUtil.getSessionFactory().close();
}
```

1. Command Service: The `CommandServiceImpl` class is used for write operations. It provides methods to create authors and books, and to add books to authors.

2. Query Service: The `QueryServiceImpl` class is used for read operations. It provides methods to get author and book details.


This separation of concerns allows for flexibility in how the application handles data access and manipulation, and is a key aspect of the CQRS pattern.

Program output:

```
17:37:56.040 [main] INFO  com.iluwatar.cqrs.app.App - Author username : null
17:37:56.040 [main] INFO  com.iluwatar.cqrs.app.App - Author evans : Author(name=Eric J. Evans, email=evans@email.com, username=eEvans)
17:37:56.041 [main] INFO  com.iluwatar.cqrs.app.App - jBloch number of books : 3
17:37:56.041 [main] INFO  com.iluwatar.cqrs.app.App - Number of authors : 3
17:37:56.041 [main] INFO  com.iluwatar.cqrs.app.App - DDD book : Book(title=Domain-Driven Design, price=60.08)
17:37:56.042 [main] INFO  com.iluwatar.cqrs.app.App - jBloch books : [Book(title=Effective Java, price=40.54), Book(title=Java Puzzlers, price=39.99), Book(title=Java Concurrency in Practice, price=29.4)]
```

## [When to Use the Command Query Responsibility Segregation Pattern in Java](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#when-to-use-the-command-query-responsibility-segregation-pattern-in-java)

- Systems requiring distinct models for read and write operations for scalability and maintainability, such as e-commerce platforms and high-traffic websites.
- Complex domain models, like financial services or healthcare applications, where the task of updating objects differs significantly from the task of reading object data.
- Scenarios where performance optimization for read operations is crucial, and the system can benefit from different data models or databases for reads and writes, enhancing data retrieval speed and accuracy.

## [Real-World Applications of CQRS Pattern in Java](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#real-world-applications-of-cqrs-pattern-in-java)

- Distributed Systems and Microservices Architecture, where different services manage read and write responsibilities.
- Event-Sourced Systems, where changes to the application state are stored as a sequence of events.
- High-Performance Web Applications, segregating read and write databases to optimize load handling.

## [Benefits and Trade-offs of Command Query Responsibility Segregation Pattern](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#benefits-and-trade-offs-of-command-query-responsibility-segregation-pattern)

Benefits:

- Scalability: By separating read and write models, each can be scaled independently according to their specific demands.
- Optimization: Allows for the optimization of read models for query efficiency and write models for transactional integrity.
- Maintainability: Reduces complexity by separating the concerns, leading to cleaner, more maintainable code.
- Flexibility: Offers the flexibility to choose different technologies for the read and write sides according to their requirements.

Trade-Offs:

- Complexity: Introduces complexity due to synchronization between read and write models, especially in consistency maintenance.
- Overhead: Might be an overkill for simple systems where the benefits do not outweigh the additional complexity.
- Learning Curve: Requires a deeper understanding and careful design to implement effectively, increasing the initial learning curve.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#related-java-design-patterns)

- [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Often used in conjunction with CQRS, where changes to the application state are stored as a sequence of events.
- Domain-Driven Design (DDD): CQRS fits well within the DDD context, providing clear boundaries and separation of concerns.
- [Repository](https://java-design-patterns.com/patterns/repository/): Can be used to abstract the data layer, providing a more seamless integration between the command and query sides.

## [References and Credits](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/#references-and-credits)

- [Implementing Domain-Driven Design](https://amzn.to/3TJN2HH)
- [Microsoft .NET: Architecting Applications for the Enterprise](https://amzn.to/4aktRes)
- [Patterns, Principles, and Practices of Domain-Driven Design](https://amzn.to/3vNV4Hm)
- [CQRS, Task Based UIs, Event Sourcing agh! (Greg Young)](http://codebetter.com/gregyoung/2010/02/16/cqrs-task-based-uis-event-sourcing-agh/)
- [CQRS (Martin Fowler)](https://martinfowler.com/bliki/CQRS.html)
- [CQRS for Great Good (Oliver Wolf)](https://www.youtube.com/watch?v=Ge53swja9Dw)
- [CQRS pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs)

---

## [architectural/event-driven-architecture] Event-Driven Architecture
> 官方文档: https://java-design-patterns.com/patterns/event-driven-architecture/

ArchitecturalAsynchronousDecouplingEnterprise patternsEvent-drivenMessagingPublish/subscribeReactiveScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/event-driven-architecture/#also-known-as)

- Event-Driven System
- Event-Based Architecture

## [Intent of Event-Driven Architecture Design Pattern](https://java-design-patterns.com/patterns/event-driven-architecture/#intent-of-event-driven-architecture-design-pattern)

Event-Driven Architecture (EDA) is designed to orchestrate behavior around the production, detection, consumption of, and reaction to events. This architecture enables highly decoupled, scalable, and dynamic interconnections between event producers and consumers.

## [Detailed Explanation of Event-Driven Architecture Pattern with Real-World Examples](https://java-design-patterns.com/patterns/event-driven-architecture/#detailed-explanation-of-event-driven-architecture-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Event-Driven Architecture (EDA) pattern is the operation of an air traffic control system. In this system, events such as aircraft entering airspace, changes in weather conditions, and ground vehicle movements trigger specific responses like altering flight paths, scheduling gate assignments, and updating runway usage. This setup allows for highly efficient, responsive, and safe management of airport operations, reflecting EDA's core principles of asynchronous communication and dynamic event handling.

In plain words

> Event-Driven Architecture is a design pattern where system behavior is dictated by the occurrence of specific events, allowing for dynamic, efficient, and decoupled responses.

Wikipedia says

> Event-driven architecture (EDA) is a software architecture paradigm concerning the production and detection of events.

Architecture diagram

![EDA Architecture Diagram](https://java-design-patterns.com/assets/img/eda-architecture-diagram.e2ffe1bb.png)

## [Programmatic Example of Event-Driven Architecture in Java](https://java-design-patterns.com/patterns/event-driven-architecture/#programmatic-example-of-event-driven-architecture-in-java)

The Event-Driven Architecture (EDA) pattern in this module is implemented using several key classes and concepts:

- Event: This is an abstract class that represents an event. It's the base class for all types of events that can occur in the system.
- UserCreatedEvent and UserUpdatedEvent: These are concrete classes that extend the Event class. They represent specific types of events that can occur in the system, namely the creation and updating of a user.
- EventDispatcher: This class is responsible for dispatching events to their respective handlers. It maintains a mapping of event types to handlers.
- UserCreatedEventHandler and UserUpdatedEventHandler: These are the handler classes for the UserCreatedEvent and UserUpdatedEvent respectively. They contain the logic to execute when these events occur.

First, we'll define the `Event` abstract class and the concrete event classes `UserCreatedEvent` and `UserUpdatedEvent`.

```java
public abstract class Event {
  // Event related properties and methods
}
```

```java
public class UserCreatedEvent extends Event {
  private User user;

  public UserCreatedEvent(User user) {
    this.user = user;
  }

  public User getUser() {
    return user;
  }
}
```

```java
public class UserUpdatedEvent extends Event {
  private User user;

  public UserUpdatedEvent(User user) {
    this.user = user;
  }

  public User getUser() {
    return user;
  }
}
```

Next, we'll define the event handlers `UserCreatedEventHandler` and `UserUpdatedEventHandler`.

```java
public class UserCreatedEventHandler {
  public void onUserCreated(UserCreatedEvent event) {
    // Logic to execute when a UserCreatedEvent occurs
  }
}
```

```java
public class UserUpdatedEventHandler {
  public void onUserUpdated(UserUpdatedEvent event) {
    // Logic to execute when a UserUpdatedEvent occurs
  }
}
```

Then, we'll define the `EventDispatcher` class that is responsible for dispatching events to their respective handlers.

```java
public class EventDispatcher {
  private Map<Class<? extends Event>, List<Consumer<Event>>> handlers = new HashMap<>();

  public <E extends Event> void registerHandler(Class<E> eventType, Consumer<E> handler) {
    handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler::accept);
  }

  public void dispatch(Event event) {
    List<Consumer<Event>> eventHandlers = handlers.get(event.getClass());
    if (eventHandlers != null) {
      eventHandlers.forEach(handler -> handler.accept(event));
    }
  }
}
```

Finally, we'll demonstrate how to use these classes in the main application.

```java
public class App {
  public static void main(String[] args) {
    // Create an EventDispatcher
    EventDispatcher dispatcher = new EventDispatcher();

    // Register handlers for UserCreatedEvent and UserUpdatedEvent
    dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler()::onUserCreated);
    dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler()::onUserUpdated);

    // Create a User
    User user = new User("iluwatar");

    // Dispatch UserCreatedEvent
    dispatcher.dispatch(new UserCreatedEvent(user));

    // Dispatch UserUpdatedEvent
    dispatcher.dispatch(new UserUpdatedEvent(user));
  }
}
```

Running the example produces the following console output:

```
22:15:19.997 [main] INFO com.iluwatar.eda.handler.UserCreatedEventHandler -- User 'iluwatar' has been Created!
22:15:20.000 [main] INFO com.iluwatar.eda.handler.UserUpdatedEventHandler -- User 'iluwatar' has been Updated!
```

This example demonstrates the Event-Driven Architecture pattern, where the occurrence of events drives the flow of the program. The system is designed to respond to events as they occur, which allows for a high degree of flexibility and decoupling between components.

## [When to Use the Event-Driven Architecture Pattern in Java](https://java-design-patterns.com/patterns/event-driven-architecture/#when-to-use-the-event-driven-architecture-pattern-in-java)

Use an Event-driven architecture when

- Systems where change detection is crucial.
- Applications that require real-time features and reactive systems.
- Systems needing to efficiently handle high throughput and sporadic loads.
- When integrating with microservices to enhance agility and scalability.

## [Real-World Applications of Event-Driven Architecture Pattern in Java](https://java-design-patterns.com/patterns/event-driven-architecture/#real-world-applications-of-event-driven-architecture-pattern-in-java)

- Real-time data processing applications.
- Complex event processing systems in finance, such as stock trading platforms.
- IoT systems for dynamic device and information management.
- Chargify, a billing API, exposes payment activity through various events ( [https://docs.chargify.com/api-events](https://docs.chargify.com/api-events))
- Amazon's AWS Lambda, lets you execute code in response to events such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices. ( [https://aws.amazon.com/lambda](https://aws.amazon.com/lambda))
- MySQL runs triggers based on events such as inserts and update events happening on database tables.

## [Benefits and Trade-offs of Event-Driven Architecture Pattern](https://java-design-patterns.com/patterns/event-driven-architecture/#benefits-and-trade-offs-of-event-driven-architecture-pattern)

Benefits:

- Scalability: Efficiently processes fluctuating loads with asynchronous processing.
- Flexibility and Agility: New event types and event consumers can be added with minimal impact on existing components.
- Responsiveness: Improves responsiveness by decoupling event processing and state management.

Trade-offs:

- Complexity in Tracking: Can be challenging to debug and track due to loose coupling and asynchronous behaviors.
- Dependency on Messaging Systems: Heavily relies on robust messaging infrastructures.
- Event Consistency: Requires careful design to handle event ordering and consistency.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/event-driven-architecture/#related-java-design-patterns)

- Microservices Architecture: Often used together with EDA to enhance agility and scalability.
- Publish/Subscribe: A common pattern used within EDA for messaging between event producers and consumers.

## [References and Credits](https://java-design-patterns.com/patterns/event-driven-architecture/#references-and-credits)

- [Patterns of Enterprise Application Architecture](https://amzn.to/3Q3vBki)
- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/49Aljz0)
- [Reactive Messaging Patterns With the Actor Model: Applications and Integration in Scala and Akka](https://amzn.to/3UeoBUa)
- [What is an Event-Driven Architecture (Amazon)](https://aws.amazon.com/event-driven-architecture/)

---

## [architectural/event-sourcing] Event Sourcing
> 官方文档: https://java-design-patterns.com/patterns/event-sourcing/

ArchitecturalDecouplingEvent-drivenFault toleranceMessagingPersistenceScalabilityTransactionsAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/event-sourcing/#also-known-as)

- Event Logging
- Event Streaming

## [Intent of Event Sourcing Design Pattern](https://java-design-patterns.com/patterns/event-sourcing/#intent-of-event-sourcing-design-pattern)

Event Sourcing is a design pattern that advocates for the storage of state changes as a sequence of events. Instead of updating a record in a database, all changes are stored as individual events which, when replayed, can recreate the state of an application at any point in time.

## [Detailed Explanation of Event Sourcing Pattern with Real-World Examples](https://java-design-patterns.com/patterns/event-sourcing/#detailed-explanation-of-event-sourcing-pattern-with-real-world-examples)

Real-world example

> Consider a banking application that tracks all transactions for user accounts. In this system, every deposit, withdrawal, and transfer is recorded as an individual event in an event log. Instead of simply updating the current account balance, each transaction is stored as a discrete event. This approach allows the bank to maintain a complete and immutable history of all account activities. If a discrepancy occurs, the bank can replay the sequence of events to reconstruct the account state at any point in time. This provides a robust audit trail, facilitates debugging, and supports features like transaction rollback and historical data analysis.

In plain words

> Event Sourcing records all state changes as a sequence of immutable events to ensure reliable state reconstruction and auditability.

[Microsoft's documentation](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) says

> The Event Sourcing pattern defines an approach to handling operations on data that's driven by a sequence of events, each of which is recorded in an append-only store. Application code sends a series of events that imperatively describe each action that has occurred on the data to the event store, where they're persisted. Each event represents a set of changes to the data (such as AddedItemToOrder).

Architecture diagram

![Event Sourcing Architecture Diagram](https://java-design-patterns.com/assets/img/event-sourcing-architecture-diagram.e1de9c3e.png)

## [Programmatic Example of Event Sourcing Pattern in Java](https://java-design-patterns.com/patterns/event-sourcing/#programmatic-example-of-event-sourcing-pattern-in-java)

In the programmatic example we transfer some money between bank accounts.

The `Event` class manages a queue of events and controls thread operations for asynchronous processing. Each event can be seen as a state change that affects the state of the system.

```java
public class Event {
    private static final Event INSTANCE = new Event();

    private static final int MAX_PENDING = 16;

    private int headIndex;

    private int tailIndex;

    private volatile Thread updateThread = null;

    private final EventMessage[] pendingEvents = new EventMessage[MAX_PENDING];

    Event() {}

    public static Event getInstance() {
        return INSTANCE;
    }
}
```

The `triggerEvent` method is where the events are created. Each time an event is triggered, it is created and added to the queue. This event contains the details of the state change.

```java
public void triggerEvent(EventMessage eventMessage) {
    init();
    for(var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) {
        var pendingEvent = getPendingEvents()[i];
        if(pendingEvent.equals(eventMessage)) {
            return;
        }
    }
    getPendingEvents()[tailIndex] = eventMessage;
    tailIndex = (tailIndex + 1) % MAX_PENDING;
}
```

The `init` and `startThread` methods ensure the thread is properly initialized and running. The `stopService` method is used to stop the thread when it's no longer needed. These methods manage the lifecycle of the thread used to process the events.

```java
public synchronized void stopService() throws InterruptedException {
    if(updateThread != null) {
        updateThread.interrupt();
        updateThread.join();
        updateThread = null;
    }
}

public synchronized boolean isServiceRunning() {
    return updateThread != null && updateThread.isAlive();
}

public void init() {
    if(updateThread == null) {
        updateThread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                update();
            }
        });
        startThread();
    }
}

private synchronized void startThread() {
    if (!updateThread.isAlive()) {
        updateThread.start();
        headIndex = 0;
        tailIndex = 0;
    }
}
```

The example is driven by the `App` class and its `main` method.

```java
@Slf4j
public class App {

  public static final int ACCOUNT_OF_DAENERYS = 1;

  public static final int ACCOUNT_OF_JON = 2;

  public static void main(String[] args) {

    var eventProcessor = new DomainEventProcessor(new JsonFileJournal());

    LOGGER.info("Running the system first time............");
    eventProcessor.reset();

    LOGGER.info("Creating the accounts............");

    eventProcessor.process(new AccountCreateEvent(
        0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen"));

    eventProcessor.process(new AccountCreateEvent(
        1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow"));

    LOGGER.info("Do some money operations............");

    eventProcessor.process(new MoneyDepositEvent(
        2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000")));

    eventProcessor.process(new MoneyDepositEvent(
        3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100")));

    eventProcessor.process(new MoneyTransferEvent(
        4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS,
        ACCOUNT_OF_JON));

    LOGGER.info("...............State:............");
    LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString());
    LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString());

    LOGGER.info("At that point system had a shut down, state in memory is cleared............");
    AccountAggregate.resetState();

    LOGGER.info("Recover the system by the events in journal file............");

    eventProcessor = new DomainEventProcessor(new JsonFileJournal());
    eventProcessor.recover();

    LOGGER.info("...............Recovered State:............");
    LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString());
    LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString());
  }
}
```

Running the example produces the following console output.

```
22:40:47.982 [main] INFO com.iluwatar.event.sourcing.app.App -- Running the system first time............
22:40:47.984 [main] INFO com.iluwatar.event.sourcing.app.App -- Creating the accounts............
22:40:47.985 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here.
22:40:48.089 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here.
22:40:48.090 [main] INFO com.iluwatar.event.sourcing.app.App -- Do some money operations............
22:40:48.090 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here.
22:40:48.095 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here.
22:40:48.099 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here.
22:40:48.099 [main] INFO com.iluwatar.event.sourcing.domain.Account -- Some external api for only realtime execution could be called here.
22:40:48.101 [main] INFO com.iluwatar.event.sourcing.app.App -- ...............State:............
22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=1, owner='Daenerys Targaryen', money=90000}
22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=2, owner='Jon Snow', money=10100}
22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- At that point system had a shut down, state in memory is cleared............
22:40:48.104 [main] INFO com.iluwatar.event.sourcing.app.App -- Recover the system by the events in journal file............
22:40:48.124 [main] INFO com.iluwatar.event.sourcing.app.App -- ...............Recovered State:............
22:40:48.124 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=1, owner='Daenerys Targaryen', money=90000}
22:40:48.124 [main] INFO com.iluwatar.event.sourcing.app.App -- Account{accountNo=2, owner='Jon Snow', money=10100}
```

In this example, the state of the system can be recreated at any point by replaying the events in the queue. This is a key feature of the Event Sourcing pattern.

## [When to Use the Event Sourcing Pattern in Java](https://java-design-patterns.com/patterns/event-sourcing/#when-to-use-the-event-sourcing-pattern-in-java)

- In systems where complete audit trails and historical changes are crucial.
- In complex domains where the state of an application is derived from a series of changes.
- For systems that benefit from high availability and scalability as Event Sourcing naturally lends itself to distributed systems.

## [Real-World Applications of Event Sourcing Pattern in Java](https://java-design-patterns.com/patterns/event-sourcing/#real-world-applications-of-event-sourcing-pattern-in-java)

- Financial systems to track transactions and account balances over time.
- E-commerce applications for order and inventory management.
- Real-time data processing systems where event consistency and replayability are critical.
- [The LMAX Architecture](https://martinfowler.com/articles/lmax.html)

## [Benefits and Trade-offs of Event Sourcing Pattern](https://java-design-patterns.com/patterns/event-sourcing/#benefits-and-trade-offs-of-event-sourcing-pattern)

Benefits:

- Auditability: Each change to the state is recorded, allowing for comprehensive auditing.
- Replayability: Events can be reprocessed to recreate historical states or move to new states.
- Scalability: Events can be processed asynchronously and in parallel.

Trade-offs

- Complexity: Implementing and maintaining an event-sourced system can introduce additional complexity.
- Event store size: Storing every state change can lead to large data volumes.
- Event versioning: Changes in event structure over time require careful handling to ensure system integrity.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/event-sourcing/#related-java-design-patterns)

- [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/cqrs/): Often used together with Event Sourcing to separate read and write responsibilities, enhancing performance and scalability.
- Snapshot: Used to optimize Event Sourcing systems by periodically saving the current state to avoid replaying a long sequence of events.

## [References and Credits](https://java-design-patterns.com/patterns/event-sourcing/#references-and-credits)

- [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/443WfiS)
- [Implementing Domain-Driven Design](https://amzn.to/3JgvA8V)
- [Patterns, Principles, and Practices of Domain-Driven Design](https://amzn.to/3VVhfWX)
- [Event Sourcing (Martin Fowler)](https://martinfowler.com/eaaDev/EventSourcing.html)
- [Event Sourcing pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)

---

## [architectural/flux] Flux
> 官方文档: https://java-design-patterns.com/patterns/flux/

ArchitecturalClient-serverDecouplingEvent-drivenPublish/subscribeReactiveAbout 3 min

* * *

## [Intent of Flux Design Pattern](https://java-design-patterns.com/patterns/flux/#intent-of-flux-design-pattern)

The Flux design pattern is intended to manage the flow of data in Java applications, particularly client-side web applications, by enforcing a unidirectional data flow. It aims to simplify the management of complex data interactions and promote a more predictable state behavior across components.

## [Detailed Explanation of Flux Pattern with Real-World Examples](https://java-design-patterns.com/patterns/flux/#detailed-explanation-of-flux-pattern-with-real-world-examples)

Real-world example

> Consider a busy restaurant kitchen as an analogy for the Flux design pattern. In this scenario, the kitchen operates based on customer orders (actions) received and processed through a single point of control (the dispatcher), which could be represented by the head chef. When an order arrives, the head chef assigns specific tasks to various sections of the kitchen (stores), such as the grill, the salad station, or the dessert team. Each section updates the progress of their tasks (state changes) back to the head chef, who ensures that all parts of the order are coordinated and completed in a synchronized manner before the dishes are sent out to the customer (the view).

In plain words

> The Flux design pattern manages data flow in applications through a unidirectional architecture, coordinating actions, dispatchers, stores, and views to ensure stable and predictable state management. This pattern is particularly useful in Java design patterns for developing responsive client-side web applications.

Wikipedia says

> To support React's concept of unidirectional data flow (which might be contrasted with AngularJS's bidirectional flow), the Flux architecture was developed as an alternative to the popular model–view–controller architecture. Flux features actions which are sent through a central dispatcher to a store, and changes to the store are propagated back to the view.

Architecture diagram

![Flux Architecture Diagram](https://java-design-patterns.com/assets/img/flux-architecture-diagram.5c769cd1.png)

## [Programmatic Example of Flux Pattern in Java](https://java-design-patterns.com/patterns/flux/#programmatic-example-of-flux-pattern-in-java)

The Flux design pattern is used for building client-side web applications. It advocates for a unidirectional data flow. When a user interacts with a view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all the views that are affected.

In the provided code, we can see an example of the Flux pattern in the `App` and `MenuStore` classes.

The `App` class is the entry point of the application. It initializes and wires the system, registers the stores with the dispatcher, registers the views with the stores, and triggers the initial rendering of the views. When a menu item is clicked, it triggers events through the dispatcher.

```java
public class App {

  public static void main(String[] args) {

    var menuStore = new MenuStore();
    Dispatcher.getInstance().registerStore(menuStore);
    var contentStore = new ContentStore();
    Dispatcher.getInstance().registerStore(contentStore);
    var menuView = new MenuView();
    menuStore.registerView(menuView);
    var contentView = new ContentView();
    contentStore.registerView(contentView);

    menuView.render();
    contentView.render();

    menuView.itemClicked(MenuItem.COMPANY);
  }
}
```

The `MenuStore` class is a concrete store that holds the state of the menu. It updates its state and notifies the views when it receives an action from the dispatcher.

```java
public class MenuStore extends Store {

  @Getter
  private MenuItem selected = MenuItem.HOME;

  @Override
  public void onAction(Action action) {
    if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
      var menuAction = (MenuAction) action;
      selected = menuAction.getMenuItem();
      notifyChange();
    }
  }
}
```

In this example, when a menu item is clicked, the `MenuView` triggers a `MENU_ITEM_SELECTED` action. The `Dispatcher` forwards this action to all registered stores. The `MenuStore` handles this action by updating its state and notifying its views, causing them to rerender with the new state.

This is a basic example of the Flux pattern, where actions are dispatched from the views, handled by the stores, and cause the views to update.

## [When to Use the Flux Pattern in Java](https://java-design-patterns.com/patterns/flux/#when-to-use-the-flux-pattern-in-java)

Flux is applicable in developing client-side Java applications, where maintaining consistent data across various components and managing complex state interactions are critical. It is especially suited for applications with dynamic user interfaces that react to frequent data updates.

## [Real-World Applications of Flux Pattern in Java](https://java-design-patterns.com/patterns/flux/#real-world-applications-of-flux-pattern-in-java)

- Facebook extensively uses the Flux design pattern in conjunction with React to build robust, scalable user interfaces that can handle complex data updates efficiently.
- Many modern web applications adopt Flux or its variations (like Redux) to manage state in environments that demand high responsiveness and predictability.

## [Benefits and Trade-offs of Flux Pattern](https://java-design-patterns.com/patterns/flux/#benefits-and-trade-offs-of-flux-pattern)

Benefits:

- Ensures a unidirectional data flow that simplifies debugging and testing.
- Enhances consistency across the application by centralizing the application state.
- Improves the predictability of data flow and interaction in large applications.

Trade-offs:

- Can introduce boilerplate and complexity in smaller applications.
- May require a learning curve to understand the pattern's architecture and its implementation nuances.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/flux/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Flux's dispatcher component acts similarly to an observer, managing notifications about data changes to various stores.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Typically, the dispatcher in Flux is implemented as a singleton.
- [Mediator](https://java-design-patterns.com/patterns/mediator/): Flux can be considered a variation of the mediator pattern where the dispatcher mediates the flow of data and ensures components do not update the state directly.

## [References and Credits](https://java-design-patterns.com/patterns/flux/#references-and-credits)

- [Learning React: Modern Patterns for Developing React Apps](https://amzn.to/3Qdn9Pg)
- [Pro React](https://amzn.to/3xNRttK)

---

## [architectural/front-controller] Front Controller
> 官方文档: https://java-design-patterns.com/patterns/front-controller/

ArchitecturalArchitectureDecouplingEnterprise patternsLayered architectureWeb developmentAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/front-controller/#also-known-as)

- Centralized Request Handling

## [Intent of Front Controller Design Pattern](https://java-design-patterns.com/patterns/front-controller/#intent-of-front-controller-design-pattern)

The Front Controller design pattern aims to provide a centralized entry point for handling all incoming web requests. This pattern ensures consistent and efficient request routing and management across a Java web application.

## [Detailed Explanation of Front Controller Pattern with Real-World Examples](https://java-design-patterns.com/patterns/front-controller/#detailed-explanation-of-front-controller-pattern-with-real-world-examples)

Real-world example

> In a real-world scenario, a front desk in a hotel serves as the centralized request handling point, similar to how the Front Controller design pattern functions in web application architecture. This desk acts as the "front controller" of the hotel, responsible for receiving all inquiries, from room service orders to maintenance requests. The receptionist assesses each request and routes it to the appropriate department—housekeeping, the kitchen, or maintenance. This system centralizes request handling, ensuring that guest needs are addressed efficiently and consistently, similar to how a Front Controller in a software application manages all incoming requests and delegates them to specific handlers.

In plain words

> The Front Controller design pattern centralizes incoming web requests into a single handling point, allowing consistent processing and delegation across an application.

Wikipedia says

> The front controller software design pattern is listed in several pattern catalogs and is related to the design of web applications. It is "a controller that handles all requests for a website", which is a useful structure for web application developers to achieve flexibility and reuse without code redundancy.

Architecture diagram

![Front Controller Architecture Diagram](https://java-design-patterns.com/assets/img/front-controller-architecture-diagram.9a7632b7.png)

## [Programmatic Example of Front Controller Pattern in Java](https://java-design-patterns.com/patterns/front-controller/#programmatic-example-of-front-controller-pattern-in-java)

The Front Controller design pattern is a pattern that provides a centralized entry point for handling all requests in a web application. It ensures that request handling is managed consistently and efficiently across an application.

In the provided code, we can see an example of the Front Controller pattern in the `App`, `FrontController` and `Dispatcher` classes.

The `App` class is the entry point of the application. It creates an instance of `FrontController` and uses it to handle various requests.

```java
public class App {

  public static void main(String[] args) {
    var controller = new FrontController();
    controller.handleRequest("Archer");
    controller.handleRequest("Catapult");
    controller.handleRequest("foobar");
  }
}
```

The `FrontController` class is the front controller in this example. It handles all requests and delegates them to the `Dispatcher`.

```java
public class FrontController {

    private final Dispatcher dispatcher;

    public FrontController() {
        this.dispatcher = new Dispatcher();
    }

    public void handleRequest(String request) {
        dispatcher.dispatch(request);
    }
}
```

The `Dispatcher` class is responsible for handling the dispatching of requests to the appropriate command. It retrieves the corresponding command based on the request and invokes the command's process method to handle the business logic.

```java
public class Dispatcher {

  public void dispatch(String request) {
    var command = getCommand(request);
    command.process();
  }

  Command getCommand(String request) {
    var commandClass = getCommandClass(request);
    try {
      return (Command) commandClass.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      throw new ApplicationException(e);
    }
  }

  static Class<?> getCommandClass(String request) {
    try {
      return Class.forName("com.iluwatar.front.controller." + request + "Command");
    } catch (ClassNotFoundException e) {
      return UnknownCommand.class;
    }
  }
}
```

In this example, when a request is received, the `FrontController` delegates the request to the `Dispatcher`, which creates a command object based on the request and calls its `process` method. The command object is responsible for handling the request and rendering the appropriate view.

This is a basic example of the Front Controller pattern, where all requests are handled by a single controller and dispatcher, ensuring consistent and efficient request handling.

## [When to Use the Front Controller Pattern in Java](https://java-design-patterns.com/patterns/front-controller/#when-to-use-the-front-controller-pattern-in-java)

- The Front Controller design pattern is particularly useful for Java web applications that require a centralized mechanism for request handling.
- Systems that need a common processing point for all requests to perform tasks such as authentication, logging, and routing.

## [Real-World Applications of Front Controller Pattern in Java](https://java-design-patterns.com/patterns/front-controller/#real-world-applications-of-front-controller-pattern-in-java)

- [Apache Struts](https://struts.apache.org/)
- Java web frameworks like Spring MVC and JavaServer Faces (JSF) implement the Front Controller pattern through their central dispatcher servlet, which manages web requests and delegates responsibilities.

## [Benefits and Trade-offs of Front Controller Pattern](https://java-design-patterns.com/patterns/front-controller/#benefits-and-trade-offs-of-front-controller-pattern)

Benefits:

- The main benefit of the Front Controller design pattern is the centralization of request handling, which simplifies maintenance and ensures consistent behavior across the application.
- Eases the integration of services like security and user session management.
- Facilitates common behavior like routing, logging, and authentication across requests.

Trade-offs:

- Can become a bottleneck if not properly managed.
- Increases complexity in the dispatcher controller, requiring careful design to avoid tight coupling.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/front-controller/#related-java-design-patterns)

- [Page Controller](https://java-design-patterns.com/patterns/page-controller/): Front Controller can delegate requests to Page Controllers, which handle specific page requests. This division supports the Single Responsibility Principle.
- [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Front Controller acts as the controller, managing the flow between model and view.
- [Command](https://java-design-patterns.com/patterns/command/): Can be used to encapsulate a request as an object, which the Front Controller can manipulate and delegate.

## [References and Credits](https://java-design-patterns.com/patterns/front-controller/#references-and-credits)

- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [architectural/hexagonal-architecture] Hexagonal Architecture
> 官方文档: https://java-design-patterns.com/patterns/hexagonal-architecture/

ArchitecturalDecouplingLayered architectureAbout 6 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/hexagonal-architecture/#also-known-as)

- Ports and Adapters

## [Intent of Hexagonal Architecture Design Pattern](https://java-design-patterns.com/patterns/hexagonal-architecture/#intent-of-hexagonal-architecture-design-pattern)

Hexagonal Architecture, also known as Ports and Adapters, is a design pattern in Java that promotes decoupling of core business logic from external interfaces like databases and user interfaces. This architectural approach enhances maintainability and testability of software systems.

## [Detailed Explanation of Hexagonal Architecture Pattern with Real-World Examples](https://java-design-patterns.com/patterns/hexagonal-architecture/#detailed-explanation-of-hexagonal-architecture-pattern-with-real-world-examples)

Real-world example

> In online banking systems, Hexagonal Architecture allows core banking logic to remain unaffected by changes in user interfaces or third-party services. This decoupling ensures the system's maintainability and flexibility. In such systems, the core banking logic (like processing transactions, managing accounts, and calculating interest) represents the application's core. This core is then surrounded by various adapters that allow the system to interact with different external interfaces without affecting the business logic. For instance, customers might access their accounts through a web interface, a mobile app, or even through ATM services. Meanwhile, the banking system also needs to interface with external services for credit checks, fraud detection, and interbank transactions. Each of these interfaces interacts with the core banking logic through specific adapters designed to translate the external calls to and from the application's internal APIs. This setup allows the bank to modify or extend its external interfaces without having to alter the core business logic, enhancing flexibility and maintainability.

In plain words

> Hexagonal Architecture organizes an application into a central core of business logic surrounded by ports and adapters that manage interactions with external systems like user interfaces and databases, allowing the core to remain independent of external concerns.

Wikipedia says

> The hexagonal architecture, or ports and adapters architecture, is an architectural pattern used in software design. It aims at creating loosely coupled application components that can be easily connected to their software environment by means of ports and adapters. This makes components exchangeable at any level and facilitates test automation.

Architecture diagram

![Hexagonal Architecture Diagram](https://java-design-patterns.com/assets/img/hexagonal-architecture-diagram.057a8c09.png)

## [Programmatic Example of Hexagonal Architecture Pattern in Java](https://java-design-patterns.com/patterns/hexagonal-architecture/#programmatic-example-of-hexagonal-architecture-pattern-in-java)

The Hexagonal Architecture, also known as Ports and Adapters, is a design pattern that aims to create a loosely coupled application where the core business logic is isolated from external interfaces like databases, user interfaces, or third-party services. This allows the core application to be independent and easily testable.

The Java code example below illustrates how Hexagonal Architecture isolates core business logic using dependency injection, making the application highly testable and independent from external components.

In the provided code, we can see an example of the Hexagonal Architecture pattern in the `App` class and the use of Google's Guice for dependency injection.

The `App` class is the entry point of the application. It creates an instance of `LotteryAdministration` and `LotteryService` through dependency injection and uses them to handle various tasks.

```java
public class App {

  public static void main(String[] args) {

    var injector = Guice.createInjector(new LotteryTestingModule());

    // start new lottery round
    var administration = injector.getInstance(LotteryAdministration.class);
    administration.resetLottery();

    // submit some lottery tickets
    var service = injector.getInstance(LotteryService.class);
    SampleData.submitTickets(service, 20);

    // perform lottery
    administration.performLottery();
  }
}
```

The `LotteryAdministration` class is responsible for managing the lottery rounds. It has methods to start a new round, perform the lottery, and reset the lottery.

```java
public class LotteryAdministration {

  private final LotteryTicketRepository repository;
  private final LotteryEventLog notifications;
  private final WireTransfers wireTransfers;

  @Inject
  public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications,
                               WireTransfers wireTransfers) {
    this.repository = repository;
    this.notifications = notifications;
    this.wireTransfers = wireTransfers;
  }

  public Map<LotteryTicketId, LotteryTicket> getAllSubmittedTickets() {
    return repository.findAll();
  }

  public LotteryNumbers performLottery() {
    // Implementation details...
  }

  public void resetLottery() {
    repository.deleteAll();
  }
}
```

The `LotteryService` class is responsible for managing the lottery tickets. It has methods to submit a ticket, check a ticket's status, and get the winning ticket.

```java
public class LotteryService {

  private final LotteryTicketRepository repository;
  private final LotteryEventLog notifications;
  private final WireTransfers wireTransfers;

  @Inject
  public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications,
                        WireTransfers wireTransfers) {
    this.repository = repository;
    this.notifications = notifications;
    this.wireTransfers = wireTransfers;
  }

  public Optional<LotteryTicketId> submitTicket(LotteryTicket ticket) {
    // Implementation details...
  }

  public LotteryTicketCheckResult checkTicketForPrize(
      LotteryTicketId id,
      LotteryNumbers winningNumbers
  ) {
    // Implementation details...
  }
}
```

Running the main function of App class produces the following output:

```
11:06:58.357 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was submitted. Bank account 334-746 was charged for 3 credits.
11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for arnold@google.com was submitted. Bank account 114-988 was charged for 3 credits.
11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ollie@google.com was submitted. Bank account 190-045 was charged for 3 credits.
11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for peter@google.com was submitted. Bank account 335-886 was charged for 3 credits.
11:06:58.359 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ray@google.com was submitted. Bank account 843-073 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was submitted. Bank account 334-746 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lisa@google.com was submitted. Bank account 024-653 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for harriet@google.com was submitted. Bank account 842-404 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com was submitted. Bank account 734-853 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lars@google.com was submitted. Bank account 746-936 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for tyron@google.com was submitted. Bank account 310-992 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for xavier@google.com was submitted. Bank account 143-947 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for kevin@google.com was submitted. Bank account 453-936 was charged for 3 credits.
11:06:58.360 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for yngwie@google.com was submitted. Bank account 241-465 was charged for 3 credits.
11:06:58.361 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was submitted. Bank account 334-746 was charged for 3 credits.
11:06:58.361 [main] ERROR com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com could not be submitted because the credit transfer of 3 credits failed.
11:06:58.362 [main] ERROR com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com could not be submitted because the credit transfer of 3 credits failed.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for mary@google.com was submitted. Bank account 234-987 was charged for 3 credits.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for edwin@google.com was submitted. Bank account 895-345 was charged for 3 credits.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for jacob@google.com was submitted. Bank account 444-766 was charged for 3 credits.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ollie@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for jacob@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for peter@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for ray@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lisa@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for harriet@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for larry@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for lars@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for tyron@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for xavier@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for kevin@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for yngwie@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for calvin@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for mary@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for arnold@google.com was checked and unfortunately did not win this time.
11:06:58.362 [main] INFO com.iluwatar.hexagonal.eventlog.StdOutEventLog -- Lottery ticket for edwin@google.com was checked and unfortunately did not win this time.
```

In this example, the `LotteryAdministration` and `LotteryService` classes are the core of the application. They interact with external interfaces like `LotteryTicketRepository`, `LotteryEventLog`, and `WireTransfers` through dependency injection, keeping the core business logic decoupled from external concerns. This is a basic example of the Hexagonal Architecture pattern, where the core application is at the center of input/output systems.

## [When to Use the Hexagonal Architecture Pattern in Java](https://java-design-patterns.com/patterns/hexagonal-architecture/#when-to-use-the-hexagonal-architecture-pattern-in-java)

Hexagonal Architecture is particularly beneficial in scenarios:

- The application needs to interact with multiple external systems.
- There is a requirement for high testability and maintainability.
- The application should remain unaffected by changes in external interfaces.

## [Real-World Applications of Hexagonal Architecture Pattern in Java](https://java-design-patterns.com/patterns/hexagonal-architecture/#real-world-applications-of-hexagonal-architecture-pattern-in-java)

- Implemented extensively within enterprise applications that leverage frameworks like Spring.
- Used in microservices architectures to maintain clear boundaries and protocols between services.
- Adopted in systems that require integration with various databases or external APIs without impacting the business logic.

## [Benefits and Trade-offs of Hexagonal Architecture Pattern](https://java-design-patterns.com/patterns/hexagonal-architecture/#benefits-and-trade-offs-of-hexagonal-architecture-pattern)

Benefits:

- Improved Testability: Allows the core functionality to be tested independently of external components.
- Flexibility: Facilitates the addition or replacement of components that interact with the application without modifying the core business logic.
- Maintainability: Reduces dependencies on external interfaces, simplifying upgrades and maintenance.

Trade-offs:

- Complexity: Introduces more abstractions and layers, which can complicate the system design and understanding.
- Overhead: Might be an over-engineering for simple applications, where simpler architectural patterns could suffice.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/hexagonal-architecture/#related-java-design-patterns)

- [Layered Architecture](https://java-design-patterns.com/patterns/layers/): Shares the concept of organizing code into responsibilities; however, Hexagonal emphasizes port-based interaction with external elements.
- Microservices: Often used in conjunction with Hexagonal Architecture to define clear boundaries and protocols between services.

## [References and Credits](https://java-design-patterns.com/patterns/hexagonal-architecture/#references-and-credits)

- [Implementing Domain-Driven Design](https://amzn.to/4dmBjrB)
- [Building Microservices](https://amzn.to/3UACtrU)

---

## [architectural/intercepting-filter] Intercepting Filter
> 官方文档: https://java-design-patterns.com/patterns/intercepting-filter/

ArchitecturalAPI designDecouplingLayered architecturePerformanceSecurityWeb developmentAbout 3 min

* * *

## [Intent of Intercepting Filter Design Pattern](https://java-design-patterns.com/patterns/intercepting-filter/#intent-of-intercepting-filter-design-pattern)

The Intercepting Filter Pattern in Java is a powerful design pattern that allows for efficient web request handling. This pattern enables the application of multiple filters in a filter chain to process and modify requests and responses.

## [Detailed Explanation of Intercepting Filter Pattern with Real-World Examples](https://java-design-patterns.com/patterns/intercepting-filter/#detailed-explanation-of-intercepting-filter-pattern-with-real-world-examples)

Real-world example

> Consider entering a secure office building where you pass through several checkpoints: a security desk checks your ID, a metal detector ensures safety, and a registration desk logs your visit. Each checkpoint acts like a filter in the Intercepting Filter pattern, processing and validating your entry step-by-step, similar to how filters handle different aspects of web requests and responses in a software system.

In plain words

> The Intercepting Filter design pattern allows you to define processing steps (filters) that execute sequentially to handle and modify web requests and responses before they reach the application or are sent to the client.

Wikipedia says

> Intercepting Filter is a Java pattern which creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code.

Architecture diagram

![Intercepting Filter Architecture Diagram](https://java-design-patterns.com/assets/img/intercepting-filter-architecture-diagram.5ac8018b.png)

## [Programmatic Example of Intercepting Filter Pattern in Java](https://java-design-patterns.com/patterns/intercepting-filter/#programmatic-example-of-intercepting-filter-pattern-in-java)

In this article, we delve into the Intercepting Filter Pattern and provide a Java example to illustrate its use. This pattern is essential for Java web development, offering a modular approach to handling common services such as logging, authentication, and data compression.

The Java implementation of the Intercepting Filter Pattern includes classes like `FilterManager` and `Client`, which facilitate the management and application of filters. Each filter in the chain performs specific tasks, ensuring a clean and efficient design.

The `App` class is the entry point of the application. It creates an instance of `FilterManager`, adds various filters to it, and sets it to a `Client`.

```java
public class App {

  public static void main(String[] args) {
    var filterManager = new FilterManager();
    filterManager.addFilter(new NameFilter());
    filterManager.addFilter(new ContactFilter());
    filterManager.addFilter(new AddressFilter());
    filterManager.addFilter(new DepositFilter());
    filterManager.addFilter(new OrderFilter());

    var client = new Client();
    client.setFilterManager(filterManager);
  }
}
```

The `FilterManager` class manages the filters and applies them to the requests.

```java
public class FilterManager {
  private final List<Filter> filters = new ArrayList<>();

  public void addFilter(Filter filter) {
    filters.add(filter);
  }

  public void filterRequest(String request) {
    for (Filter filter : filters) {
      filter.execute(request);
    }
  }
}
```

The `Client` class sends the request to the `FilterManager`.

```java
public class Client {
  private FilterManager filterManager;

  public void setFilterManager(FilterManager filterManager) {
    this.filterManager = filterManager;
  }

  public void sendRequest(String request) {
    filterManager.filterRequest(request);
  }
}
```

The `Filter` interface and its implementations (`NameFilter`, `ContactFilter`, `AddressFilter`, `DepositFilter`, `OrderFilter`) define the filters that can be applied to the requests.

```java
public interface Filter {
  void execute(String request);
}

public class NameFilter extends AbstractFilter {

    @Override
    public String execute(Order order) {
        var result = super.execute(order);
        var name = order.getName();
        if (name == null || name.isEmpty() || name.matches(".*[^\\w|\\s]+.*")) {
            return result + "Invalid name! ";
        } else {
            return result;
        }
    }
}

// Other Filter implementations...
```

In this example, the `App` class sets up a `FilterManager` with various filters and assigns it to a `Client`. When the `Client` sends a request, the `FilterManager` applies all the filters to the request. This is a basic example of the Intercepting Filter pattern, where common processing tasks are encapsulated in filters and applied to requests in a standard manner.

## [When to Use the Intercepting Filter Pattern in Java](https://java-design-patterns.com/patterns/intercepting-filter/#when-to-use-the-intercepting-filter-pattern-in-java)

Use the Intercepting Filter pattern when

- In Java web applications to manage cross-cutting concerns.
- When you need to apply pre-processing and post-processing steps to requests and responses, typically in web applications.
- Suitable for handling cross-cutting concerns such as logging, authentication, data compression, and encryption transparently.

## [Intercepting Filter Pattern Java Tutorials](https://java-design-patterns.com/patterns/intercepting-filter/#intercepting-filter-pattern-java-tutorials)

- [Introduction to Intercepting Filter Pattern in Java (Baeldung)](https://www.baeldung.com/intercepting-filter-pattern-in-java)
- [Design Pattern - Intercepting Filter Pattern (TutorialsPoint)](http://www.tutorialspoint.com/design_pattern/intercepting_filter_pattern.htm)

## [Real-World Applications of Intercepting Filter Pattern in Java](https://java-design-patterns.com/patterns/intercepting-filter/#real-world-applications-of-intercepting-filter-pattern-in-java)

- Frameworks like Spring MVC and web servers such as Apache Tomcat utilize the Intercepting Filter Pattern to enhance Java web development. This pattern's ability to centralize control and streamline web request handling makes it a go-to choice for developers.
- [javax.servlet.FilterChain](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/FilterChain.html) and [javax.servlet.Filter](https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/Filter.html)
- [Struts 2 - Interceptors](https://struts.apache.org/core-developers/interceptors.html)

## [Benefits and Trade-offs of Intercepting Filter Pattern](https://java-design-patterns.com/patterns/intercepting-filter/#benefits-and-trade-offs-of-intercepting-filter-pattern)

Benefits:

- Promotes separation of concerns by allowing filters to be independently developed, tested, and reused.
- Enhances flexibility through configurable filter chains.
- Simplifies application maintenance by centralizing control in filter management.

Trade-offs:

- Introducing many filters can lead to performance overhead due to the processing of each request and response through multiple filters.
- Debugging and tracing the request flow through multiple filters can be complex.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/intercepting-filter/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): Filters in the Intercepting Filter pattern can be considered as decorators that add additional responsibilities to request handling. They modify the request/response without altering their fundamental behavior.
- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Filters are linked in a chain, where each filter processes the request or response and optionally passes it to the next filter in the chain, similar to how responsibilities are passed along in the Chain of Responsibility pattern.

## [References and Credits](https://java-design-patterns.com/patterns/intercepting-filter/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [architectural/layered-architecture] Layered Architecture
> 官方文档: https://java-design-patterns.com/patterns/layered-architecture/

ArchitecturalAbstractionDecouplingEnterprise patternsLayered architectureScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/layered-architecture/#also-known-as)

- N-Tier Architecture

## [Intent of Layered Architecture Design Pattern](https://java-design-patterns.com/patterns/layered-architecture/#intent-of-layered-architecture-design-pattern)

The Layered Architecture design pattern helps organize applications into groups of subtasks at different levels of abstraction, facilitating independent development and maintenance of each layer.

## [Detailed Explanation of Layered Architecture Pattern with Real-World Examples](https://java-design-patterns.com/patterns/layered-architecture/#detailed-explanation-of-layered-architecture-pattern-with-real-world-examples)

Real-world example

> Imagine constructing a modern high-rise building, analogous to using the Layered Architecture design pattern in software development. This pattern allows each software layer, such as the data layer, service layer, and presentation layer, to support seamless interaction while maintaining independence, enhancing maintainability and scalability. Just as a building is divided into layers such as the foundation, structural floors, residential floors, and the rooftop, each with specific functions and built using different materials and techniques, a software application can be similarly structured.
>
> In this analogy, the foundation represents the data layer, responsible for managing database operations. The structural floors are akin to the service layer, which contains business logic and rules. The residential floors parallel the presentation layer, which deals with user interfaces and interactions. Finally, the rooftop could be seen as the API layer, allowing external systems to communicate with the application.
>
> Just as each floor in a building is constructed to support the layers above and below, each software layer supports seamless interaction with its neighboring layers while maintaining a degree of independence. This structure allows for easy maintenance and updates, such as refurbishing the interiors (presentation layer) without affecting the underlying structures (business logic and data layers).

In plain words

> The Layered Architecture pattern organizes software into hierarchical groups of tasks, each encapsulated in distinct layers that interact with each other, facilitating ease of maintenance, scalability, and clear separation of concerns.

Wikipedia says

> In software engineering, multitier architecture (often referred to as n-tier architecture) or multilayered architecture is a client–server architecture in which presentation, application processing, and data management functions are physically separated.

Architecture diagram

![Layered Architecture Diagram](https://java-design-patterns.com/assets/img/layered-architecture-diagram.706e02d1.png)

## [Programmatic Example of Layered Architecture in Java](https://java-design-patterns.com/patterns/layered-architecture/#programmatic-example-of-layered-architecture-in-java)

On the data layer, we keep our cake building blocks. `Cake` consist of layers and topping.

```java
@Entity
public class Cake {
  @Id
  @GeneratedValue
  private Long id;
  @OneToOne(cascade = CascadeType.REMOVE)
  private CakeTopping topping;
  @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
  private Set<CakeLayer> layers;
}
```

The service layer offers `CakeBakingService` for easy access to different aspects of cakes.

```java
public interface CakeBakingService {
  void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException;
  List<CakeInfo> getAllCakes();
  void saveNewTopping(CakeToppingInfo toppingInfo);
  List<CakeToppingInfo> getAvailableToppings();
  void saveNewLayer(CakeLayerInfo layerInfo);
  List<CakeLayerInfo> getAvailableLayers();
}
```

On the top we have our `View` responsible for rendering the cakes.

```java
public interface View {
  void render();
}
@Slf4j
public class CakeViewImpl implements View {
  private final CakeBakingService cakeBakingService;
  public CakeViewImpl(CakeBakingService cakeBakingService) {
    this.cakeBakingService = cakeBakingService;
  }
  public void render() {
    cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString()));
  }
}
```

## [When to Use the Layered Architecture Pattern in Java](https://java-design-patterns.com/patterns/layered-architecture/#when-to-use-the-layered-architecture-pattern-in-java)

This pattern is suitable for structuring applications that can be divided into groups where each group has a specific role or responsibility. Common in enterprise applications, it simplifies dependencies, enhances maintainability, and supports scaling and technology stack segregation.

Use the Layers architecture when

- You want clearly divide software responsibilities into different parts of the program.
- You want to prevent a change from propagating throughout the application.
- You want to make your application more maintainable and testable.

## [Real-World Applications of Layered Architecture Pattern in Java](https://java-design-patterns.com/patterns/layered-architecture/#real-world-applications-of-layered-architecture-pattern-in-java)

- Web applications where the presentation, business logic, and data access layers are distinctly separated.
- Enterprise systems where core functionalities are isolated from interface applications and databases.

## [Benefits and Trade-offs of Layered Architecture Pattern](https://java-design-patterns.com/patterns/layered-architecture/#benefits-and-trade-offs-of-layered-architecture-pattern)

Benefits

- Improved manageability with separation of concerns
- Easier to update or modify one layer without affecting others
- Promotes reuse of functionalities.

Trade-offs

- Potential performance overhead due to layer interaction
- Complexity in layer management
- Challenges in designing an effective layer distribution.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/layered-architecture/#related-java-design-patterns)

- [Model-View-Controller](https://java-design-patterns.com/patterns/model-view-controller/): Shares separation of concerns by dividing application into input, processing, and output. Layered Architecture often implements an MVC within its presentation layer.
- Service-Oriented Architecture (SOA): Both patterns emphasize modularization but SOA focuses more on distributed services that can be reused across different systems.

## [References and Credits](https://java-design-patterns.com/patterns/layered-architecture/#references-and-credits)

- [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://amzn.to/3UoKkaR)
- [Java Design Pattern Essentials](https://amzn.to/4drLhHU)
- [Pattern-Oriented Software Architecture Volume 1: A System of Patterns](https://amzn.to/3xZ1ELU)

---

## [architectural/microservices-aggregrator] Microservices Aggregator
> 官方文档: https://java-design-patterns.com/patterns/microservices-aggregrator/

ArchitecturalAPI designClient-serverData processingDecouplingIntegrationMicroservicesScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/microservices-aggregrator/#also-known-as)

- API Composition

## [Intent of Microservices Aggregator Design Pattern](https://java-design-patterns.com/patterns/microservices-aggregrator/#intent-of-microservices-aggregator-design-pattern)

The Microservices Aggregator pattern helps aggregate responses from multiple microservices into a single unified response, optimizing client-server interactions in scalable systems.

## [Detailed Explanation of Microservices Aggregator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/microservices-aggregrator/#detailed-explanation-of-microservices-aggregator-pattern-with-real-world-examples)

Real-world example

> In a travel booking platform, an Aggregator Microservice consolidates data from flights, hotels, and car rentals microservices, providing a seamless user experience and enhancing scalability. Instead of the user making separate requests to each service, the platform employs an Aggregator Microservice. This microservice calls each of these services, collects their responses, and then consolidates the information into a single, unified response that is sent back to the user. This simplifies the user experience by providing all necessary travel details in one place and reduces the number of direct interactions the user needs to have with the underlying services.

In plain words

> Microservices Aggregator collects pieces of data from various microservices and returns an aggregate for processing.

Stack Overflow says

> Microservices Aggregator invokes multiple services to achieve the functionality required by the application.

Architecture diagram

![Microservices Aggregator Architecture Diagram](https://java-design-patterns.com/assets/img/microservices-aggregator-architecture-diagram.826e0cf3.png)

## [Programmatic Example of Microservices Aggregator Pattern in Java](https://java-design-patterns.com/patterns/microservices-aggregrator/#programmatic-example-of-microservices-aggregator-pattern-in-java)

Our web marketplace utilizes an Aggregator microservice to fetch combined product and inventory information from separate microservices, ensuring efficient data processing and improved system performance.

Let's start from the data model. Here's our `Product`.

```java
public class Product {
    private String title;
    private int productInventories;
    // Other properties and methods...
}
```

Next we can introduce our `Aggregator` microservice. It contains clients `ProductInformationClient` and `ProductInventoryClient` for calling respective microservices.

```java

@RestController
public class Aggregator {

    @Resource
    private ProductInformationClient informationClient;

    @Resource
    private ProductInventoryClient inventoryClient;

    @RequestMapping(path = "/product", method = RequestMethod.GET)
    public Product getProduct() {

        var product = new Product();
        var productTitle = informationClient.getProductTitle();
        var productInventory = inventoryClient.getProductInventories();

        //Fallback to error message
        product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed"));

        //Fallback to default error inventory
        product.setProductInventories(requireNonNullElse(productInventory, -1));

        return product;
    }
}
```

Here's the essence of information microservice implementation. Inventory microservice is similar, it just returns inventory counts.

```java

@RestController
public class InformationController {
    @RequestMapping(value = "/information", method = RequestMethod.GET)
    public String getProductTitle() {
        return "The Product Title.";
    }
}
```

Now calling our `Aggregator` REST API returns the product information.

```bash
# Example bash call
curl http://localhost:50004/product

# Example output
{"title":"The Product Title.","productInventories":5}
```

## [When to Use the Microservices Aggregator Pattern in Java](https://java-design-patterns.com/patterns/microservices-aggregrator/#when-to-use-the-microservices-aggregator-pattern-in-java)

The Microservices Aggregator pattern is ideal for scenarios requiring composite responses from multiple microservices, such as in e-commerce and dashboard applications where aggregated data enhances user experience and system efficiency.

## [Benefits and Trade-offs of Microservices Aggregator Pattern](https://java-design-patterns.com/patterns/microservices-aggregrator/#benefits-and-trade-offs-of-microservices-aggregator-pattern)

Benefits:

- Simplified Client: Clients interact with just one service rather than managing calls to multiple microservices, which simplifies client-side logic.
- Reduced Latency: By aggregating responses, the number of network calls is reduced, which can improve the application's overall latency.
- Decoupling: Clients are decoupled from the individual microservices, allowing for more flexibility in changing the microservices landscape without impacting clients.
- Centralized Logic: Aggregation allows for centralized transformation and logic application on the data collected from various services, which can be more efficient than handling it in the client or spreading it across multiple services.

Trade-offs:

- Single Point of Failure: The aggregator service can become a bottleneck or a single point of failure if not designed with high availability and scalability in mind.
- Complexity: Implementing an aggregator can introduce complexity, especially in terms of data aggregation logic and error handling when dealing with multiple services.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/microservices-aggregrator/#related-java-design-patterns)

- [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): The Microservices Aggregator pattern is often used in conjunction with an API Gateway, which provides a single entry point for clients to access multiple microservices.
- [Composite](https://java-design-patterns.com/patterns/composite/): The Microservices Aggregator pattern can be seen as a form of the Composite pattern, where the composite is the aggregated response from multiple microservices.
- [Facade](https://java-design-patterns.com/patterns/facade/): The Microservices Aggregator pattern can be seen as a form of the Facade pattern, where the facade is the aggregator service that provides a simplified interface to the client.

## [References and Credits](https://java-design-patterns.com/patterns/microservices-aggregrator/#references-and-credits)

- [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43aGpSR)
- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z)
- [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://amzn.to/3T9g9Uj)
- [Microservice Architecture: Aligning Principles, Practices, and Culture](https://amzn.to/3T9jZNi)
- [Microservices Patterns: With examples in Java](https://amzn.to/4a5LHkP)
- [Pattern: API Composition](https://microservices.io/patterns/data/api-composition.html)
- [Production-Ready Microservices: Building Standardized Systems Across an Engineering Organization](https://amzn.to/4a0Vk4c)
- [Microservice Design Patterns (Arun Gupta)](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/)

---

## [architectural/microservices-client-side-ui-composition] Microservices Client Side Ui Composition
> 官方文档: https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/

ArchitecturalClient-serverCloud distributedCompositionDecouplingIntegrationMicroservicesModularityScalabilityWeb developmentAbout 2 min

* * *

## [Intent of Client-Side UI Composition Design Pattern](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#intent-of-client-side-ui-composition-design-pattern)

Compose user interface from independently deployable microservices on the client side for greater flexibility and decoupling.

## [Also Known As](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#also-known-as)

- UI Aggregator
- Frontend-Driven Composition

## [Detailed Explanation of Client-Side UI Composition Pattern with Real-World Examples](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#detailed-explanation-of-client-side-ui-composition-pattern-with-real-world-examples)

Real-world Example

> In a SaaS dashboard, a client-side composition pattern enables various independent modules like “Billing,” “Reports,” and “Account Settings” to be developed and deployed by separate teams. These modules are composed into a unified interface for the user, with each module independently fetching data from its respective microservice.

In Plain Words

> The Client-Side UI Composition pattern breaks down the user interface into smaller, independent parts that can be developed, maintained, and scaled separately by different teams.

Wikipedia says

> UI composition refers to the practice of building a user interface from modular components, each responsible for fetching its own data and rendering its own content. This approach enables faster development cycles, easier maintenance, and better scalability in large systems.

Sequence diagram

![Client-Side UI Composition sequence diagram](https://java-design-patterns.com/assets/img/microservices-client-side-ui-composition-sequence-diagram.894eb109.png)

## [Programmatic Example of Client-Side UI Composition in Java](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#programmatic-example-of-client-side-ui-composition-in-java)

This example composes an e-commerce frontend by integrating three independent modules. Each module is served by a microservice and fetched on the client side through an API Gateway.

### [`ApiGateway` Implementation](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#apigateway-implementation)

```java
public class ApiGateway {

    private final Map<String, FrontendComponent> routes = new HashMap<>();

    public void registerRoute(String path, FrontendComponent component) {
        routes.put(path, component);
    }

    public String handleRequest(String path, Map<String, String> params) {
        if (routes.containsKey(path)) {
            return routes.get(path).fetchData(params);
        } else {
            return "404 Not Found";
        }
    }
}
```

### [`FrontendComponent` Interface](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#frontendcomponent-interface)

```java
public interface FrontendComponent {
    String fetchData(Map<String, String> params);
}
```

### [Example Components](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#example-components)

```java
public class ProductComponent implements FrontendComponent {
    @Override
    public String fetchData(Map<String, String> params) {
        return "Displaying Products: " + params.getOrDefault("category", "all");
    }
}

public class CartComponent implements FrontendComponent {
    @Override
    public String fetchData(Map<String, String> params) {
        return "Displaying Cart for User: " + params.getOrDefault("userId", "unknown");
    }
}
```

This approach dynamically assembles UI components based on the route in the client-side request. Each component fetches its data asynchronously and renders it within the main interface.

## [When to Use the Client-Side UI Composition Pattern](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#when-to-use-the-client-side-ui-composition-pattern)

- When each microservice must present its own UI components
- When frequent independent deployments of UI features are required
- When teams own end-to-end functionality, including front-end modules
- When Java-based backends provide separate APIs for direct UI consumption

## [Client-Side UI Composition Pattern Tutorials](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#client-side-ui-composition-pattern-tutorials)

- [Micro Frontends in Action (O'Reilly)](https://www.oreilly.com/library/view/micro-frontends-in/9781617296873/)
- [Micro Frontends with React (ThoughtWorks)](https://www.thoughtworks.com/insights/articles/building-micro-frontends-using-react)
- [API Gateway in Microservices (Spring Cloud)](https://spring.io/guides/gs/gateway/)

## [Real-World Applications of Client-Side UI Composition Pattern in Java](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#real-world-applications-of-client-side-ui-composition-pattern-in-java)

- Large-scale e-commerce portals with microservices powering modular pages
- SaaS platforms requiring rapid iteration of front-end features
- Java-based microservice architectures using frameworks like Spring Boot for modular UI components

## [Benefits and Trade-offs of Client-Side UI Composition Pattern](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#benefits-and-trade-offs-of-client-side-ui-composition-pattern)

Benefits:

- Facilitates independent deployment cycles for UI features
- Reduces overall coupling and fosters autonomy among teams
- Enables polyglot front-end development

Trade-offs:

- Increases client complexity for rendering and data aggregation
- Can cause performance challenges with multiple service calls
- Demands consistent UX guidelines across diverse microservices

## [Related Design Patterns](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#related-design-patterns)

- Backend for Frontend (BFF): Provides custom endpoints for specific UIs
- Micro Frontends: Splits the front-end into smaller, individually deployable fragments
- [Microservices API Gateway Pattern](https://java-design-patterns.com/patterns/microservices-api-gateway/): API Gateway serves as a routing mechanism for client-side UI requests.

## [References and Credits](https://java-design-patterns.com/patterns/microservices-client-side-ui-composition/#references-and-credits)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Building Microservices with Micro Frontends (Martin Fowler)](https://martinfowler.com/articles/micro-frontends.html)
- [Client-Side UI Composition (Microservices.io)](https://microservices.io/patterns/client-side-ui-composition.html)
- [Cloud Native Java: Designing Resilient Systems with Spring Boot, Spring Cloud, and Cloud Foundry](https://amzn.to/44vDTat)
- [Micro Frontends Architecture (Microfrontends.org)](https://micro-frontends.org/)
- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)

---

## [architectural/microservices-distributed-tracing] Microservices Distributed Tracing
> 官方文档: https://java-design-patterns.com/patterns/microservices-distributed-tracing/

ArchitecturalCloud distributedMicroservicesResilienceObservabilityScalabilitySystem healthAbout 4 min

* * *

## [Intent of Microservices Distributed Tracing Design Pattern](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#intent-of-microservices-distributed-tracing-design-pattern)

Provide a mechanism to trace and correlate requests as they traverse multiple microservices in a distributed system, enabling end-to-end visibility and easier troubleshooting.

## [Also known as](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#also-known-as)

- Distributed Request Tracing
- End-to-End Microservice Tracing

## [Detailed Explanation of Microservices Distributed Tracing Pattern with Real-World Examples](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#detailed-explanation-of-microservices-distributed-tracing-pattern-with-real-world-examples)

Real-world example

> Imagine an online food delivery platform where one microservice handles user orders, another manages restaurant menus, and yet another coordinates courier assignments. When a user places an order, the request travels through all three services in sequence. By implementing distributed tracing, each service attaches a trace identifier to its logs. This allows the operations team to follow the journey of a single order across the entire pipeline, identify any delays along the way, and quickly pinpoint which service is causing the bottleneck or experiencing an error.

In plain words

> Distributed tracing allows you to follow a request's journey through all the services it interacts with, providing insights into system performance and aiding in debugging.

Wikipedia says

> Tracing in software engineering refers to the process of capturing and recording information about the execution of a software program. This information is typically used by programmers for debugging purposes, and additionally, depending on the type and detail of information contained in a trace log, by experienced system administrators or technical-support personnel and by software monitoring tools to diagnose common problems with software.

Sequence diagram

![Microservices Distributed Tracing Sequence Diagram](https://java-design-patterns.com/assets/img/microservices-distributed-tracing-sequence-diagram.2d573c32.png)

## [Programmatic Example of Microservices Distributed Tracing in Java](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#programmatic-example-of-microservices-distributed-tracing-in-java)

This implementation shows how an e-commerce platform's `OrderService` interacts with both `PaymentService` and `ProductService`. When a customer places an order, the `OrderService` calls the `PaymentService` to process the payment and the `ProductService` to check the product inventory. By adding distributed trace instrumentation (usually via libraries like Spring Cloud Sleuth or OpenTelemetry), each service attaches trace context to outgoing requests and logs. These logs can then be viewed in the Zipkin interface (or other tracing tools, such as Jaeger) to observe the entire flow of the request and quickly identify any performance bottlenecks or failures across multiple services.

Here's the `Order microservice` implementation.

```java
@Slf4j
@RestController
public class OrderController {

    private final OrderService orderService;

    public OrderController(final OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping("/order")
    public ResponseEntity<String> processOrder(@RequestBody(required = false) String request) {
        LOGGER.info("Received order request: {}", request);
        var result = orderService.processOrder();
        LOGGER.info("Order processed result: {}", result);
        return ResponseEntity.ok(result);
    }
}
```

```java
@Slf4j
@Service
public class OrderService {

    private final RestTemplateBuilder restTemplateBuilder;

    public OrderService(final RestTemplateBuilder restTemplateBuilder) {
        this.restTemplateBuilder = restTemplateBuilder;
    }

    public String processOrder() {
        if (validateProduct() && processPayment()) {
            return "Order processed successfully";
        }
        return "Order processing failed";
    }

    Boolean validateProduct() {
        try {
            ResponseEntity<Boolean> productValidationResult = restTemplateBuilder
                    .build()
                    .postForEntity("http://localhost:30302/product/validate", "validating product",
                            Boolean.class);
            LOGGER.info("Product validation result: {}", productValidationResult.getBody());
            return productValidationResult.getBody();
        } catch (ResourceAccessException | HttpClientErrorException e) {
            LOGGER.error("Error communicating with product service: {}", e.getMessage());
            return false;
        }
    }

    Boolean processPayment() {
        try {
            ResponseEntity<Boolean> paymentProcessResult = restTemplateBuilder
                    .build()
                    .postForEntity("http://localhost:30301/payment/process", "processing payment",
                            Boolean.class);
            LOGGER.info("Payment processing result: {}", paymentProcessResult.getBody());
            return paymentProcessResult.getBody();
        } catch (ResourceAccessException | HttpClientErrorException e) {
            LOGGER.error("Error communicating with payment service: {}", e.getMessage());
            return false;
        }
    }
}
```

Here's the `Payment microservice` implementation.

```java

@Slf4j
@RestController
public class PaymentController {

    @PostMapping("/payment/process")
    public ResponseEntity<Boolean> payment(@RequestBody(required = false) String request) {
        LOGGER.info("Received payment request: {}", request);
        boolean result = true;
        LOGGER.info("Payment result: {}", result);
        return ResponseEntity.ok(result);
    }
}
```

Here's the `Product microservice` implementation.

```java
/**
 * Controller for handling product validation requests.
 */
@Slf4j
@RestController
public class ProductController {

    /**
     * Validates the product based on the request.
     *
     * @param request the request body containing product information (can be null)
     * @return ResponseEntity containing the validation result (true)
     */
    @PostMapping("/product/validate")
    public ResponseEntity<Boolean> validateProduct(@RequestBody(required = false) String request) {
        LOGGER.info("Received product validation request: {}", request);
        boolean result = true;
        LOGGER.info("Product validation result: {}", result);
        return ResponseEntity.ok(result);
    }
}
```

In this example, each microservice would typically be configured with tracing libraries (like Sleuth or OpenTelemetry). The trace context is propagated via HTTP headers, enabling the logs and metrics for each service call to be grouped together and visualized in Zipkin or another compatible tool. This ensures complete end-to-end visibility into each request’s journey.

## [When to Use the Microservices Distributed Tracing Pattern in Java](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#when-to-use-the-microservices-distributed-tracing-pattern-in-java)

- When multiple services form a single user request path and debugging failures requires visibility across service boundaries.
- When monitoring or diagnosing performance bottlenecks is critical in a multi-service environment.
- When correlation of logs and metrics from independent services is needed to understand overall system health.

## [Microservices Distributed Tracing Pattern Java Tutorials](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#microservices-distributed-tracing-pattern-java-tutorials)

- [Spring Boot - Tracing (Spring)](https://docs.spring.io/spring-boot/reference/actuator/tracing.html)
- [Reactive Observability (Spring Academy)](https://spring.academy/guides/microservices-observability-reactive-spring-boot-3)
- [Spring Cloud – Tracing Services with Zipkin (Baeldung)](https://dzone.com/articles/getting-started-with-spring-cloud-gateway)

## [Real-World Applications of Microservices Distributed Tracing Pattern in Java](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#real-world-applications-of-microservices-distributed-tracing-pattern-in-java)

- OpenTelemetry for tracing instrumentation in Java services.
- Spring Cloud Sleuth for automatic tracing in Spring Boot microservices.
- Jaeger and Zipkin for collecting and visualizing distributed traces in Java-based systems.

## [Benefits and Trade-offs of Microservices Distributed Tracing Pattern](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#benefits-and-trade-offs-of-microservices-distributed-tracing-pattern)

Benefits:

- Centralized insight into request paths across services, reducing time to diagnose issues.
- Improved observability enables proactive identification of system bottlenecks.
- Aids in debugging and troubleshooting complex systems.

Trade-offs:

- Adds overhead to each request due to tracing data.
- Requires additional infrastructure (e.g., Zipkin, Jaeger) for collecting and visualizing traces.
- Can become complex to manage in large-scale systems.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#related-java-design-patterns)

- [API Gateway Microservice](https://java-design-patterns.com/patterns/microservices-api-gateway/): Acts as an entry point to microservices and can propagate trace information to downstream services.
- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Distributed tracing can be used alongside the Circuit Breaker pattern to monitor and handle failures gracefully, preventing cascading failures in microservices.
- [Log Aggregation Microservice](https://java-design-patterns.com/patterns/microservices-log-aggregation/): Distributed tracing works well in conjunction with log aggregation to provide comprehensive observability and troubleshooting capabilities.
- [Saga](https://java-design-patterns.com/patterns/saga/): Orchestrates distributed transactions, which benefit from trace identifiers to correlate steps across services.

## [References and Credits](https://java-design-patterns.com/patterns/microservices-distributed-tracing/#references-and-credits)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Distributed tracing (microservices.io)](https://microservices.io/patterns/observability/distributed-tracing.html)
- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
- [OpenTelemetry Documentation](https://opentelemetry.io/docs/)
- [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF)

---

## [architectural/model-view-controller] Model-View-Controller
> 官方文档: https://java-design-patterns.com/patterns/model-view-controller/

ArchitecturalArchitectureClient-serverDecouplingLayered architecturePresentationAbout 2 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/model-view-controller/#also-known-as)

- MVC

## [Intent of Model-View-Controller Design Pattern](https://java-design-patterns.com/patterns/model-view-controller/#intent-of-model-view-controller-design-pattern)

To separate an application into three interconnected components (Model, View, Controller), enabling modular development of each part independently, enhancing maintainability and scalability. Model-View-Controller (MVC) design pattern is widely used in Java applications for web development and user interface separation.

## [Detailed Explanation of Model-View-Controller Pattern with Real-World Examples](https://java-design-patterns.com/patterns/model-view-controller/#detailed-explanation-of-model-view-controller-pattern-with-real-world-examples)

Real-world example

> Consider ICU room in a hospital displaying patient health information on devices taking input from sensors. The display shows data received from the controller, which updates from the sensor model. This exemplifies the MVC design pattern in a real-world Java application.

In plain words

> MVC separates the business logic from user interface by mediating Controller between Model & View.

Wikipedia says

> Model–view–controller (MVC) is commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.

Architecture diagram

![Model-View-Controller Architecture Diagram](https://java-design-patterns.com/assets/img/mvc-architecture-diagram.84a7be09.png)

## [Programmatic Example of Model-View-Controller Pattern in Java](https://java-design-patterns.com/patterns/model-view-controller/#programmatic-example-of-model-view-controller-pattern-in-java)

Consider following `GiantModel` model class that provides the health, fatigue & nourishment information.

```java
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GiantModel {

  private Health health;
  private Fatigue fatigue;
  private Nourishment nourishment;

  @Override
  public String toString() {
    return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment);
  }
}
```

`GiantView` class to display received patient data.

```java
public class GiantView {

  public void displayGiant(GiantModel giant) {
    LOGGER.info(giant.toString());
  }
}
```

`GiantController` class takes updates from `GiantModel` and sends to `GiantView` for display.

```java
public class GiantController {

  private final GiantModel giant;
  private final GiantView view;

  public GiantController(GiantModel giant, GiantView view) {
    this.giant = giant;
    this.view = view;
  }

  @SuppressWarnings("UnusedReturnValue")
  public Health getHealth() {
    return giant.getHealth();
  }

  public void setHealth(Health health) {
    this.giant.setHealth(health);
  }

  @SuppressWarnings("UnusedReturnValue")
  public Fatigue getFatigue() {
    return giant.getFatigue();
  }

  public void setFatigue(Fatigue fatigue) {
    this.giant.setFatigue(fatigue);
  }

  @SuppressWarnings("UnusedReturnValue")
  public Nourishment getNourishment() {
    return giant.getNourishment();
  }

  public void setNourishment(Nourishment nourishment) {
    this.giant.setNourishment(nourishment);
  }

  public void updateView() {
    this.view.displayGiant(giant);
  }
}
```

This example demonstrates how the MVC pattern separates concerns in a Java application, making it easier to manage and update components independently.

## [When to Use the Model-View-Controller Pattern in Java](https://java-design-patterns.com/patterns/model-view-controller/#when-to-use-the-model-view-controller-pattern-in-java)

- Used in web applications to separate data model, user interface, and user input processing.
- Suitable for applications requiring a clear separation of concerns, ensuring that the business logic, user interface, and user input are loosely coupled and independently managed, following the MVC pattern.

## [Model-View-Controller Pattern Java Tutorials](https://java-design-patterns.com/patterns/model-view-controller/#model-view-controller-pattern-java-tutorials)

- [Spring Boot Model (ZetCode)](https://zetcode.com/springboot/model/)
- [Spring MVC Tutorial (Baeldung)](https://www.baeldung.com/spring-mvc-tutorial)

## [Real-World Applications of Model-View-Controller Pattern in Java](https://java-design-patterns.com/patterns/model-view-controller/#real-world-applications-of-model-view-controller-pattern-in-java)

- Frameworks like Spring MVC in Java for web applications.
- Desktop applications in Java, such as those using Swing or JavaFX.

## [Benefits and Trade-offs of Model-View-Controller Pattern](https://java-design-patterns.com/patterns/model-view-controller/#benefits-and-trade-offs-of-model-view-controller-pattern)

Benefits:

- Promotes organized code structure by separating concerns.
- Facilitates parallel development of components.
- Enhances testability due to decoupled nature.
- Easier to manage and update individual parts without affecting others.

Trade-offs:

- Increased complexity in initially setting up the architecture.
- Can lead to excessive boilerplate if not implemented correctly or for very small projects.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/model-view-controller/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Often used in MVC where the view observes the model for changes; this is a fundamental relationship for updating the UI when the model state changes.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Controllers may use different strategies for handling user input, related through the ability to switch strategies for user input processing in Java MVC applications.
- [Composite](https://java-design-patterns.com/patterns/composite/): Views can be structured using the Composite Pattern to manage hierarchies of user interface components.

## [References and Credits](https://java-design-patterns.com/patterns/model-view-controller/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Pro Spring 5: An In-Depth Guide to the Spring Framework and Its Tools](https://amzn.to/3y9Rrwp)
- [Model-view-controller (Wikipedia)](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)

---

## [architectural/model-view-intent] Model-View-Intent
> 官方文档: https://java-design-patterns.com/patterns/model-view-intent/

ArchitecturalAbstractionDecouplingPresentationReactiveState trackingAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/model-view-intent/#also-known-as)

- MVI

## [Intent of Model-View-Intent Design Pattern](https://java-design-patterns.com/patterns/model-view-intent/#intent-of-model-view-intent-design-pattern)

The Model-View-Intent (MVI) pattern for Java applications creates a unidirectional and cyclical data flow between the Model, View, and Intent components, enhancing UI predictability and state management.

## [Detailed Explanation of Model-View-Intent Pattern with Real-World Examples](https://java-design-patterns.com/patterns/model-view-intent/#detailed-explanation-of-model-view-intent-pattern-with-real-world-examples)

Real-world example

> Consider a real-world analogy of the Model-View-Intent (MVI) pattern in Java using the scenario of ordering at a fast-food restaurant to understand its application in enhancing UI state management.
>
> In this analogy:
>
> - **Model:** It's like the kitchen of the restaurant, where the current state of your order is managed. As you choose items, the kitchen updates the order status and ingredients used.
> - **View:** This represents the menu and the digital display board where you see your current order summary. It reflects the current state of your order, showing what items you've added or removed.
> - **Intent:** Think of this as your decision-making process when you interact with the menu. Each choice you make (like adding a burger or removing a drink) sends a specific intention to the system (kitchen).
>
> When you decide to add an item to your order (Intent), the kitchen (Model) processes this request, updates the state of your order, and then the display (View) updates to show the latest status of your order. This cycle continues until you finalize your order, demonstrating the unidirectional and cyclical flow characteristic of MVI. This ensures that every change in the order is predictably and accurately reflected in the customer's view, similar to how UI components update in response to state changes in software using MVI.

In plain words

> The Model-View-Intent (MVI) pattern is a reactive architectural approach where user actions (Intent) modify the application state (Model), and the updated state is then reflected back in the user interface (View) in a unidirectional and cyclical data flow.

Architecture diagram

![Model-View-Intent Architecture Diagram](https://java-design-patterns.com/assets/img/mvi-architecture-diagram.7c86b42f.png)

## [Programmatic Example of Model-View-Intent Pattern in Java](https://java-design-patterns.com/patterns/model-view-intent/#programmatic-example-of-model-view-intent-pattern-in-java)

The Model-View-Intent (MVI) pattern for Java is a modern approach to structuring your application's logic, ensuring a smooth, unidirectional flow of data and events. It's a variation of the Model-View-Presenter (MVP) and Model-View-ViewModel (MVVM) patterns, but with a more streamlined flow of data and events.

In MVI, the View sends user events to the Intent. The Intent translates these events into a state change in the Model. The Model then pushes this new state to the View, which updates itself accordingly. This creates a unidirectional data flow, which can make your code easier to understand and debug.

First, we have the `App` class, which serves as the entry point for the application. It creates the View and ViewModel, and then simulates a series of user interactions with the calculator.

```java
public final class App {
  private static final double RANDOM_VARIABLE = 10.0;

  public static void main(final String[] args) {
    var view = new CalculatorView(new CalculatorViewModel());
    var variable1 = RANDOM_VARIABLE;

    view.setVariable(variable1);
    view.add();
    view.displayTotal();

    variable1 = 2.0;
    view.setVariable(variable1);
    view.subtract();
    view.divide();
    view.multiply();
    view.displayTotal();
  }

  private App() {
  }
}
```

The `CalculatorView` class represents the View in MVI. It receives user events (in this case, simulated by the `App` class), and sends them to the ViewModel. It also updates its display when it receives a new state from the ViewModel.

```java
public class CalculatorView {
  private CalculatorViewModel viewModel;

  public CalculatorView(CalculatorViewModel viewModel) {
    this.viewModel = viewModel;
  }

  public void setVariable(double variable) {
    viewModel.process(new SetVariableEvent(variable));
  }

  public void add() {
    viewModel.process(new AddEvent());
  }

  public void subtract() {
    viewModel.process(new SubtractEvent());
  }

  public void divide() {
    viewModel.process(new DivideEvent());
  }

  public void multiply() {
    viewModel.process(new MultiplyEvent());
  }

  public void displayTotal() {
    System.out.println("Total: " + viewModel.getState().getTotal());
  }
}
```

The `CalculatorViewModel` class represents the ViewModel in MVI. It receives events from the View, updates the Model's state accordingly, and then pushes the new state to the View.

```java
public class CalculatorViewModel {
  private CalculatorModel model;

  public CalculatorViewModel() {
    this.model = new CalculatorModel();
  }

  public void process(UserEvent event) {
    event.apply(model);
  }

  public CalculatorModel getState() {
    return model;
  }
}
```

The `CalculatorModel` class represents the Model in MVI. It holds the current state of the calculator, and provides methods for updating that state.

```java
public class CalculatorModel {
  private double total;
  private double variable;

  public void setVariable(double variable) {
    this.variable = variable;
  }

  public void add() {
    total += variable;
  }

  public void subtract() {
    total -= variable;
  }

  public void divide() {
    total /= variable;
  }

  public void multiply() {
    total *= variable;
  }

  public double getTotal() {
    return total;
  }
}
```

Finally, the `UserEvent` interface and its implementations represent the different types of user events that can occur. Each event knows how to apply itself to the Model.

```java
public interface UserEvent {
  void apply(CalculatorModel model);
}

public class SetVariableEvent implements UserEvent {
  private double variable;

  public SetVariableEvent(double variable) {
    this.variable = variable;
  }

  @Override
  public void apply(CalculatorModel model) {
    model.setVariable(variable);
  }
}

// Similar classes would be created for AddEvent, SubtractEvent, DivideEvent, and MultiplyEvent ...
```

This example demonstrates the key aspects of the MVI pattern: unidirectional data flow, clear separation of concerns, and the use of events to drive changes in the Model's state.

## [When to Use the Model-View-Intent Pattern in Java](https://java-design-patterns.com/patterns/model-view-intent/#when-to-use-the-model-view-intent-pattern-in-java)

- The MVI pattern is useful in Java applications with complex user interfaces that require a clear separation of concerns, predictable state management, and enhanced maintainability.
- Often applied in reactive programming environments to ensure a smooth data flow and state consistency.

## [Model-View-Intent Pattern Java Tutorials](https://java-design-patterns.com/patterns/model-view-intent/#model-view-intent-pattern-java-tutorials)

- [Model View Intent: a new Android Architecture Pattern (Apium Academy)](https://apiumacademy.com/blog/model-view-intent-pattern/)
- [MVI Architecture for Android Tutorial: Getting Started (Kodeco)](https://www.kodeco.com/817602-mvi-architecture-for-android-tutorial-getting-started)

## [Real-World Applications of Model-View-Intent Pattern in Java](https://java-design-patterns.com/patterns/model-view-intent/#real-world-applications-of-model-view-intent-pattern-in-java)

- Widely adopted in reactive and event-driven Java applications, particularly those using frameworks like RxJava or Project Reactor.
- Used in Android development, especially with libraries that support reactive programming such as RxJava and LiveData.

## [Benefits and Trade-offs of Model-View-Intent Pattern](https://java-design-patterns.com/patterns/model-view-intent/#benefits-and-trade-offs-of-model-view-intent-pattern)

Benefits:

- Enhances the predictability of the UI by establishing a clear and cyclical data flow.
- Improves testability due to well-defined separation between components.
- Supports better state management by centralizing the state within the Model.

Trade-offs:

- Increases complexity for simple UIs due to the structured and cyclical flow.
- Requires familiarity with reactive programming paradigms.
- Can lead to boilerplate code if not managed properly.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/model-view-intent/#related-java-design-patterns)

[Model-View-ViewModel (MVVM)](https://java-design-patterns.com/patterns/model-view-viewmodel/): Shares a similar goal of separating the view from the model but differs as MVI introduces a cyclical data flow.

[Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): MVI can be seen as an evolution of MVC, focusing more on reactive programming and unidirectional data flow.

[Observer](https://java-design-patterns.com/patterns/observer/): Essential in MVI to observe changes in the Model and update the View accordingly.

## [References and Credits](https://java-design-patterns.com/patterns/model-view-intent/#references-and-credits)

- [Functional and Reactive Domain Modeling](https://amzn.to/4adghJ8)
- [Reactive Programming with RxJava: Creating Asynchronous, Event-Based Applications](https://amzn.to/4dxwawC)

---

## [architectural/model-view-presenter] Model-View-Presenter
> 官方文档: https://java-design-patterns.com/patterns/model-view-presenter/

ArchitecturalArchitectureClient-serverDecouplingEnterprise patternsInterfacePresentationAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/model-view-presenter/#also-known-as)

- MVP

## [Intent of Model-View-Presenter Design Pattern](https://java-design-patterns.com/patterns/model-view-presenter/#intent-of-model-view-presenter-design-pattern)

MVP aims to separate the user interface (UI) logic from the business logic and model in a software application, enabling easier testing and maintenance.

## [Detailed Explanation of Model-View-Presenter Pattern with Real-World Examples](https://java-design-patterns.com/patterns/model-view-presenter/#detailed-explanation-of-model-view-presenter-pattern-with-real-world-examples)

Real-world example

> Consider a real-world analogy of the Model-View-Presenter (MVP) pattern using a restaurant scenario:
>
> - **Model:** This is the kitchen in a restaurant, where all the cooking and preparation of dishes happens. It's responsible for managing the food ingredients, cooking processes, and ensuring that recipes are followed correctly.
>
> - **View:** This represents the dining area and the menu presented to the customers. It displays the available dishes, takes orders, and shows the final presentation of the food. However, it doesn't decide what's cooked or how it's prepared.
>
> - **Presenter:** Acting as the waiter, the presenter takes the customer's order (input) and communicates it to the kitchen (model). The waiter then brings the prepared food (output) back to the customer in the dining area (view). The waiter ensures that what the customer sees (the menu and food presentation) aligns with what the kitchen can provide, and also updates the view based on the kitchen's capabilities (e.g., out-of-stock items).
>
>
> In this analogy, the clear separation of roles allows the restaurant to operate efficiently: the kitchen focuses on food preparation, the dining area on customer interaction, and the waiter bridges the two, ensuring smooth operation and customer satisfaction.

In plain words

> The Model-View-Presenter (MVP) pattern separates the user interface, business logic, and data interaction in an application, with the presenter mediating between the view and the model to facilitate clear communication and updates. Java developers use MVP to improve application structure.

Wikipedia says

> Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces. In MVP, the presenter assumes the functionality of the "middle-man". In MVP, all presentation logic is pushed to the presenter.

Architecture diagram

![Model-View-Presenter Architecture Diagram](https://java-design-patterns.com/assets/img/mvp-architecture-diagram.bd626c5d.png)

## [Programmatic Example of Model-View-Presenter Pattern in Java](https://java-design-patterns.com/patterns/model-view-presenter/#programmatic-example-of-model-view-presenter-pattern-in-java)

The Model-View-Presenter (MVP) design pattern is a derivative of the well-known Model-View-Controller (MVC) pattern. It aims to separate the application's logic (Model), GUIs (View), and the way that the user's actions update the application's logic (Presenter). This separation of concerns makes the application easier to manage, extend, and test.

Let's break down the MVP pattern using the provided code:

1. **Model**: The Model represents the application's logic. In our case, the `FileLoader` class is the Model. It's responsible for handling the file loading process.

```java
@Getter
public class FileLoader implements Serializable {
  //...
  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  public boolean fileExists() {
    //...
  }

  public String loadData() {
    //...
  }
}
```

2. **View**: The View is responsible for displaying the data provided by the Model. Here, the `FileSelectorView` interface and its implementation `FileSelectorJFrame` represent the View. They define how to display data and messages to the user.

```java
public interface FileSelectorView {
  //...
  void setPresenter(FileSelectorPresenter presenter);
  void open();
  void close();
  void showMessage(String message);
  void displayData(String data);
  String getFileName();
}

public class FileSelectorJFrame implements FileSelectorView {
  //...
  @Override
  public void displayData(String data) {
    this.dataDisplayed = true;
  }
}
```

3. **Presenter**: The Presenter acts as a bridge between the Model and the View. It reacts to the user's actions and updates the View accordingly. In our example, the `FileSelectorPresenter` class is the Presenter.

```java
public class FileSelectorPresenter implements Serializable {
  //...
  public void setLoader(FileLoader loader) {
    this.loader = loader;
  }

  public void start() {
    view.setPresenter(this);
    view.open();
  }

  public void fileNameChanged() {
    loader.setFileName(view.getFileName());
  }

  public void confirmed() {
    //...
  }

  public void cancelled() {
    view.close();
  }
}
```

Finally, we wire up the Presenter, the View, and the Model in the `App` class:

```java
public class App {
  public static void main(String[] args) {
    var loader = new FileLoader();
    var frame = new FileSelectorJFrame();
    var presenter = new FileSelectorPresenter(frame);
    presenter.setLoader(loader);
    presenter.start();
  }
}
```

In this setup, the `App` class creates instances of the Model, View, and Presenter. It then connects these instances, forming the MVP triad. The Presenter is given a reference to the View, and the Model is set on the Presenter. Finally, the Presenter is started, which in turn opens the View.

## [When to Use the Model-View-Presenter Pattern in Java](https://java-design-patterns.com/patterns/model-view-presenter/#when-to-use-the-model-view-presenter-pattern-in-java)

Use MVP in applications where a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) is needed between the presentation layer and the underlying business logic. It's particularly useful in client-server applications and enterprise-level applications.

## [Real-World Applications of Model-View-Presenter Pattern in Java](https://java-design-patterns.com/patterns/model-view-presenter/#real-world-applications-of-model-view-presenter-pattern-in-java)

- Desktop applications like those built using Java Swing or JavaFX.
- Web applications with complex user interfaces and business logic.

## [Benefits and Trade-offs of Model-View-Presenter Pattern](https://java-design-patterns.com/patterns/model-view-presenter/#benefits-and-trade-offs-of-model-view-presenter-pattern)

Benefits:

- Enhances testability of UI logic by allowing the presenter to be tested separately from the view.
- Promotes a clean separation of concerns, making the application easier to manage and extend.
- Facilitates easier UI updates without affecting the business logic.

Trade-offs:

- Increases complexity with more classes and interfaces.
- Requires careful design to avoid over-coupling between the presenter and the view.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/model-view-presenter/#related-java-design-patterns)

- [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): MVP is often considered a variant of MVC where the presenter takes over the controller's role in managing user input and updating the model.
- [Model-View-ViewModel (MVVM)](https://java-design-patterns.com/patterns/model-view-viewmodel/): Similar to MVP but adapted for frameworks like WPF or frameworks that support data binding, making the view update automatically when the model changes.

## [References and Credits](https://java-design-patterns.com/patterns/model-view-presenter/#references-and-credits)

- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/4a8qcQ1)

---

## [architectural/model-view-viewmodel] Model-View-ViewModel
> 官方文档: https://java-design-patterns.com/patterns/model-view-viewmodel/

ArchitecturalArchitectureData bindingDecouplingPresentationScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/model-view-viewmodel/#also-known-as)

- MVVM

## [Intent of Model-View-ViewModel Design Pattern](https://java-design-patterns.com/patterns/model-view-viewmodel/#intent-of-model-view-viewmodel-design-pattern)

The intent of the Model-View-ViewModel (MVVM) pattern in Java is to provide a clear [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns) between the UI logic, the presentation logic, and the business logic by dividing the application into three interconnected components: Model, View, and ViewModel.

## [Detailed Explanation of Model-View-ViewModel Pattern with Real-World Examples](https://java-design-patterns.com/patterns/model-view-viewmodel/#detailed-explanation-of-model-view-viewmodel-pattern-with-real-world-examples)

Real-world example

> Consider a real-world analogous example of the MVVM pattern similar to organizing a cooking show. In this scenario:
>
> - **Model:** Represents the recipe itself, which includes the ingredients and the steps needed to cook the dish. The model is purely about the data and rules for preparing the dish but does not concern itself with how this information is presented to the audience.
>
> - **View:** Is akin to the kitchen set where the cooking show is filmed, including all the visual elements like the layout of the kitchen, the placement of ingredients, and the cookware. The view is responsible for the visual presentation and how the audience sees the cooking process.
>
> - **ViewModel:** Acts like the script for the cooking show, where it interprets the recipe (model) and organizes the flow of the show. It tells the chef (view) what to display next, when to add ingredients, and how to respond to changes like substituting an ingredient. The ViewModel bridges the gap between the technical details of the recipe and the chef's presentation, ensuring the audience understands each step without delving into the complexities of the recipe itself.
>
>
> In this example, the ViewModel allows the chef to focus on cooking and interacting with the audience, while the underlying recipe remains unchanged, promoting a clear separation of concerns.

In plain words

> The MVVM design pattern separates an application into three distinct components: the Model, which holds the data and business logic; the View, which displays the user interface; and the ViewModel, which acts as an intermediary to bind data from the Model to the View.

Wikipedia says

> Model–view–viewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform.

Architecture diagram

![Model-View-ViewModel Architecture Diagram](https://java-design-patterns.com/assets/img/mvvm-architecture-diagram.6026b955.png)

## [Programmatic Example of Model-View-ViewModel Pattern in Java](https://java-design-patterns.com/patterns/model-view-viewmodel/#programmatic-example-of-model-view-viewmodel-pattern-in-java)

ViewModel will hold the business logic and expose the data from model to View.

```java
public class BookViewModel {
  @WireVariable
  private List<Book> bookList;
  private Book selectedBook;
  private BookService bookService = new BookServiceImpl();

  public Book getSelectedBook() {
    return selectedBook;
  }

  @NotifyChange("selectedBook")
  public void setSelectedBook(Book selectedBook) {
    this.selectedBook = selectedBook;
  }

  public List<Book> getBookList() {
    return bookService.load();
  }

  /** Deleting a book.
   */
  @Command
  @NotifyChange({"selectedBook","bookList"})
  public void deleteBook() {
    if (selectedBook != null) {
      getBookList().remove(selectedBook);
      selectedBook = null;
    }
}
```

View will have no logic, only UI elements.

```xml
<zk>
<window title="List of Books" border="normal" width="600px" apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('com.iluwatar.model.view.viewmodel.BookViewModel')">
    <vbox hflex="true">
        <listbox model="@bind(vm.bookList)" selectedItem="@bind(vm.selectedBook)" height="400px" mold="paging">
            <listhead>
                <listheader label="Book Name"/>
                <listheader label="Author"/>
            </listhead>
            <template name="model" var="book">
                <listitem >
                    <listcell label="@bind(book.name)"/>
                    <listcell label="@bind(book.author)"/>
                </listitem>
            </template>
        </listbox>
    </vbox>
    <toolbar>
        <button label="Delete" onClick="@command('deleteBook')" disabled="@load(empty vm.selectedBook)" />
    </toolbar>
    <hbox style="margin-top:20px" visible="@bind(not empty vm.selectedBook)">
		<vbox>
			<hlayout>
				Book Name : <label value="@bind(vm.selectedBook.name)" style="font-weight:bold"/>
			</hlayout>
			<hlayout>
				Book Author : <label value="@bind(vm.selectedBook.author)" style="font-weight:bold"/>
			</hlayout>
			<hlayout>
				Book Description : <label value="@bind(vm.selectedBook.description)" style="font-weight:bold"/>
			</hlayout>
		</vbox>
	</hbox>
</window>
</zk>
```

To deploy the example, go to model-view-viewmodel folder and run:

- `mvn clean install`
- `mvn jetty:run -Djetty.http.port=9911`
- Open browser to address: [http://localhost:9911/model-view-viewmodel/](http://localhost:9911/model-view-viewmodel/)

## [When to Use the Model-View-ViewModel Pattern in Java](https://java-design-patterns.com/patterns/model-view-viewmodel/#when-to-use-the-model-view-viewmodel-pattern-in-java)

MVVM is applicable in applications requiring a clear separation between the user interface and the underlying business logic, especially in large-scale, data-driven applications where UI and business logic change independently. This makes the Model-View-ViewModel pattern ideal for Java applications.

## [Model-View-ViewModel Pattern Java Tutorials](https://java-design-patterns.com/patterns/model-view-viewmodel/#model-view-viewmodel-pattern-java-tutorials)

- [Data Binding in Android (developer.android.com)](https://developer.android.com/codelabs/android-databinding#0)
- [Introduction to Model View View Model (MVVM) (GeeksforGeeks)](https://www.geeksforgeeks.org/introduction-to-model-view-view-model-mvvm/)
- [Patterns - WPF Apps With The Model-View-ViewModel Design Pattern (Microsoft)](https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern)

## [Real-World Applications of Model-View-ViewModel Pattern in Java](https://java-design-patterns.com/patterns/model-view-viewmodel/#real-world-applications-of-model-view-viewmodel-pattern-in-java)

- Widely used in JavaFX applications for desktop interfaces.
- Utilized in Android development with libraries like DataBinding and LiveData for reactive UI updates.
- ZK Framework [zkoss.org](https://www.zkoss.org/)
- KnockoutJS [knockoutjs.com](https://knockoutjs.com/)

## [Benefits and Trade-offs of Model-View-ViewModel Pattern](https://java-design-patterns.com/patterns/model-view-viewmodel/#benefits-and-trade-offs-of-model-view-viewmodel-pattern)

Benefits:

- Improved testability due to decoupling of business and presentation logic.
- Easier maintenance and modification of the user interface without affecting the underlying data model.
- Enhanced reusability of the ViewModel across different views if designed generically.

Trade-offs:

- Increased complexity in small applications where simpler patterns might suffice.
- Learning curve associated with understanding and applying the pattern correctly.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/model-view-viewmodel/#related-java-design-patterns)

- [MVC (Model-View-Controller)](https://java-design-patterns.com/patterns/model-view-controller/): MVVM can be seen as a derivative of MVC with a stronger emphasis on binding and decoupling, where the ViewModel acts as an intermediary unlike the controller in MVC.
- [MVP (Model-View-Presenter)](https://java-design-patterns.com/patterns/model-view-presenter/): Similar to MVVM but with a focus on the presenter handling the UI logic, making MVVM's ViewModel more passive in terms of direct UI manipulation.

## [References and Credits](https://java-design-patterns.com/patterns/model-view-viewmodel/#references-and-credits)

- [Android Programming: The Big Nerd Ranch Guide](https://amzn.to/3wBGG5o)
- [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/4a8qcQ1)

---

## [architectural/monolithic-architecture] Monolithic Architecture
> 官方文档: https://java-design-patterns.com/patterns/monolithic-architecture/

ArchitecturalArchitectureCohesionEncapsulationLayered architectureModularityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/monolithic-architecture/#also-known-as)

- Single-tier architecture
- Monolith

## [The Intent of Monolithic Design pattern](https://java-design-patterns.com/patterns/monolithic-architecture/#the-intent-of-monolithic-design-pattern)

Encapsulate all the functionality of an application within a single, cohesive codebase.

## [Detailed Explanation of the Monolithic Architecture](https://java-design-patterns.com/patterns/monolithic-architecture/#detailed-explanation-of-the-monolithic-architecture)

Real-world example

> An analogous real-world example of the Monolithic Architecture pattern is a department store. Just like a monolithic Java application, a department store hosts all product categories, sales, storage, and customer services within a single, large building. It simplifies shopping by consolidating everything under one roof, making operations straightforward and easy to manage. However, expanding or rearranging specific departments becomes increasingly challenging over time, similar to how scaling individual functionalities within a monolithic system can become complex and cumbersome.

In plain words

> The monolithic design pattern structures an application as a single unified unit, where all components are tightly coupled and run within a single process.

Wikipedia says

> In software engineering, a monolithic application is a single unified software application that is self-contained and independent of other applications, but typically lacks flexibility. There are advantages and disadvantages of building applications in a monolithic style of software architecture, depending on requirements. Monolith applications are relatively simple and have a low cost but their shortcomings are lack of elasticity, fault tolerance and scalability.

Mind map

![Monolithic Architecture Mind Map](https://java-design-patterns.com/assets/img/monolithic-architecture-mind-map.f038a28e.png)

Flowchart

![Monolithic Architecture Flowchart](https://java-design-patterns.com/assets/img/monolithic-architecture-flowchart.a198a777.png)

## [Programmatic Example of Monolithic Architecture in Java](https://java-design-patterns.com/patterns/monolithic-architecture/#programmatic-example-of-monolithic-architecture-in-java)

This is a simplified version of the main application, demonstrating how a monolithic architecture can be implemented. Here, all the essential services—such as user management (`UserCon`), product management (`ProductCon`), and order processing (`OrderCon`) — are tightly integrated within a single executable Java application. The CLI provides a straightforward user interaction point where operations like user registration, adding products, and placing orders are handled.

```java
@SpringBootApplication
public class EcommerceApp implements CommandLineRunner {

  private static final Logger log = LogManager.getLogger(EcommerceApp.class);
  private final UserCon userService;
  private final ProductCon productService;
  private final OrderCon orderService;
  public EcommerceApp(UserCon userService, ProductCon productService, OrderCon orderService) {
    this.userService = userService;
    this.productService = productService;
    this.orderService = orderService;
  }
  public static void main(String... args) {
    SpringApplication.run(EcommerceApp.class, args);
  }
  @Override
  public void run(String... args) {
    Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8);

    log.info("Welcome to the Monolithic E-commerce CLI!");
    while (true) {
      log.info("\nChoose an option:");
      log.info("1. Register User");
      log.info("2. Add Product");
      log.info("3. Place Order");
      log.info("4. Exit");
      log.info("Enter your choice: ");

      int userInput = scanner.nextInt();
      scanner.nextLine();

      switch (userInput) {
        case 1 -> registerUser(scanner);
        case 2 -> addProduct(scanner);
        case 3 -> placeOrder(scanner);
        case 4 -> {
          log.info("Exiting the application. Goodbye!");
          return;
        }
        default -> log.info("Invalid choice! Please try again.");
      }
    }
  }
  protected void registerUser(Scanner scanner) {
    log.info("Enter user details:");
    log.info("Name: ");
    String name = scanner.nextLine();
    log.info("Email: ");
    String email = scanner.nextLine();
    log.info("Password: ");
    String password = scanner.nextLine();

    User user = new User(null, name, email, password);
    userService.registerUser(user);
    log.info("User registered successfully!");
  }

}
```

In this example, the core business functionalities are closely interconnected, sharing common resources and residing within the same codebase. This approach simplifies initial application development, testing, and deployment, as each component can easily access the others directly without the overhead of inter-service communication. However, as the application grows, scaling individual components independently becomes more challenging, highlighting the key trade-off inherent in the monolithic architecture.

## [When to Use the Monolithic Architecture in Java](https://java-design-patterns.com/patterns/monolithic-architecture/#when-to-use-the-monolithic-architecture-in-java)

- Suitable for small to medium-sized applications where simplicity, cohesive development, and ease of deployment outweigh scalability and flexibility requirements.
- Applicable in contexts where initial rapid development and ease of testing are prioritized.

## [Real-World Applications of Monolithic Architecture in Java](https://java-design-patterns.com/patterns/monolithic-architecture/#real-world-applications-of-monolithic-architecture-in-java)

- Early-stage Java web applications developed using frameworks like Spring MVC, Java EE (Servlets/JSP), or frameworks like Play.
- Traditional Java enterprise applications packaged and deployed as WAR or EAR files on application servers such as Apache Tomcat, Jetty, or WildFly.
- Standalone Java applications and desktop applications packaged as single executable JAR files.

## [Benefits and Trade-offs of Monolithic Architecture](https://java-design-patterns.com/patterns/monolithic-architecture/#benefits-and-trade-offs-of-monolithic-architecture)

Benefits:

- Simpler to develop, test, and deploy as the application is a single unit.
- Easier debugging and performance monitoring due to the single unified runtime.
- Typically faster initial development and straightforward management of dependencies.

Trade-offs:

- Poor scalability and potential performance bottlenecks as the application grows.
- Limited modularity, leading to increased complexity and harder maintainability over time.
- Slow deployments and updates due to a single large codebase.
- Difficult to scale individual functionalities independently.

## [Related Patterns](https://java-design-patterns.com/patterns/monolithic-architecture/#related-patterns)

- Microservices Architecture: Breaks down a monolithic application into independently deployable services, directly addressing the scalability and maintainability limitations of monoliths.
- [Layered Architecture](https://java-design-patterns.com/patterns/layered-architecture/): Often used internally within monoliths to provide clear separation between presentation, business logic, and persistence layers.

## [References](https://java-design-patterns.com/patterns/monolithic-architecture/#references)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Fundamentals of Software Architecture: An Engineering Approach](https://amzn.to/4cx4A2N)
- [Monolithic Architecture - System Design (GeeksforGeeks)](https://www.geeksforgeeks.org/monolithic-architecture-system-design/)
- [Monolithic Application (Wikipedia)](https://en.wikipedia.org/wiki/Monolithic_application)
- [Pattern: Monolithic Architecture (Microservices.io)](https://microservices.io/patterns/monolithic.html)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [What Is Monolithic Architecture? (IBM)](https://www.ibm.com/think/topics/monolithic-architecture)

---

## [architectural/naked-objects] Naked Objects
> 官方文档: https://java-design-patterns.com/patterns/naked-objects/

ArchitecturalArchitectureBusinessDecouplingDomainEnterprise patternsInstantiationObject compositionPersistenceAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/naked-objects/#also-known-as)

- Transparent Objects

## [Intent of Naked Objects Design Pattern](https://java-design-patterns.com/patterns/naked-objects/#intent-of-naked-objects-design-pattern)

To enable the rapid development of maintainable systems by representing all business objects directly and automatically creating the user interface from these definitions. Naked Objects design pattern is essential for developers aiming to align user interfaces with domain models seamlessly.

## [Detailed Explanation of Naked Objects Pattern with Real-World Examples](https://java-design-patterns.com/patterns/naked-objects/#detailed-explanation-of-naked-objects-pattern-with-real-world-examples)

Real-world example

> In a Naked Objects design pattern, a company might develop a customer relationship management (CRM) system where each business object, such as "Customer," "Order," and "Product," is represented directly. This allows for a dynamic and adaptable UI reflecting the underlying domain model with minimal developer intervention. The user interface is automatically generated based on these domain objects, allowing sales representatives to view and edit customer information, track orders, and manage inventory without needing a separately designed UI.
>
> This approach ensures that any changes in the business logic or domain model are immediately reflected in the user interface, significantly reducing the development and maintenance time. For instance, if a new field, "Loyalty Points," is added to the "Customer" object to track rewards, this field automatically appears in the CRM's user interface without additional UI development. This keeps the system flexible and closely aligned with the evolving business needs.

In plain words

> The Naked Objects design pattern automatically generates a user interface from domain objects, allowing for rapid development and easy maintenance by ensuring the UI directly reflects the underlying business model.

Wikipedia says

> Naked objects is an architectural pattern used in software engineering. It is defined by three principles:
>
> 1. All business logic should be encapsulated onto the domain objects. This principle is not unique to naked objects; it is a strong commitment to encapsulation.
> 2. The user interface should be a direct representation of the domain objects, with all user actions consisting of creating, retrieving, or invoking methods on domain objects. This principle is not unique to naked objects: it is an interpretation of an object-oriented user interface.
>
> The naked object pattern's innovative feature arises by combining the 1st and 2nd principles into a 3rd principle: 3. The user interface shall be entirely automatically created from the definitions of the domain objects. This may be done using reflection or source code generation.

Architecture diagram

![Naked Objects Architecture Diagram](https://java-design-patterns.com/assets/img/naked-objects-architecture-diagram.e8f7a080.png)

## [Programmatic Example of Naked Objects Pattern in Java](https://java-design-patterns.com/patterns/naked-objects/#programmatic-example-of-naked-objects-pattern-in-java)

Consider a simplified example with domain objects representing books and authors. In a Java-based application using the Naked Objects pattern, we define domain objects such as `Book` and `Author`. This example illustrates how Naked Objects can streamline user interface generation and domain object manipulation.

Suppose we have the following domain objects in a Java-based application:

```java
@DomainObject
public class Book {
    @Property
    private String title;

    @Property
    private String author;

    @Action
    public void borrow() {
        // Implement borrowing logic here
    }
}

@DomainObject
public class Author {
    @Property
    private String name;

    @Collection
    public List<Book> getBooks() {
        // Implement logic to retrieve books by this author
    }

    @Action
    public Book createBook(String title) {
        // Implement logic to create a new book by this author
    }
}
```

In this example, we define two domain objects: `Book` and `Author`. The `Book` class has properties for the `title` and `author`, as well as an action to `borrow` the book. The `Author` class has a property for the author's `name`, a collection of books they have written (`getBooks`), and an action to create a new book (`createBook`).

With the Naked Objects framework or tool, the user interface for managing books and authors can be automatically generated based on these domain object definitions. Users can interact with the generated UI to create, retrieve, update, and delete books and authors directly through a user-friendly interface.

Here's how you can use these domain objects to create and interact with books and authors programmatically:

```java
var author = new Author();
author.setName("J.K. Rowling");
var book = author.createBook("Harry Potter and the Philosopher's Stone");
book.setAuthor(author);
book.borrow();
var booksByAuthor = author.getBooks();
```

This example demonstrates how the Naked Objects pattern can be implemented in a Java-based application with domain objects for books and authors. Users can directly manipulate these domain objects through the generated user interface.

## [When to Use the Naked Objects Pattern in Java](https://java-design-patterns.com/patterns/naked-objects/#when-to-use-the-naked-objects-pattern-in-java)

- When aiming to create a system where the domain objects can be easily understood and manipulated without an explicit user interface design.
- For applications requiring a dynamic, adaptable UI that reflects the underlying domain model with minimal developer intervention.

## [Real-World Applications of Naked Objects Pattern in Java](https://java-design-patterns.com/patterns/naked-objects/#real-world-applications-of-naked-objects-pattern-in-java)

- Enterprise applications where business rules and domain logic are primary.
- Systems that benefit from a dynamic and adaptive user interface.

## [Benefits and Trade-offs of Naked Objects Pattern](https://java-design-patterns.com/patterns/naked-objects/#benefits-and-trade-offs-of-naked-objects-pattern)

Benefits:

- Rapid development
- Improved maintainability
- Easy domain understanding
- Alignment between the UI and business model

Trade-offs:

- Reduced UI flexibility
- Potential over-exposure of the domain model
- Reliance on framework capabilities

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/naked-objects/#related-java-design-patterns)

Active Record: Similar in exposing domain models directly, but Active Record typically involves persistence aspects as well.

Domain-Driven Design: Shares the focus on domain modeling but without the automatic UI generation of Naked Objects.

## [References and Credits](https://java-design-patterns.com/patterns/naked-objects/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Naked Objects](https://amzn.to/3yhrfQr)
- [Naked Objects (Richard Pawson)](http://downloads.nakedobjects.net/resources/Pawson%20thesis.pdf)
- [Introducing Apache Isis (Apache Isis)](https://isis.apache.org/versions/1.16.0/pages/downloadable-presentations/resources/downloadable-presentations/IntroducingApacheIsis-notes.pdf)

---

## [architectural/page-controller] Page Controller
> 官方文档: https://java-design-patterns.com/patterns/page-controller/

ArchitecturalAPI designBusinessClient-serverDecouplingEnterprise patternsLayered architecturePresentationWeb developmentAbout 3 min

* * *

## [Intent of Page Controller Design Pattern](https://java-design-patterns.com/patterns/page-controller/#intent-of-page-controller-design-pattern)

The Page Controller pattern is intended to handle requests for a specific page or action within a web application, processing input, and determining the appropriate view for rendering the response.

## [Detailed Explanation of Page Controller Pattern with Real-World Examples](https://java-design-patterns.com/patterns/page-controller/#detailed-explanation-of-page-controller-pattern-with-real-world-examples)

Real-world example

> Imagine a large department store with multiple specialized counters: Customer Service, Returns, Electronics, and Clothing. Each counter has a dedicated staff member who handles specific tasks for that department.
>
> In this analogy, the department store is the web application, and each specialized counter represents a Page Controller. The Customer Service counter (Page Controller) handles customer inquiries, the Returns counter processes returns and exchanges, the Electronics counter assists with electronic goods, and the Clothing counter manages clothing-related requests. Each counter operates independently, addressing the specific needs of their respective department, just as each Page Controller handles requests for a specific page or action within the web application.

In plain words

> The Page Controller pattern handles requests for specific pages or actions within a Java web application, processing input, executing business logic, and determining the appropriate view for rendering the response, enhancing response handling and system architecture.

Architecture diagram

![Page Controller Architecture Diagram](https://java-design-patterns.com/assets/img/page-controller-architecture-diagram.84c756e3.png)

## [Programmatic Example of Page Controller Pattern in Java](https://java-design-patterns.com/patterns/page-controller/#programmatic-example-of-page-controller-pattern-in-java)

The Page Controller design pattern is a pattern used in web development where each page of a website is associated with a class or function known as a controller. The controller handles the HTTP requests for that page and determines which model and view to use. Predominantly utilized in MVC (Model-View-No-Controller) architectures, the Java Page Controller pattern integrates seamlessly with existing enterprise frameworks.

In the provided code, we have an example of the Page Controller pattern implemented using Spring Boot in Java. Let's break it down:

1. **SignupController**: This is a Page Controller for the signup page. It handles HTTP GET and POST requests at the "/signup" path. The GET request returns the signup page, and the POST request processes the signup form and redirects to the user page.

```java
@Controller
@Component
public class SignupController {
  SignupView view = new SignupView();

  @GetMapping("/signup")
  public String getSignup() {
    return view.display();
  }

  @PostMapping("/signup")
  public String create(SignupModel form, RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("name", form.getName());
    redirectAttributes.addAttribute("email", form.getEmail());
    redirectAttributes.addFlashAttribute("userInfo", form);
    return view.redirect(form);
  }
}
```

2. **UserController**: This is another Page Controller, this time for the user page. It handles HTTP GET requests at the "/user" path, returning the user page.

```java
@Slf4j
@Controller
public class UserController {
  UserView view = new UserView();

  @GetMapping("/user")
  public String getUserPath(SignupModel form, Model model) {
    model.addAttribute("name", form.getName());
    model.addAttribute("email", form.getEmail());
    return view.display(form);
  }
}
```

3. **SignupModel and UserModel**: These are the data models used by the controllers. They hold the data to be displayed on the page.

```java
@Component
@Getter
@Setter
public class SignupModel {
  private String name;
  private String email;
  private String password;
}

@Getter
@Setter
public class UserModel {
  private String name;
  private String email;
}
```

4. **SignupView and UserView**: These are the views used by the controllers. They determine how the data is presented to the user.

```java
@Slf4j
public class SignupView {
  public String display() {
    return "/signup";
  }

  public String redirect(SignupModel form) {
    return "redirect:/user";
  }
}

@Slf4j
public class UserView {
  public String display(SignupModel user) {
    return "/user";
  }
}
```

In this example, the controllers (`SignupController` and `UserController`) are the Page Controllers. They handle the HTTP requests for their respective pages and determine which model and view to use. The models (`SignupModel` and `UserModel`) hold the data for the page, and the views (`SignupView` and `UserView`) determine how that data is presented. This separation of concerns makes the code easier to manage and maintain.

## [When to Use the Page Controller Pattern in Java](https://java-design-patterns.com/patterns/page-controller/#when-to-use-the-page-controller-pattern-in-java)

- When developing a web application where each page or action needs specific processing.
- When aiming to separate the request handling logic from the view rendering logic.
- In scenarios where a clear separation of concerns between different layers (controller, view) is required.

## [Real-World Applications of Page Controller Pattern in Java](https://java-design-patterns.com/patterns/page-controller/#real-world-applications-of-page-controller-pattern-in-java)

- Spring MVC (Java)
- Apache Struts
- JSF (JavaServer Faces)

## [Benefits and Trade-offs of Page Controller Pattern](https://java-design-patterns.com/patterns/page-controller/#benefits-and-trade-offs-of-page-controller-pattern)

Benefits:

- [Separation of Concerns](https://java-design-patterns.com/principles/#separation-of-concerns): Clearly separates the controller logic from the view, making the application easier to manage and maintain.
- Reusability: Common logic can be reused across multiple controllers, reducing code duplication.
- Testability: Controllers can be tested independently of the view, improving unit test coverage.

Trade-offs:

- Complexity: Can add complexity to the application structure, requiring careful organization and documentation.
- Overhead: May introduce performance overhead due to additional layers of abstraction and processing.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/page-controller/#related-java-design-patterns)

- [Front Controller](https://java-design-patterns.com/patterns/front-controller/): Often used in conjunction with Page Controller to handle common pre-processing logic such as authentication and logging.
- View Helper: Works alongside Page Controller to assist in preparing the view, often handling formatting and other presentation logic.
- [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Page Controller is a fundamental part of the MVC architecture, acting as the Controller.

## [References and Credits](https://java-design-patterns.com/patterns/page-controller/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Page Controller (Martin Fowler)](https://www.martinfowler.com/eaaCatalog/pageController.html)

---

## [architectural/polling-publisher] Polling Publisher-Subscriber
> 官方文档: https://java-design-patterns.com/patterns/polling-publisher/

ArchitecturalSpring BootKafkaMicroservicesAsynchronous MessagingDecouplingAbout 2 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/polling-publisher/#also-known-as)

- Event-Driven Architecture
- Asynchronous Pub/Sub Pattern
- Message Queue-Based Polling System

## [Intent of Polling Publisher-Subscriber Pattern](https://java-design-patterns.com/patterns/polling-publisher/#intent-of-polling-publisher-subscriber-pattern)

The Polling Publisher-Subscriber pattern decouples data producers from consumers by enabling asynchronous, message-driven communication. A service polls a data source and publishes messages to a message broker (e.g., Kafka), which are then consumed by one or more subscriber services.

## [Detailed Explanation of the Pattern with Real-World Examples](https://java-design-patterns.com/patterns/polling-publisher/#detailed-explanation-of-the-pattern-with-real-world-examples)

### [Real-world analogy](https://java-design-patterns.com/patterns/polling-publisher/#real-world-analogy)

> A news agency constantly polls for the latest news updates. Once it receives new information, it publishes them to different news outlets (TV, newspapers, apps). Each outlet consumes and displays the updates independently.

### [In plain words](https://java-design-patterns.com/patterns/polling-publisher/#in-plain-words)

> One service regularly checks for updates (polls) and sends messages to Kafka. Another service listens to Kafka and processes the messages asynchronously.

### [Wikipedia says](https://java-design-patterns.com/patterns/polling-publisher/#wikipedia-says)

> This pattern closely resembles the [Publish–subscribe model](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern), where messages are sent by publishers and received by subscribers without them knowing each other.

### [Architecture Flow](https://java-design-patterns.com/patterns/polling-publisher/#architecture-flow)

```
+------------+      +--------+      +-------------+
|  Publisher | ---> | Kafka  | ---> | Subscriber  |
+------------+      +--------+      +-------------+
```

## [Programmatic Example (Spring Boot + Kafka)](https://java-design-patterns.com/patterns/polling-publisher/#programmatic-example-spring-boot-kafka)

### [Publisher Service](https://java-design-patterns.com/patterns/polling-publisher/#publisher-service)

- Uses Spring's `@Scheduled` to poll data periodically.
- Publishes data to a Kafka topic.
- Optionally exposes a REST API for manual data publishing.

```java
@Scheduled(fixedRate = 5000)
public void pollAndPublish() {
    String data = pollingService.getLatestData();
    kafkaTemplate.send("updates-topic", data);
}
```

### [Subscriber Service](https://java-design-patterns.com/patterns/polling-publisher/#subscriber-service)

- Listens to Kafka topic using `@KafkaListener`.
- Processes messages asynchronously.

```java
@KafkaListener(topics = "updates-topic")
public void processUpdate(String message) {
    log.info("Received update: {}", message);
    updateProcessor.handle(message);
}
```

## [When to Use the Polling Publisher-Subscriber Pattern](https://java-design-patterns.com/patterns/polling-publisher/#when-to-use-the-polling-publisher-subscriber-pattern)

Use this pattern when:

- Real-time push from the producer is not possible.
- Loose coupling between producers and consumers is desired.
- You need asynchronous, scalable event processing.
- You are building an event-driven microservices architecture.

## [Real-World Applications](https://java-design-patterns.com/patterns/polling-publisher/#real-world-applications)

- Real-time reporting dashboards
- Health check aggregators for distributed systems
- IoT telemetry processing
- Notification and alerting systems

## [Benefits and Trade-offs of Polling Pub/Sub Pattern](https://java-design-patterns.com/patterns/polling-publisher/#benefits-and-trade-offs-of-polling-pub-sub-pattern)

### [Benefits](https://java-design-patterns.com/patterns/polling-publisher/#benefits)

- Loose coupling between services
- Asynchronous and scalable architecture
- Fault-tolerant with message persistence in Kafka
- Easy to extend with new consumers or publishers

### [Trade-Offs](https://java-design-patterns.com/patterns/polling-publisher/#trade-offs)

- Polling introduces latency between data generation and consumption
- Requires managing and configuring Kafka (or other brokers)
- Slightly more complex deployment and infrastructure setup

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/polling-publisher/#related-java-design-patterns)

- [Observer Pattern](https://java-design-patterns.com/patterns/observer/)
- [Mediator Pattern](https://java-design-patterns.com/patterns/mediator/)
- [Message Queue Pattern](https://java-design-patterns.com/patterns/event-queue/)

## [References and Credits](https://java-design-patterns.com/patterns/polling-publisher/#references-and-credits)

- [Apache Kafka Documentation](https://kafka.apache.org/documentation/)
- [Spring Kafka Documentation](https://docs.spring.io/spring-kafka)
- [Spring Scheduled Tasks](https://www.baeldung.com/spring-scheduled-tasks)
- [Spring Kafka Tutorial – Baeldung](https://www.baeldung.com/spring-kafka)
- Inspired by: [iluwatar/java-design-patterns](https://github.com/iluwatar/java-design-patterns)

---

## [architectural/presentation-model] Presentation Model
> 官方文档: https://java-design-patterns.com/patterns/presentation-model/

ArchitecturalDecouplingEncapsulationPresentationTestingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/presentation-model/#also-known-as)

- Application Model

## [Intent of Presentation Model Design Pattern](https://java-design-patterns.com/patterns/presentation-model/#intent-of-presentation-model-design-pattern)

The Presentation Model pattern separates the logic of the user interface (UI) from the business logic by creating a model that represents the data and behavior of the UI independently.

## [Detailed Explanation of Presentation Model Pattern with Real-World Examples](https://java-design-patterns.com/patterns/presentation-model/#detailed-explanation-of-presentation-model-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Presentation Model design pattern is the relationship between a scriptwriter, an actor, and a director in a theater production. The scriptwriter creates the script (analogous to the business logic), which the actor then interprets and performs on stage (analogous to the user interface). The director acts as the intermediary, ensuring that the actor's performance aligns with the script and the vision of the play (similar to the Presentation Model coordinating the UI and the business logic). This separation allows the script to be rewritten without changing the actor's techniques or the director's interpretation, ensuring flexibility and maintainability.

In plain words

> The Presentation Model design pattern separates the UI logic from the business logic by creating an intermediate model that represents the data and behavior of the UI independently, enhancing testability, maintainability, and flexibility.

Architecture diagram

![Presentation Model Architecture Diagram](https://java-design-patterns.com/assets/img/presentation-model-architecture-diagram.ef52f7d0.png)

## [Programmatic Example of Presentation Model Pattern in Java](https://java-design-patterns.com/patterns/presentation-model/#programmatic-example-of-presentation-model-pattern-in-java)

The Presentation Model design pattern is a pattern that separates the responsibility of managing the state and behavior of the GUI in a separate model class. This model class is not tied to the view and can be used to test the GUI behavior independently of the GUI itself.

Let's take a look at the code provided and see how it implements the Presentation Model pattern.

First, we have the `Album` class. This class represents the data model in our application. It contains properties like `title`, `artist`, `isClassical`, and `composer`.

```java
@Setter
@Getter
@AllArgsConstructor
public class Album {
    private String title;
    private String artist;
    private boolean isClassical;
    private String composer;
}
```

Next, we have the `DisplayedAlbums` class. This class is responsible for managing a collection of `Album` objects.

```java
@Slf4j
@Getter
public class DisplayedAlbums {
    private final List<Album> albums;

    public DisplayedAlbums() {
        this.albums = new ArrayList<>();
    }

    public void addAlbums(final String title,
                          final String artist, final boolean isClassical,
                          final String composer) {
        if (isClassical) {
            this.albums.add(new Album(title, artist, true, composer));
        } else {
            this.albums.add(new Album(title, artist, false, ""));
        }
    }
}
```

The `PresentationModel` class is where the Presentation Model pattern is implemented. This class is responsible for managing the state and behavior of the GUI. It contains a reference to the `DisplayedAlbums` object and provides methods for interacting with the selected album.

```java
public class PresentationModel {

    private final DisplayedAlbums data;
    private int selectedAlbumNumber;
    private Album selectedAlbum;

    public PresentationModel(final DisplayedAlbums dataOfAlbums) {
        this.data = dataOfAlbums;
        this.selectedAlbumNumber = 1;
        this.selectedAlbum = this.data.getAlbums().get(0);
    }

    // other methods...
}
```

The `App` class is the entry point of the application. It creates a `View` object and calls its `createView` method to start the GUI.

```java
public final class App {
    public static void main(final String[] args) {
        var view = new View();
        view.createView();
    }
}
```

In this example, the `PresentationModel` class is the Presentation Model. It separates the GUI's state and behavior from the `View` class, allowing the GUI to be tested independently from the actual GUI components.

## [When to Use the Presentation Model Pattern in Java](https://java-design-patterns.com/patterns/presentation-model/#when-to-use-the-presentation-model-pattern-in-java)

Use the Presentation Model Pattern when

- Use when you want to decouple the UI from the underlying business logic to allow for easier testing, maintenance, and the ability to support multiple views or platforms.
- Ideal for applications where the UI changes frequently or needs to be different across various platforms while keeping the core logic intact.

## [Real-World Applications of Presentation Model Pattern in Java](https://java-design-patterns.com/patterns/presentation-model/#real-world-applications-of-presentation-model-pattern-in-java)

The Presentation Model pattern is used in:

- JavaFX applications: Utilizing JavaFX properties and bindings to create a clear separation between the UI and business logic.
- Swing applications: Employing a Presentation Model to decouple Swing components from the application logic, enhancing testability and flexibility.
- Android apps: Implementing MVVM architecture using ViewModel classes to manage UI-related data and lifecycle-aware components.

## [Benefits and Trade-offs of Presentation Model Pattern](https://java-design-patterns.com/patterns/presentation-model/#benefits-and-trade-offs-of-presentation-model-pattern)

Benefits:

- Decoupling: Enhances [separation of concerns](https://java-design-patterns.com/principles/#separation-of-concerns), making the system more modular and testable.
- Testability: Facilitates unit testing of UI logic without the need for actual UI components.
- Maintainability: Simplifies maintenance by isolating changes to the UI or business logic.
- Flexibility: Supports multiple views for the same model, making it easier to adapt the UI for different platforms.

Trade-offs:

- Complexity: Can introduce additional layers and complexity in the application architecture.
- Learning Curve: May require a deeper understanding of binding mechanisms and state management.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/presentation-model/#related-java-design-patterns)

- [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Similar in that it separates concerns, but Presentation Model encapsulates more of the view logic.
- [Model-View-Presenter (MVP)](https://java-design-patterns.com/patterns/model-view-presenter/): Another UI pattern focusing on separation of concerns, but with a different interaction model.
- [Observer](https://java-design-patterns.com/patterns/observer/): Often used within the Presentation Model to update the UI when the model changes.

## [References and Credits](https://java-design-patterns.com/patterns/presentation-model/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Presentation Model (Martin Fowler)](https://martinfowler.com/eaaDev/PresentationModel.html)

---

## [architectural/service-layer] Service Layer
> 官方文档: https://java-design-patterns.com/patterns/service-layer/

ArchitecturalAPI designBusinessDecouplingEnterprise patternsLayered architectureAbout 6 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/service-layer/#also-known-as)

- Application Facade

## [Intent of Service Layer Design Pattern](https://java-design-patterns.com/patterns/service-layer/#intent-of-service-layer-design-pattern)

The Service Layer pattern is crucial for Java developers focusing on building robust application architectures that separate business processes from user interface concerns.

The pattern encapsulate business logic in a distinct layer to promote separation of concerns and to provide a well-defined API for the presentation layer.

## [Detailed Explanation of Service Layer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/service-layer/#detailed-explanation-of-service-layer-pattern-with-real-world-examples)

Real-world example

> Imagine a complex restaurant system where orders are managed through a centralized 'service layer' to ensure efficient operation and clear communication between the front and back of the house. Each section specializes in a part of the meal, but the waitstaff don't interact directly with the kitchen staff. Instead, all orders go through a head chef who coordinates the workflow. The head chef acts like the service layer, handling the business logic (order coordination) and providing a unified interface for the waitstaff (presentation layer) to interact with the kitchen (data access layer).

In plain words

> A pattern that encapsulates business logic into a distinct layer to promote separation of concerns and provide a clear API for the presentation layer.

Wikipedia says

> Service layer is an architectural pattern, applied within the service-orientation design paradigm, which aims to organize the services, within a service inventory, into a set of logical layers. Services that are categorized into a particular layer share functionality. This helps to reduce the conceptual overhead related to managing the service inventory, as the services belonging to the same layer address a smaller set of activities.

Architecture diagram

![Service Layer Architecture Diagram](https://java-design-patterns.com/assets/img/service-layer-architecture-diagram.14916f41.png)

## [Programmatic Example of Service Layer Pattern in Java](https://java-design-patterns.com/patterns/service-layer/#programmatic-example-of-service-layer-pattern-in-java)

Our Java implementation uses the Service Layer pattern to streamline interactions between data access objects (DAOs) and the business logic, ensuring a clean separation of concerns.

The example application demonstrates interactions between a client `App` and a service `MagicService` that allows interaction between wizards, spellbooks and spells. The service is implemented with 3-layer architecture

(entity, dao, service).

For this explanation we are looking at one vertical slice of the system. Let's start from the entity layer and look at `Wizard` class. Other entities not shown here are `Spellbook` and `Spell`.

```java

@Entity
@Table(name = "WIZARD")
@Getter
@Setter
public class Wizard extends BaseEntity {

    @Id
    @GeneratedValue
    @Column(name = "WIZARD_ID")
    private Long id;

    private String name;

    @ManyToMany(cascade = CascadeType.ALL)
    private Set<Spellbook> spellbooks;

    public Wizard() {
        spellbooks = new HashSet<>();
    }

    public Wizard(String name) {
        this();
        this.name = name;
    }

    public void addSpellbook(Spellbook spellbook) {
        spellbook.getWizards().add(this);
        spellbooks.add(spellbook);
    }

    @Override
    public String toString() {
        return name;
    }
}
```

Above the entity layer we have DAOs. For `Wizard` the DAO layer looks as follows.

```java
public interface WizardDao extends Dao<Wizard> {

    Wizard findByName(String name);
}
```

```java
public class WizardDaoImpl extends DaoBaseImpl<Wizard> implements WizardDao {

    @Override
    public Wizard findByName(String name) {
        Transaction tx = null;
        Wizard result;
        try (var session = getSessionFactory().openSession()) {
            tx = session.beginTransaction();
            var criteria = session.createCriteria(persistentClass);
            criteria.add(Restrictions.eq("name", name));
            result = (Wizard) criteria.uniqueResult();
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        }
        return result;
    }
}
```

Next we can look at the Service Layer, which in our case consists of a single `MagicService`.

```java
public interface MagicService {

    List<Wizard> findAllWizards();

    List<Spellbook> findAllSpellbooks();

    List<Spell> findAllSpells();

    List<Wizard> findWizardsWithSpellbook(String name);

    List<Wizard> findWizardsWithSpell(String name);
}

public class MagicServiceImpl implements MagicService {

    private final WizardDao wizardDao;
    private final SpellbookDao spellbookDao;
    private final SpellDao spellDao;

    public MagicServiceImpl(WizardDao wizardDao, SpellbookDao spellbookDao, SpellDao spellDao) {
        this.wizardDao = wizardDao;
        this.spellbookDao = spellbookDao;
        this.spellDao = spellDao;
    }

    @Override
    public List<Wizard> findAllWizards() {
        return wizardDao.findAll();
    }

    @Override
    public List<Spellbook> findAllSpellbooks() {
        return spellbookDao.findAll();
    }

    @Override
    public List<Spell> findAllSpells() {
        return spellDao.findAll();
    }

    @Override
    public List<Wizard> findWizardsWithSpellbook(String name) {
        var spellbook = spellbookDao.findByName(name);
        return new ArrayList<>(spellbook.getWizards());
    }

    @Override
    public List<Wizard> findWizardsWithSpell(String name) {
        var spell = spellDao.findByName(name);
        var spellbook = spell.getSpellbook();
        return new ArrayList<>(spellbook.getWizards());
    }
}
```

And finally, we can show how the client `App` interacts with `MagicService` in the Service Layer.

```java
@Slf4j
public class App {

    public static final String BOOK_OF_IDORES = "Book of Idores";

    public static void main(String[] args) {
        // populate the in-memory database
        initData();
        // query the data using the service
        queryData();
    }

    public static void initData() {
        // spells
        var spell1 = new Spell("Ice dart");
        var spell2 = new Spell("Invisibility");
        var spell3 = new Spell("Stun bolt");
        var spell4 = new Spell("Confusion");
        var spell5 = new Spell("Darkness");
        var spell6 = new Spell("Fireball");
        var spell7 = new Spell("Enchant weapon");
        var spell8 = new Spell("Rock armour");
        var spell9 = new Spell("Light");
        var spell10 = new Spell("Bee swarm");
        var spell11 = new Spell("Haste");
        var spell12 = new Spell("Levitation");
        var spell13 = new Spell("Magic lock");
        var spell14 = new Spell("Summon hell bat");
        var spell15 = new Spell("Water walking");
        var spell16 = new Spell("Magic storm");
        var spell17 = new Spell("Entangle");
        var spellDao = new SpellDaoImpl();
        spellDao.persist(spell1);
        spellDao.persist(spell2);
        spellDao.persist(spell3);
        spellDao.persist(spell4);
        spellDao.persist(spell5);
        spellDao.persist(spell6);
        spellDao.persist(spell7);
        spellDao.persist(spell8);
        spellDao.persist(spell9);
        spellDao.persist(spell10);
        spellDao.persist(spell11);
        spellDao.persist(spell12);
        spellDao.persist(spell13);
        spellDao.persist(spell14);
        spellDao.persist(spell15);
        spellDao.persist(spell16);
        spellDao.persist(spell17);

        // spellbooks
        var spellbookDao = new SpellbookDaoImpl();
        var spellbook1 = new Spellbook("Book of Orgymon");
        spellbookDao.persist(spellbook1);
        spellbook1.addSpell(spell1);
        spellbook1.addSpell(spell2);
        spellbook1.addSpell(spell3);
        spellbook1.addSpell(spell4);
        spellbookDao.merge(spellbook1);
        var spellbook2 = new Spellbook("Book of Aras");
        spellbookDao.persist(spellbook2);
        spellbook2.addSpell(spell5);
        spellbook2.addSpell(spell6);
        spellbookDao.merge(spellbook2);
        var spellbook3 = new Spellbook("Book of Kritior");
        spellbookDao.persist(spellbook3);
        spellbook3.addSpell(spell7);
        spellbook3.addSpell(spell8);
        spellbook3.addSpell(spell9);
        spellbookDao.merge(spellbook3);
        var spellbook4 = new Spellbook("Book of Tamaex");
        spellbookDao.persist(spellbook4);
        spellbook4.addSpell(spell10);
        spellbook4.addSpell(spell11);
        spellbook4.addSpell(spell12);
        spellbookDao.merge(spellbook4);
        var spellbook5 = new Spellbook(BOOK_OF_IDORES);
        spellbookDao.persist(spellbook5);
        spellbook5.addSpell(spell13);
        spellbookDao.merge(spellbook5);
        var spellbook6 = new Spellbook("Book of Opaen");
        spellbookDao.persist(spellbook6);
        spellbook6.addSpell(spell14);
        spellbook6.addSpell(spell15);
        spellbookDao.merge(spellbook6);
        var spellbook7 = new Spellbook("Book of Kihione");
        spellbookDao.persist(spellbook7);
        spellbook7.addSpell(spell16);
        spellbook7.addSpell(spell17);
        spellbookDao.merge(spellbook7);

        // wizards
        var wizardDao = new WizardDaoImpl();
        var wizard1 = new Wizard("Aderlard Boud");
        wizardDao.persist(wizard1);
        wizard1.addSpellbook(spellbookDao.findByName("Book of Orgymon"));
        wizard1.addSpellbook(spellbookDao.findByName("Book of Aras"));
        wizardDao.merge(wizard1);
        var wizard2 = new Wizard("Anaxis Bajraktari");
        wizardDao.persist(wizard2);
        wizard2.addSpellbook(spellbookDao.findByName("Book of Kritior"));
        wizard2.addSpellbook(spellbookDao.findByName("Book of Tamaex"));
        wizardDao.merge(wizard2);
        var wizard3 = new Wizard("Xuban Munoa");
        wizardDao.persist(wizard3);
        wizard3.addSpellbook(spellbookDao.findByName(BOOK_OF_IDORES));
        wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen"));
        wizardDao.merge(wizard3);
        var wizard4 = new Wizard("Blasius Dehooge");
        wizardDao.persist(wizard4);
        wizard4.addSpellbook(spellbookDao.findByName("Book of Kihione"));
        wizardDao.merge(wizard4);
    }

    public static void queryData() {
        var wizardDao = new WizardDaoImpl();
        var spellbookDao = new SpellbookDaoImpl();
        var spellDao = new SpellDaoImpl();
        var service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao);
        LOGGER.info("Enumerating all wizards");
        service.findAllWizards().stream().map(Wizard::getName).forEach(LOGGER::info);
        LOGGER.info("Enumerating all spellbooks");
        service.findAllSpellbooks().stream().map(Spellbook::getName).forEach(LOGGER::info);
        LOGGER.info("Enumerating all spells");
        service.findAllSpells().stream().map(Spell::getName).forEach(LOGGER::info);
        LOGGER.info("Find wizards with spellbook 'Book of Idores'");
        var wizardsWithSpellbook = service.findWizardsWithSpellbook(BOOK_OF_IDORES);
        wizardsWithSpellbook.forEach(w -> LOGGER.info("{} has 'Book of Idores'", w.getName()));
        LOGGER.info("Find wizards with spell 'Fireball'");
        var wizardsWithSpell = service.findWizardsWithSpell("Fireball");
        wizardsWithSpell.forEach(w -> LOGGER.info("{} has 'Fireball'", w.getName()));
    }
}
```

The program output:

```
INFO  [2024-05-27 09:16:40,668] com.iluwatar.servicelayer.app.App: Enumerating all wizards
INFO  [2024-05-27 09:16:40,671] com.iluwatar.servicelayer.app.App: Aderlard Boud
INFO  [2024-05-27 09:16:40,671] com.iluwatar.servicelayer.app.App: Anaxis Bajraktari
INFO  [2024-05-27 09:16:40,671] com.iluwatar.servicelayer.app.App: Xuban Munoa
INFO  [2024-05-27 09:16:40,671] com.iluwatar.servicelayer.app.App: Blasius Dehooge
INFO  [2024-05-27 09:16:40,671] com.iluwatar.servicelayer.app.App: Enumerating all spellbooks
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Orgymon
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Aras
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Kritior
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Tamaex
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Idores
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Opaen
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Book of Kihione
INFO  [2024-05-27 09:16:40,675] com.iluwatar.servicelayer.app.App: Enumerating all spells
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Ice dart
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Invisibility
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Stun bolt
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Confusion
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Darkness
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Fireball
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Enchant weapon
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Rock armour
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Light
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Bee swarm
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Haste
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Levitation
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Magic lock
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Summon hell bat
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Water walking
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Magic storm
INFO  [2024-05-27 09:16:40,679] com.iluwatar.servicelayer.app.App: Entangle
INFO  [2024-05-27 09:16:40,680] com.iluwatar.servicelayer.app.App: Find wizards with spellbook 'Book of Idores'
INFO  [2024-05-27 09:16:40,680] com.iluwatar.servicelayer.app.App: Xuban Munoa has 'Book of Idores'
INFO  [2024-05-27 09:16:40,681] com.iluwatar.servicelayer.app.App: Find wizards with spell 'Fireball'
INFO  [2024-05-27 09:16:40,683] com.iluwatar.servicelayer.app.App: Aderlard Boud has 'Fireball'
```

## [When to Use the Service Layer Pattern in Java](https://java-design-patterns.com/patterns/service-layer/#when-to-use-the-service-layer-pattern-in-java)

- Use when you need to separate business logic from presentation logic.
- Ideal for applications with complex business rules and workflows.
- Suitable for projects requiring a clear API for the presentation layer.

## [Real-World Applications of Service Layer Pattern in Java](https://java-design-patterns.com/patterns/service-layer/#real-world-applications-of-service-layer-pattern-in-java)

- Java EE applications where Enterprise JavaBeans (EJB) are used to implement the service layer.
- Spring Framework applications using the @Service annotation to denote service layer classes.
- Web applications that need to separate business logic from controller logic.

## [Benefits and Trade-offs of Service Layer Pattern](https://java-design-patterns.com/patterns/service-layer/#benefits-and-trade-offs-of-service-layer-pattern)

Benefits:

Implementing a Service Layer in Java

- Promotes code reuse by encapsulating business logic in one place.
- Enhances testability by isolating business logic.
- Improves maintainability and flexibility of enterprise applications.

Trade-offs:

- May introduce additional complexity by adding another layer to the application.
- Can result in performance overhead due to the extra layer of abstraction.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/service-layer/#related-java-design-patterns)

- [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies interactions with complex subsystems by providing a unified interface.
- [DAO (Data Access Object)](https://java-design-patterns.com/patterns/dao/): Often used together with the Service Layer to handle data persistence.
- [MVC (Model-View-Controller)](https://java-design-patterns.com/patterns/model-view-controller/): The Service Layer can be used to encapsulate business logic in the model component.

## [References and Credits](https://java-design-patterns.com/patterns/service-layer/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Spring in Action](https://amzn.to/4asnpSG)
- [Service Layer (Martin Fowler)](http://martinfowler.com/eaaCatalog/serviceLayer.html)

---

## [architectural/service-to-worker] Service to Worker
> 官方文档: https://java-design-patterns.com/patterns/service-to-worker/

ArchitecturalBusinessDecouplingLayered architecturePresentationWeb developmentAbout 3 min

* * *

## [Intent of Service to Worker Design Pattern](https://java-design-patterns.com/patterns/service-to-worker/#intent-of-service-to-worker-design-pattern)

The Service to Worker design pattern in Java combines the Dispatcher View and Service Locator patterns to facilitate the separation of processing, control flow, and view management in web applications.

## [Detailed Explanation of Service to Worker Pattern with Real-World Examples](https://java-design-patterns.com/patterns/service-to-worker/#detailed-explanation-of-service-to-worker-pattern-with-real-world-examples)

Real-world example

> Imagine a large restaurant chain with a central kitchen and multiple waitstaff. When a customer places an order, the waitstaff (Controller) takes the order and hands it over to the kitchen (Service). The kitchen then processes the order, prepares the dish, and hands it back to the waitstaff. The waitstaff finally delivers the dish to the customer (View). This scenario mirrors Java web applications using the Service to Worker pattern, where backend logic (like the kitchen) is separated from frontend interactions (like the waitstaff), improving focus and efficiency in design pattern implementation.

In plain words

> Separates the processing logic from the view in web applications to improve maintainability and scalability.

Sequence diagram

![Service to Worker sequence diagram](https://java-design-patterns.com/assets/img/service-to-worker-sequence-diagram.bdc00160.png)

## [Programmatic Example of Service to Worker Pattern in Java](https://java-design-patterns.com/patterns/service-to-worker/#programmatic-example-of-service-to-worker-pattern-in-java)

The Service to Worker design pattern separates the processing logic from the view in web applications to improve maintainability and scalability. It combines the Dispatcher View and Service Locator patterns to facilitate the separation of processing, control flow, and view management in web applications.

In our example, we have a `GiantController` class, which acts as the controller in the Service to Worker pattern. It takes commands and updates the view. The `Dispatcher` class is responsible for performing actions and updating the view.

Here is the `GiantController` class:

```java
public class GiantController {

  public Dispatcher dispatcher;

  public GiantController(Dispatcher dispatcher) {
    this.dispatcher = dispatcher;
  }

  public void setCommand(Command s, int index) {
    dispatcher.performAction(s, index);
  }

  public void updateView(GiantModel giantModel) {
    dispatcher.updateView(giantModel);
  }
}
```

In the `GiantController` class, we have a `setCommand` method that takes a `Command` and an index. This method is used to control the dispatcher. The `updateView` method is used to update the view with the provided `GiantModel`.

The `App` class is the entry point of our application:

```java
public class App {

  public static void main(String[] args) {
    var giant1 = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
    var giant2 = new GiantModel("giant2", Health.DEAD, Fatigue.SLEEPING, Nourishment.STARVING);
    var action1 = new Action(giant1);
    var action2 = new Action(giant2);
    var view = new GiantView();
    var dispatcher = new Dispatcher(view);
    dispatcher.addAction(action1);
    dispatcher.addAction(action2);
    var controller = new GiantController(dispatcher);

    controller.updateView(giant1);
    controller.updateView(giant2);

    controller.setCommand(new Command(Fatigue.SLEEPING, Health.HEALTHY, Nourishment.STARVING), 0);
    controller.setCommand(new Command(Fatigue.ALERT, Health.HEALTHY, Nourishment.HUNGRY), 1);

    controller.updateView(giant1);
    controller.updateView(giant2);
  }
}
```

In the `main` method, we create two `GiantModel` instances, `giant1` and `giant2`, and two `Action` instances, `action1` and `action2`. We then create a `GiantView` instance and a `Dispatcher` instance. We add `action1` and `action2` to the `Dispatcher` and create a `GiantController` with the `Dispatcher`. We then update the view with `giant1` and `giant2`, set some commands, and update the view again.

Console output:

```
12:23:10.895 [main] INFO com.iluwatar.servicetoworker.GiantView -- Giant giant1, The giant looks healthy, alert and saturated.
12:23:10.897 [main] INFO com.iluwatar.servicetoworker.GiantView -- Giant giant2, The giant looks dead, sleeping and starving.
12:23:10.897 [main] INFO com.iluwatar.servicetoworker.GiantView -- Giant giant1, The giant looks healthy, sleeping and starving.
12:23:10.897 [main] INFO com.iluwatar.servicetoworker.GiantView -- Giant giant2, The giant looks healthy, alert and hungry.
```

This is a simple example of how the Service to Worker pattern can be implemented in a Java application.

## [When to Use the Service to Worker Pattern in Java](https://java-design-patterns.com/patterns/service-to-worker/#when-to-use-the-service-to-worker-pattern-in-java)

- Use when you need to separate the controller logic from the view to improve code maintainability and enable team members to work on different parts of the application independently.
- Suitable for Java web applications that utilize MVC architecture.
- Appropriate for scenarios requiring complex request processing before displaying a view.

## [Real-World Applications of Service to Worker Pattern in Java](https://java-design-patterns.com/patterns/service-to-worker/#real-world-applications-of-service-to-worker-pattern-in-java)

- Java-based web frameworks like Struts and Spring MVC.
- Enterprise web applications requiring a clean separation between presentation logic and business logic.

## [Benefits and Trade-offs of Service to Worker Pattern](https://java-design-patterns.com/patterns/service-to-worker/#benefits-and-trade-offs-of-service-to-worker-pattern)

Benefits:

- Enhances code maintainability by separating concerns.
- Facilitates team collaboration by decoupling the controller and view components.
- Simplifies the addition of new views and modifications to existing ones.

Trade-offs:

- Increases the complexity of the application structure.
- May introduce additional overhead due to the layered architecture.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/service-to-worker/#related-java-design-patterns)

- [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Service to Worker is a specialized form of MVC, focusing on separating request handling and view management.
- [Front Controller](https://java-design-patterns.com/patterns/front-controller/): Often used in conjunction with Service to Worker to centralize request handling and routing.

## [References and Credits](https://java-design-patterns.com/patterns/service-to-worker/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [architectural/view-helper] View Helper
> 官方文档: https://java-design-patterns.com/patterns/view-helper/

ArchitecturalArchitecturePresentationDecouplingCode reuseAbout 3 min

* * *

## [Intent of View Helper Design Pattern](https://java-design-patterns.com/patterns/view-helper/#intent-of-view-helper-design-pattern)

The View Helper Design Pattern separates presentation logic from the view by delegating complex UI tasks — like formatting or conditional display — to reusable helper components. This keeps views clean, promotes reuse, and aligns with the MVC principle of separating concerns between the view and the business logic.

## [Detailed Explanation with Real‑World Analogy](https://java-design-patterns.com/patterns/view-helper/#detailed-explanation-with-real%E2%80%90world-analogy)

Real‑world example

> Imagine you're putting together a slideshow for a business presentation. You focus on arranging the slides, choosing the layout, and telling the story. But for tasks like resizing images, formatting charts, or converting data into visual form, you use tools or templates that automate those parts.
>
> In this analogy, you are the view, and the tools/templates are the helpers. They handle the heavy lifting behind the scenes so you can concentrate on the presentation. Similarly, in the View Helper pattern, the view delegates logic-heavy tasks—such as formatting or conditionally displaying data—to helper classes, keeping the view layer clean and presentation-focused.

### [In plain words](https://java-design-patterns.com/patterns/view-helper/#in-plain-words)

> The View Helper pattern is about keeping your UI code clean by moving any logic—like formatting, calculations, or decision-making—into separate helper classes. Instead of stuffing all the logic into the HTML or template files, you delegate it to helpers, so the view just focuses on showing the final result.

### [Sequence diagram](https://java-design-patterns.com/patterns/view-helper/#sequence-diagram)

![Sequence diagram for View Helper](https://java-design-patterns.com/assets/img/view-helper-sequence-diagram.3f553c4e.png)

## [Programmatic Example of View Helper Pattern in Java](https://java-design-patterns.com/patterns/view-helper/#programmatic-example-of-view-helper-pattern-in-java)

Raw domain object

```java
public record Product(String name, BigDecimal price, LocalDate releaseDate, boolean discounted) {}
```

View model object for display

```java
public record ProductViewModel(String name, String price, String releasedDate) {}
```

View Helper formats data for display

```java
class ProductViewHelper implements ViewHelper<Product, ProductViewModel> {

  private static final String DISCOUNT_TAG = " (ON SALE)";

  public ProductViewModel prepare(Product product) {
    var displayName = product.name() + (product.discounted() ? DISCOUNT_TAG : "");
    var priceWithCurrency = NumberFormat.getCurrencyInstance(US).format(product.price());
    var formattedDate = product.releaseDate().format(ISO_DATE);

    return new ProductViewModel(displayName, priceWithCurrency, formattedDate);
  }
}
```

View renders the formatted data

```java
public class ConsoleProductView implements View<ProductViewModel> {

  @Override
  public void render(ProductViewModel productViewModel) {
    LOGGER.info(productViewModel.toString());
  }
}
```

The `App.java` class simulates how the View Helper pattern works in a real application. It starts with a raw `Product` object containing unformatted data.

Then it:

1. Initializes a helper (`ProductViewHelper`) to format the product data for display.
2. Creates a view (`ConsoleProductView`) to render the formatted data.
3. Uses a controller (`ProductController`) to coordinate the flow between raw data, helper logic, and view rendering.

Finally, it simulates a user request by passing the product to the controller, which prepares the view model using the helper and displays it using the view. This demonstrates a clean separation between data, presentation logic, and rendering.

## [When to Use the View Helper Pattern in Java](https://java-design-patterns.com/patterns/view-helper/#when-to-use-the-view-helper-pattern-in-java)

Use the View Helper pattern when your view layer starts containing logic such as formatting data, applying conditional styles, or transforming domain objects for display. It's especially useful in MVC architectures where you want to keep views clean and focused on rendering, while delegating non-trivial presentation logic to reusable helper classes. This pattern helps improve maintainability, testability, and separation of concerns in your application's UI layer.

## [Real‑World Uses of View Helper Pattern in Java](https://java-design-patterns.com/patterns/view-helper/#real%E2%80%90world-uses-of-view-helper-pattern-in-java)

The View Helper pattern is widely used in web frameworks that follow the MVC architecture. In Java-based web applications (e.g., JSP, Spring MVC), it's common to use helper classes or utility methods to format dates, currencies, or apply conditional logic before rendering views. Technologies like Thymeleaf or JSF often rely on custom tags or expression helpers to achieve the same effect.

## [Benefits and Trade‑offs](https://java-design-patterns.com/patterns/view-helper/#benefits-and-trade%E2%80%90offs)

Benefits:

- Separation of concerns: Keeps view templates clean by moving logic into dedicated helpers.
- Reusability: Common formatting and display logic can be reused across multiple views.
- Improved maintainability: Easier to update presentation logic without touching the view.
- Testability: Helpers can be unit tested independently from the UI layer.

Trade‑offs:

- Added complexity: Introduces extra classes, which may feel unnecessary for very simple views.
- Overuse risk: Excessive use of helpers can spread logic thinly across many files, making it harder to trace behavior.
- Tight coupling risk: If not designed carefully, helpers can become tightly coupled to specific views or data formats.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/view-helper/#related-java-design-patterns)

- [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): View Helper supports the View layer in MVC by offloading logic from the view to helper classes.
- [Template Method](https://java-design-patterns.com/patterns/template-method/): Can structure the steps of rendering or data transformation, with helpers handling specific formatting tasks.
- [Data Transfer Object (DTO)](https://java-design-patterns.com/patterns/data-transfer-object/): Often used alongside View Helper when transferring raw data that needs formatting before being displayed.

## [References & Credits](https://java-design-patterns.com/patterns/view-helper/#references-credits)

- [Core J2EE Patterns: View Helper.](https://www.oracle.com/java/technologies/viewhelper.html)

---

<!-- ============================================ -->
<!-- Concurrency 并发模式 (22 个) -->
<!-- ============================================ -->

## [concurrency/active-object] Active Object
> 官方文档: https://java-design-patterns.com/patterns/active-object/

ConcurrencyAsynchronousDecouplingMessagingSynchronizationThread managementAbout 4 min

* * *

## [Intent of Active Object Design Pattern](https://java-design-patterns.com/patterns/active-object/#intent-of-active-object-design-pattern)

The Active Object pattern provides a reliable method for asynchronous processing in Java, ensuring responsive applications and efficient thread management. It achieves this by encapsulating tasks within objects that have their own thread and message queue. This separation keeps the main thread responsive and avoids issues like direct thread manipulation or shared state access.

## [Detailed Explanation of Active Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/active-object/#detailed-explanation-of-active-object-pattern-with-real-world-examples)

Real-world example

> Imagine a busy restaurant where customers place orders with waiters. Instead of the waiters going to the kitchen to prepare the food themselves, they write the orders on slips and hand them to a dispatcher. The dispatcher manages a pool of chefs who prepare the meals asynchronously. Once a chef is free, they pick up the next order from the queue, prepare the dish, and notify the waiter when it's ready for serving.
>
> In this analogy, the waiters represent the client threads, the dispatcher represents the scheduler, and the chefs represent the method execution in separate threads. This setup allows the waiters to continue taking orders without being blocked by the food preparation process, much like the Active Object pattern decouples method invocation from execution to enhance concurrency.

In plain words

> The Active Object pattern decouples method execution from method invocation to improve concurrency and responsiveness in multithreaded applications.

Wikipedia says

> The active object design pattern decouples method execution from method invocation for objects that each reside in their own thread of control.\[1\] The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.
>
> The pattern consists of six elements:
>
> - A proxy, which provides an interface towards clients with publicly accessible methods.
> - An interface which defines the method request on an active object.
> - A list of pending requests from clients.
> - A scheduler, which decides which request to execute next.
> - The implementation of the active object method.
> - A callback or variable for the client to receive the result.

Sequence diagram

![Active Object sequence diagram](https://java-design-patterns.com/assets/img/active-object-sequence-diagram.0d1b1a13.png)

## [Programmatic Example of Active Object in Java](https://java-design-patterns.com/patterns/active-object/#programmatic-example-of-active-object-in-java)

This section explains how the Active Object design pattern works in Java, highlighting its use in asynchronous task management and concurrency control.

The Orcs are known for their wildness and untameable soul. It seems like they have their own thread of control based on previous behavior. To implement a creature that has its own thread of control mechanism and expose its API only and not the execution itself, we can use the Active Object pattern.

```java
public abstract class ActiveCreature {
    private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName());

    private BlockingQueue<Runnable> requests;

    private String name;

    private Thread thread;

    public ActiveCreature(String name) {
        this.name = name;
        this.requests = new LinkedBlockingQueue<Runnable>();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        requests.take().run();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage());
                    }
                }
            }
        }
        );
        thread.start();
    }

    public void eat() throws InterruptedException {
        requests.put(new Runnable() {
                         @Override
                         public void run() {
                             logger.info("{} is eating!", name());
                             logger.info("{} has finished eating!", name());
                         }
                     }
        );
    }

    public void roam() throws InterruptedException {
        requests.put(new Runnable() {
                         @Override
                         public void run() {
                             logger.info("{} has started to roam the wastelands.", name());
                         }
                     }
        );
    }

    public String name() {
        return this.name;
    }
}
```

We can see that any class that will extend the `ActiveCreature` class will have its own thread of control to invoke and execute methods.

For example, the `Orc` class:

```java
public class Orc extends ActiveCreature {

    public Orc(String name) {
        super(name);
    }
}
```

Now, we can create multiple creatures such as orcs, tell them to eat and roam, and they will execute it on their own thread of control:

```java
public class App implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(App.class.getName());

    private static final int NUM_CREATURES = 3;

    public static void main(String[] args) {
        var app = new App();
        app.run();
    }

    @Override
    public void run() {
        List<ActiveCreature> creatures = new ArrayList<>();
        try {
            for (int i = 0; i < NUM_CREATURES; i++) {
                creatures.add(new Orc(Orc.class.getSimpleName() + i));
                creatures.get(i).eat();
                creatures.get(i).roam();
            }
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
            Thread.currentThread().interrupt();
        } finally {
            for (int i = 0; i < NUM_CREATURES; i++) {
                creatures.get(i).kill(0);
            }
        }
    }
}
```

Program output:

```
09:00:02.501 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 is eating!
09:00:02.501 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 is eating!
09:00:02.501 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 is eating!
09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has finished eating!
09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has finished eating!
09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has started to roam in the wastelands.
09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has finished eating!
09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has started to roam in the wastelands.
09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands.
```

## [When to Use the Active Object Pattern in Java](https://java-design-patterns.com/patterns/active-object/#when-to-use-the-active-object-pattern-in-java)

Use the Active Object pattern in Java when:

- when you need to handle asynchronous tasks without blocking the main thread, ensuring better performance and responsiveness.
- When you need to interact with external resources asynchronously.
- When you want to improve the responsiveness of your application.
- When you need to manage concurrent tasks in a modular and maintainable way.

## [Active Object Pattern Java Tutorials](https://java-design-patterns.com/patterns/active-object/#active-object-pattern-java-tutorials)

- [Android and Java Concurrency: The Active Object Pattern(Douglas Schmidt)](https://www.youtube.com/watch?v=Cd8t2u5Qmvc)

## [Real-World Applications of Active Object Pattern in Java](https://java-design-patterns.com/patterns/active-object/#real-world-applications-of-active-object-pattern-in-java)

- Real-time trading systems where transaction requests are handled asynchronously.
- GUIs where long-running tasks are executed in the background without freezing the user interface.
- Game programming to handle concurrent updates to game state or AI computations.

## [Benefits and Trade-offs of Active Object Pattern](https://java-design-patterns.com/patterns/active-object/#benefits-and-trade-offs-of-active-object-pattern)

Discover the benefits and trade-offs of using the Active Object pattern in Java, including improved thread safety and potential overhead concerns.

Benefits:

- Improves responsiveness of the main thread.
- Encapsulates concurrency concerns within objects.
- Promotes better code organization and maintainability.
- Provides thread safety and avoids shared state access problems.

Trade-offs:

- Introduces additional overhead due to message passing and thread management.
- May not be suitable for all types of concurrency problems.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/active-object/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/): Encapsulates a request as an object, similarly to how the Active Object pattern encapsulates method calls.
- [Promise](https://java-design-patterns.com/patterns/promise/): Provides a means to retrieve the result of an asynchronous method call, often used in conjunction with Active Object.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): The Active Object pattern can use a proxy to handle method invocations asynchronously.

## [References and Credits](https://java-design-patterns.com/patterns/active-object/#references-and-credits)

- [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE)
- [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Learning Concurrent Programming in Scala](https://amzn.to/3UE07nV)
- [Pattern Languages of Program Design 3](https://amzn.to/3OI1j61)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)

---

## [concurrency/actor-model] Actor Model
> 官方文档: https://java-design-patterns.com/patterns/actor-model/

ConcurrencyConcurrencyMessagingIsolationAsynchronousDistributed SystemsActor ModelAbout 2 min

* * *

## [Also Known As](https://java-design-patterns.com/patterns/actor-model/#also-known-as)

- Message-passing concurrency
- Actor-based concurrency

* * *

## [Intent of Actor Model Pattern](https://java-design-patterns.com/patterns/actor-model/#intent-of-actor-model-pattern)

The Actor Model pattern enables the construction of highly concurrent, distributed, and fault-tolerant systems by using isolated components (actors) that interact exclusively through asynchronous message passing.

* * *

## [Detailed Explanation of Actor Model Pattern with Real-World Examples](https://java-design-patterns.com/patterns/actor-model/#detailed-explanation-of-actor-model-pattern-with-real-world-examples)

### [📦 Real-world Example](https://java-design-patterns.com/patterns/actor-model/#%F0%9F%93%A6-real-world-example)

Imagine a customer service system:

- Each **customer support agent** is an **actor**.
- Customers **send questions (messages)** to agents.
- Each agent handles one request at a time and can **respond asynchronously** without interfering with other agents.

* * *

### [🧠 In Plain Words](https://java-design-patterns.com/patterns/actor-model/#%F0%9F%A7%A0-in-plain-words)

> "Actors are like independent workers that never share memory and only communicate through messages."

* * *

### [📖 Wikipedia Says](https://java-design-patterns.com/patterns/actor-model/#%F0%9F%93%96-wikipedia-says)

> [Actor model](https://en.wikipedia.org/wiki/Actor_model) is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent computation.

* * *

### [🧹 Architecture Diagram](https://java-design-patterns.com/patterns/actor-model/#%F0%9F%A7%B9-architecture-diagram)

![UML Class Diagram](https://java-design-patterns.com/assets/img/Actor_Model_UML_Class_Diagram.818a6b21.png)

* * *

## [Programmatic Example of Actor Model Pattern in Java](https://java-design-patterns.com/patterns/actor-model/#programmatic-example-of-actor-model-pattern-in-java)

### [Actor.java](https://java-design-patterns.com/patterns/actor-model/#actor-java)

```java
public abstract class Actor implements Runnable {

    @Setter @Getter private String actorId;
    private final BlockingQueue<Message> mailbox = new LinkedBlockingQueue<>();
    private volatile boolean active = true;

    public void send(Message message) {
        mailbox.add(message);
    }

    public void stop() {
        active = false;
    }

    @Override
    public void run() {

    }

    protected abstract void onReceive(Message message);
}
```

### [Message.java](https://java-design-patterns.com/patterns/actor-model/#message-java)

```java

@AllArgsConstructor
@Getter
@Setter
public class Message {
    private final String content;
    private final String senderId;
}
```

### [ActorSystem.java](https://java-design-patterns.com/patterns/actor-model/#actorsystem-java)

```java
public class ActorSystem {
    public void startActor(Actor actor) {
        String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID
        actor.setActorId(actorId); // assign the actor it's ID
        actorRegister.put(actorId, actor); // Register and save the actor with it's ID
        executor.submit(actor); // Run the actor in a thread
    }
    public Actor getActorById(String actorId) {
        return actorRegister.get(actorId); //  Find by Id
    }

    public void shutdown() {
        executor.shutdownNow(); // Stop all threads
    }
}
```

### [App.java](https://java-design-patterns.com/patterns/actor-model/#app-java)

```java
public class App {
  public static void main(String[] args) {
    ActorSystem system = new ActorSystem();
      Actor srijan = new ExampleActor(system);
      Actor ansh = new ExampleActor2(system);

      system.startActor(srijan);
      system.startActor(ansh);
      ansh.send(new Message("Hello ansh", srijan.getActorId()));
      srijan.send(new Message("Hello srijan!", ansh.getActorId()));

      Thread.sleep(1000); // Give time for messages to process

      srijan.stop(); // Stop the actor gracefully
      ansh.stop();
      system.shutdown(); // Stop the actor system
  }
}
```

* * *

## [When to Use the Actor Model Pattern in Java](https://java-design-patterns.com/patterns/actor-model/#when-to-use-the-actor-model-pattern-in-java)

- When building **concurrent or distributed systems**
- When you want **no shared mutable state**
- When you need **asynchronous, message-driven communication**
- When components should be **isolated and loosely coupled**

* * *

## [Actor Model Pattern Java Tutorials](https://java-design-patterns.com/patterns/actor-model/#actor-model-pattern-java-tutorials)

- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka)
- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143)

* * *

## [Real-World Applications of Actor Model Pattern in Java](https://java-design-patterns.com/patterns/actor-model/#real-world-applications-of-actor-model-pattern-in-java)

- [Akka Framework](https://akka.io/)
- [Erlang and Elixir concurrency](https://www.erlang.org/)
- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/)
- JVM-based game engines and simulators

* * *

## [Benefits and Trade-offs of Actor Model Pattern](https://java-design-patterns.com/patterns/actor-model/#benefits-and-trade-offs-of-actor-model-pattern)

### [✅ Benefits](https://java-design-patterns.com/patterns/actor-model/#%E2%9C%85-benefits)

- High concurrency support
- Easy scaling across threads or machines
- Fault isolation and recovery
- Message ordering within actors

### [⚠️ Trade-offs](https://java-design-patterns.com/patterns/actor-model/#%E2%9A%A0%EF%B8%8F-trade-offs)

- Harder to debug due to asynchronous behavior
- Slight performance overhead due to message queues
- More complex to design than simple method calls

* * *

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/actor-model/#related-java-design-patterns)

- [Command Pattern](https://java-design-patterns.com/patterns/command)
- [Mediator Pattern](https://java-design-patterns.com/patterns/mediator)
- [Event-Driven Architecture](https://java-design-patterns.com/patterns/event-driven-architecture)
- [Observer Pattern](https://java-design-patterns.com/patterns/observer)

* * *

## [References and Credits](https://java-design-patterns.com/patterns/actor-model/#references-and-credits)

- _Programming Erlang_, Joe Armstrong
- _Reactive Design Patterns_, Roland Kuhn
- _The Actor Model in 10 Minutes_, [InfoQ Article](https://www.infoq.com/articles/actor-model/)
- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html)

giscus

#### 0 reactions

#### 0 comments

WritePreview

[Styling with Markdown is supported](https://guides.github.com/features/mastering-markdown/ "Styling with Markdown is supported")

[Sign in with GitHub](https://giscus.app/api/oauth/authorize?redirect_uri=https%3A%2F%2Fjava-design-patterns.com%2Fpatterns%2Factor-model%2F)

---

## [concurrency/async-method-invocation] Async Method Invocation
> 官方文档: https://java-design-patterns.com/patterns/async-method-invocation/

ConcurrencyAsynchronousDecouplingReactiveScalabilityThread managementAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/async-method-invocation/#also-known-as)

- Asynchronous Procedure Call

## [Intent of Async Method Invocation Design Pattern](https://java-design-patterns.com/patterns/async-method-invocation/#intent-of-async-method-invocation-design-pattern)

The Async Method Invocation pattern is designed to enhance concurrency by allowing methods to be called asynchronously. This pattern helps in executing parallel tasks, reducing wait times, and improving system throughput.

## [Detailed Explanation of Async Method Invocation Pattern with Real-World Examples](https://java-design-patterns.com/patterns/async-method-invocation/#detailed-explanation-of-async-method-invocation-pattern-with-real-world-examples)

Real-world example

> Asynchronous method invocation enables non-blocking operations, allowing multiple processes to run concurrently. This pattern is particularly useful in applications requiring high scalability and performance, such as web servers and microservices.
>
> In the context of space rockets, an analogous example of the Async Method Invocation pattern can be seen in the communication between the mission control center and the onboard systems of the rocket. When mission control sends a command to the rocket to adjust its trajectory or perform a system check, they do not wait idly for the rocket to complete the task and report back. Instead, mission control continues to monitor other aspects of the mission and manage different tasks. The rocket executes the command asynchronously and sends a status update or result back to mission control once the operation is complete. This allows mission control to efficiently manage multiple concurrent operations without being blocked by any single task, similar to how asynchronous method invocation works in software systems.

In plain words

> Asynchronous method invocation starts task processing and returns immediately before the task is ready. The results of the task processing are returned to the caller later.

Wikipedia says

> In multithreaded computer programming, asynchronous method invocation (AMI), also known as asynchronous method calls or the asynchronous pattern is a design pattern in which the call site is not blocked while waiting for the called code to finish. Instead, the calling thread is notified when the reply arrives. Polling for a reply is an undesired option.

Sequence diagram

![Async Method Invocation sequence diagram](https://java-design-patterns.com/assets/img/async-method-invocation-sequence-diagram.e58675b7.png)

## [Programmatic Example of Async Method Invocation Pattern in Java](https://java-design-patterns.com/patterns/async-method-invocation/#programmatic-example-of-async-method-invocation-pattern-in-java)

Consider a scenario where multiple tasks need to be executed simultaneously. Using the Async Method Invocation pattern, you can initiate these tasks without waiting for each to complete, thus optimizing resource usage and reducing latency.

In this example, we are launching space rockets and deploying lunar rovers.

The application demonstrates the async method invocation pattern. The key parts of the pattern are`AsyncResult` which is an intermediate container for an asynchronously evaluated value, `AsyncCallback` which can be provided to be executed on task completion and `AsyncExecutor` that manages the execution of the async tasks.

```java
public interface AsyncResult<T> {
    boolean isCompleted();

    T getValue() throws ExecutionException;

    void await() throws InterruptedException;
}
```

```java
public interface AsyncCallback<T> {
    void onComplete(T value);

    void onError(Exception ex);
}
```

```java
public interface AsyncExecutor {
    <T> AsyncResult<T> startProcess(Callable<T> task);

    <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);

    <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
}
```

`ThreadAsyncExecutor` is an implementation of `AsyncExecutor`. Some of its key parts are highlighted next.

```java
public class ThreadAsyncExecutor implements AsyncExecutor {

    @Override
    public <T> AsyncResult<T> startProcess(Callable<T> task) {
        return startProcess(task, null);
    }

    @Override
    public <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback) {
        var result = new CompletableResult<>(callback);
        new Thread(
                () -> {
                    try {
                        result.setValue(task.call());
                    } catch (Exception ex) {
                        result.setException(ex);
                    }
                },
                "executor-" + idx.incrementAndGet())
                .start();
        return result;
    }

    @Override
    public <T> T endProcess(AsyncResult<T> asyncResult)
            throws ExecutionException, InterruptedException {
        if (!asyncResult.isCompleted()) {
            asyncResult.await();
        }
        return asyncResult.getValue();
    }
}
```

Then we are ready to launch some rockets to see how everything works together.

```java
  public static void main(String[] args) throws Exception {
    // construct a new executor that will run async tasks
    var executor = new ThreadAsyncExecutor();

    // start few async tasks with varying processing times, two last with callback handlers
    final var asyncResult1 = executor.startProcess(lazyval(10, 500));
    final var asyncResult2 = executor.startProcess(lazyval("test", 300));
    final var asyncResult3 = executor.startProcess(lazyval(50L, 700));
    final var asyncResult4 = executor.startProcess(lazyval(20, 400),
            callback("Deploying lunar rover"));
    final var asyncResult5 =
            executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover"));

    // emulate processing in the current thread while async tasks are running in their own threads
    Thread.sleep(350); // Oh boy, we are working hard here
    log("Mission command is sipping coffee");

    // wait for completion of the tasks
    final var result1 = executor.endProcess(asyncResult1);
    final var result2 = executor.endProcess(asyncResult2);
    final var result3 = executor.endProcess(asyncResult3);
    asyncResult4.await();
    asyncResult5.await();

    // log the results of the tasks, callbacks log immediately when complete
    log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result1));
    log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result2));
    log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result3));
}
```

Here's the program console output.

```
21:47:08.227[executor-2]INFO com.iluwatar.async.method.invocation.App-Space rocket<test> launched successfully
21:47:08.269[main]INFO com.iluwatar.async.method.invocation.App-Mission command is sipping coffee
21:47:08.318[executor-4]INFO com.iluwatar.async.method.invocation.App-Space rocket<20>launched successfully
21:47:08.335[executor-4]INFO com.iluwatar.async.method.invocation.App-Deploying lunar rover<20>
21:47:08.414[executor-1]INFO com.iluwatar.async.method.invocation.App-Space rocket<10>launched successfully
21:47:08.519[executor-5]INFO com.iluwatar.async.method.invocation.App-Space rocket<callback> launched successfully
21:47:08.519[executor-5]INFO com.iluwatar.async.method.invocation.App-Deploying lunar rover<callback>
21:47:08.616[executor-3]INFO com.iluwatar.async.method.invocation.App-Space rocket<50>launched successfully
21:47:08.617[main]INFO com.iluwatar.async.method.invocation.App-Space rocket<10>launch complete
21:47:08.617[main]INFO com.iluwatar.async.method.invocation.App-Space rocket<test> launch complete
21:47:08.618[main]INFO com.iluwatar.async.method.invocation.App-Space rocket<50>launch complete
```

## [When to Use the Async Method Invocation Pattern in Java](https://java-design-patterns.com/patterns/async-method-invocation/#when-to-use-the-async-method-invocation-pattern-in-java)

This pattern is ideal for applications needing to manage multiple parallel tasks efficiently. It is commonly used in scenarios such as handling background processes, improving user interface responsiveness, and managing asynchronous data processing.

Use the async method invocation pattern when

- When operations do not need to complete before proceeding with the next steps in a program.
- For tasks that are resource-intensive or time-consuming, such as IO operations, network requests, or complex computations, where making the operation synchronous would significantly impact performance or user experience.
- In GUI applications to prevent freezing or unresponsiveness during long-running tasks.
- In web applications for non-blocking IO operations.

## [Real-World Applications of Async Method Invocation Pattern in Java](https://java-design-patterns.com/patterns/async-method-invocation/#real-world-applications-of-async-method-invocation-pattern-in-java)

Many modern applications leverage the Async Method Invocation pattern, including web servers handling concurrent requests, microservices architectures, and systems requiring intensive background processing.

- Web servers handling HTTP requests asynchronously to improve throughput and reduce latency.
- Desktop and mobile applications using background threads to perform time-consuming operations without blocking the user interface.
- Microservices architectures where services perform asynchronous communications via messaging queues or event streams.
- [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html)
- [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)
- [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)
- [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx)

## [Benefits and Trade-offs of Async Method Invocation Pattern](https://java-design-patterns.com/patterns/async-method-invocation/#benefits-and-trade-offs-of-async-method-invocation-pattern)

While this pattern offers significant performance benefits, it also introduces complexity in error handling and resource management. Proper implementation is essential to avoid potential pitfalls such as race conditions and deadlocks.

Benefits:

- Improved Responsiveness: The main thread or application flow remains unblocked, improving the user experience in GUI applications and overall responsiveness.
- Better Resource Utilization: By enabling parallel execution, system resources (like CPU and IO) are utilized more efficiently, potentially improving the application's throughput.
- Scalability: Easier to scale applications, as tasks can be distributed across available resources more effectively.

Trade-offs:

- Complexity: Introducing asynchronous operations can complicate the codebase, making it more challenging to understand, debug, and maintain.
- Resource Management: Requires careful management of threads or execution contexts, which can introduce overhead and potential resource exhaustion issues.
- Error Handling: Asynchronous operations can make error handling more complex, as exceptions may occur in different threads or at different times.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/async-method-invocation/#related-java-design-patterns)

The Async Method Invocation pattern often works well with other design patterns like the Command Pattern for encapsulating requests, the Observer Pattern for event handling, and the Promise Pattern for managing asynchronous results.

- [Command](https://java-design-patterns.com/patterns/command/): Asynchronous method invocation can be used to implement the Command pattern, where commands are executed asynchronously.
- [Observer](https://java-design-patterns.com/patterns/observer/): Asynchronous method invocation can be used to notify observers asynchronously when a subject's state changes.
- [Promise](https://java-design-patterns.com/patterns/promise/): The AsyncResult interface can be considered a form of Promise, representing a value that may not be available yet.

## [References and Credits](https://java-design-patterns.com/patterns/async-method-invocation/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3Ti1N4f)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Concurrency in Practice](https://amzn.to/4ab97VU)

---

## [concurrency/backpressure] Backpressure
> 官方文档: https://java-design-patterns.com/patterns/backpressure/

ConcurrencyAsynchronousEvent-drivenReactiveResilienceAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/backpressure/#also-known-as)

- Flow Control
- Rate Limiting Mechanism

## [Intent of the Backpressure Design Pattern](https://java-design-patterns.com/patterns/backpressure/#intent-of-the-backpressure-design-pattern)

Control the rate of data production so downstream consumers are not overwhelmed by excessive load.

## [Detailed Explanation of Backpressure Pattern with Real-World Examples](https://java-design-patterns.com/patterns/backpressure/#detailed-explanation-of-backpressure-pattern-with-real-world-examples)

Real-world example

> Imagine a busy coffee shop where multiple baristas brew drinks (producers), and a single barista is responsible for carefully crafting latte art (consumer). If drinks are brewed faster than the latte-art barista can decorate them, they pile up, risking quality issues or discarded drinks. By introducing a pacing system—only sending new cups once the latte-art barista is ready—everyone stays synchronized, ensuring minimal waste and a consistently enjoyable customer experience.

In plain words

> The Backpressure design pattern is a flow control mechanism that prevents overwhelming a system by regulating data production based on the consumer’s processing capacity.

Wikipedia says

> Back pressure (or backpressure) is the term for a resistance to the desired flow of fluid through pipes. Obstructions or tight bends create backpressure via friction loss and pressure drop. In distributed systems in particular event-driven architecture, back pressure is a technique to regulate flow of data, ensuring that components do not become overwhelmed.

Sequence diagram

![Backpressure sequence diagram](https://java-design-patterns.com/assets/img/backpressure-sequence-diagram.4b053038.png)

## [Programmatic Example of Backpressure Pattern in Java](https://java-design-patterns.com/patterns/backpressure/#programmatic-example-of-backpressure-pattern-in-java)

This example demonstrates how backpressure can be implemented using Project Reactor. We begin by creating a simple publisher that emits a stream of integers, introducing a small delay to mimic a slower production rate:

```java
public class Publisher {
    public static Flux<Integer> publish(int start, int count, int delay) {
        return Flux.range(start, count).delayElements(Duration.ofMillis(delay)).log();
    }
}
```

Next, we define a custom subscriber by extending Reactor’s BaseSubscriber. It simulates slow processing by sleeping for 500ms per item. Initially, the subscriber requests ten items; for every five items processed, it requests five more:

```java
public class Subscriber extends BaseSubscriber<Integer> {

    private static final Logger logger = LoggerFactory.getLogger(Subscriber.class);

    @Override
    protected void hookOnSubscribe(@NonNull Subscription subscription) {
        logger.info("subscribe()");
        request(10); //request 10 items initially
    }

    @Override
    protected void hookOnNext(@NonNull Integer value) {
        processItem();
        logger.info("process({})", value);
        if (value % 5 == 0) {
            // request for the next 5 items after processing first 5
            request(5);
        }
    }

    @Override
    protected void hookOnComplete() {
        //completed processing.
    }

    private void processItem() {
        try {
            Thread.sleep(500); // simulate slow processing
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
```

Finally, in the `main` method, we publish a range of integers and subscribe using the custom subscriber. A short sleep in the main thread allows the emission, backpressure requests, and processing to be fully observed:

```java
public static void main(String[] args) throws InterruptedException {
    Subscriber sub = new Subscriber();
    Publisher.publish(1, 8, 200).subscribe(sub);
    Thread.sleep(5000); //wait for execution

}
```

Below is an example of the program’s output. It shows the subscriber’s log entries, including when it requests more data and when each integer is processed:

```
23:09:55.746 [main] DEBUG reactor.util.Loggers -- Using Slf4j logging framework
23:09:55.762 [main] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onSubscribe(FluxConcatMapNoPrefetch.FluxConcatMapNoPrefetchSubscriber)
23:09:55.762 [main] INFO com.iluwatar.backpressure.Subscriber -- subscribe()
23:09:55.763 [main] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- request(10)
23:09:55.969 [parallel-1] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(1)
23:09:56.475 [parallel-1] INFO com.iluwatar.backpressure.Subscriber -- process(1)
23:09:56.680 [parallel-2] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(2)
23:09:57.185 [parallel-2] INFO com.iluwatar.backpressure.Subscriber -- process(2)
23:09:57.389 [parallel-3] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(3)
23:09:57.894 [parallel-3] INFO com.iluwatar.backpressure.Subscriber -- process(3)
23:09:58.099 [parallel-4] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(4)
23:09:58.599 [parallel-4] INFO com.iluwatar.backpressure.Subscriber -- process(4)
23:09:58.805 [parallel-5] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(5)
23:09:59.311 [parallel-5] INFO com.iluwatar.backpressure.Subscriber -- process(5)
23:09:59.311 [parallel-5] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- request(5)
23:09:59.516 [parallel-6] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(6)
23:10:00.018 [parallel-6] INFO com.iluwatar.backpressure.Subscriber -- process(6)
23:10:00.223 [parallel-7] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(7)
23:10:00.729 [parallel-7] INFO com.iluwatar.backpressure.Subscriber -- process(7)
23:10:00.930 [parallel-8] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onNext(8)
23:10:01.436 [parallel-8] INFO com.iluwatar.backpressure.Subscriber -- process(8)
23:10:01.437 [parallel-8] INFO reactor.Flux.ConcatMapNoPrefetch.1 -- onComplete()
```

## [When to Use the Backpressure Pattern In Java](https://java-design-patterns.com/patterns/backpressure/#when-to-use-the-backpressure-pattern-in-java)

- Use in Java systems where data is produced at high velocity and consumers risk overload.
- Applicable in reactive or event-driven architectures to maintain stability under varying load conditions.

## [Benefits and Trade-offs of Backpressure Pattern](https://java-design-patterns.com/patterns/backpressure/#benefits-and-trade-offs-of-backpressure-pattern)

Benefits:

- Protects consumers from saturation and resource exhaustion.

Trade-offs:

- Introduces possible delays if production must slow down to match consumer capacity.
- Requires careful orchestration in complex systems with multiple concurrent data sources.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/backpressure/#related-java-design-patterns)

- [Observer Pattern](https://java-design-patterns.com/patterns/observer/): Both patterns involve a producer notifying consumers. Observer is synchronous and tightly coupled (observers know the subject).
- [Publish-Subscribe Pattern](https://java-design-patterns.com/patterns/publish-subscribe/): Both patterns deal with asynchronous data flow and can work together to manage message distribution and consumption effectively.

## [References and Credits](https://java-design-patterns.com/patterns/backpressure/#references-and-credits)

- [Backpressure Explained (RedHat Developers Blog)](https://developers.redhat.com/articles/backpressure-explained)
- [Hands-On Reactive Programming in Spring 5](https://amzn.to/3YuYfyO)
- [Reactive Programming with RxJava: Creating Asynchronous, Event-Based Applications](https://amzn.to/42negbf)
- [Reactive Streams in Java](https://amzn.to/3RJjUzA)
- [Reactive Streams Specification](https://www.reactive-streams.org/)

---

## [concurrency/balking] Balking
> 官方文档: https://java-design-patterns.com/patterns/balking/

ConcurrencyConcurrencyDecouplingFault toleranceSynchronizationAbout 4 min

* * *

## [Intent of Balking Design Pattern](https://java-design-patterns.com/patterns/balking/#intent-of-balking-design-pattern)

The Balking Pattern in Java is a concurrency design pattern that prevents an object from executing certain code if it is in an incomplete or inappropriate state. This pattern is crucial for managing state and concurrency in multithreaded Java applications.

## [Detailed Explanation of Balking Pattern with Real-World Examples](https://java-design-patterns.com/patterns/balking/#detailed-explanation-of-balking-pattern-with-real-world-examples)

Real-world example

> A real-world analogy of the Balking design pattern can be seen in a laundry service. Imagine a washing machine at a laundromat that only starts washing clothes if the door is properly closed and locked. If a user tries to start the machine while the door is open, the machine balks and does nothing. This ensures that the washing process only begins when it is safe to do so, preventing water spillage and potential damage to the machine. Similarly, the Balking pattern in software design ensures that operations are only executed when the object is in an appropriate state, preventing erroneous actions and maintaining system stability.

In plain words

> Using the balking pattern, a certain code executes only if the object is in particular state.

Wikipedia says

> The balking pattern is a software design pattern that only executes an action on an object when the object is in a particular state. For example, if an object reads ZIP files and a calling method invokes a get method on the object when the ZIP file is not open, the object would "balk" at the request.

Flowchart

![Balking flowchart](https://java-design-patterns.com/assets/img/balking-flowchart.5470f462.png)

## [Programmatic Example of Balking Pattern in Java](https://java-design-patterns.com/patterns/balking/#programmatic-example-of-balking-pattern-in-java)

This example demonstrates the Balking Pattern in a multithreaded Java application, highlighting state management and concurrency control. The Balking Pattern is exemplified by a washing machine's start button that initiates washing only if the machine is idle. This ensures state management and prevents concurrent issues.

There's a start-button in a washing machine to initiate the laundry washing. When the washing machine is inactive the button works as expected, but if it's already washing the button does nothing.

In this example implementation, `WashingMachine` is an object that has two states in which it can be: ENABLED and WASHING. If the machine is ENABLED, the state changes to WASHING using a thread-safe method. On the other hand, if it already has been washing and any other thread executes `wash`it won't do that and returns without doing anything.

Here are the relevant parts of the `WashingMachine` class.

```java

@Slf4j
public class WashingMachine {

    private final DelayProvider delayProvider;
    private WashingMachineState washingMachineState;

    public WashingMachine(DelayProvider delayProvider) {
        this.delayProvider = delayProvider;
        this.washingMachineState = WashingMachineState.ENABLED;
    }

    public WashingMachineState getWashingMachineState() {
        return washingMachineState;
    }

    public void wash() {
        synchronized (this) {
            var machineState = getWashingMachineState();
            LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState);
            if (this.washingMachineState == WashingMachineState.WASHING) {
                LOGGER.error("Cannot wash if the machine has been already washing!");
                return;
            }
            this.washingMachineState = WashingMachineState.WASHING;
        }
        LOGGER.info("{}: Doing the washing", Thread.currentThread().getName());
        this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing);
    }

    public synchronized void endOfWashing() {
        washingMachineState = WashingMachineState.ENABLED;
        LOGGER.info("{}: Washing completed.", Thread.currentThread().getId());
    }
}
```

Here's the simple `DelayProvider` interface used by the `WashingMachine`.

```java
public interface DelayProvider {
    void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
}
```

Now, we introduce the application using the `WashingMachine`.

```java
public static void main(String... args) {
    final var washingMachine = new WashingMachine();
    var executorService = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 3; i++) {
        executorService.execute(washingMachine::wash);
    }
    executorService.shutdown();
    try {
        if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
            executorService.shutdownNow();
        }
    } catch (InterruptedException ie) {
        LOGGER.error("ERROR: Waiting on executor service shutdown!");
        Thread.currentThread().interrupt();
    }
}
```

Here is the console output of the program.

```
14:02:52.268 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Actual machine state: ENABLED
14:02:52.272 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-2: Doing the washing
14:02:52.272 [pool-1-thread-3] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-3: Actual machine state: WASHING
14:02:52.273 [pool-1-thread-3] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing!
14:02:52.273 [pool-1-thread-1] INFO com.iluwatar.balking.WashingMachine - pool-1-thread-1: Actual machine state: WASHING
14:02:52.273 [pool-1-thread-1] ERROR com.iluwatar.balking.WashingMachine - Cannot wash if the machine has been already washing!
14:02:52.324 [pool-1-thread-2] INFO com.iluwatar.balking.WashingMachine - 14: Washing completed.
```

## [When to Use the Balking Pattern in Java](https://java-design-patterns.com/patterns/balking/#when-to-use-the-balking-pattern-in-java)

Use the Balking pattern when

- You want to invoke an action on an object only when it is in a particular state
- Objects are generally only in a state that is prone to balking temporarily but for an unknown amount of time
- In multithreaded applications where certain actions should only proceed when specific conditions are met, and those conditions are expected to change over time due to external factors or concurrent operations.

## [Real-World Applications of Balking Pattern in Java](https://java-design-patterns.com/patterns/balking/#real-world-applications-of-balking-pattern-in-java)

- Resource pooling, where resources are only allocated if they are in a valid state for allocation.
- Thread management, where threads only proceed with tasks if certain conditions (like task availability or resource locks) are met.

## [Benefits and Trade-offs of Balking Pattern](https://java-design-patterns.com/patterns/balking/#benefits-and-trade-offs-of-balking-pattern)

Benefits:

- Reduces unnecessary lock acquisitions in situations where actions cannot proceed, enhancing performance in concurrent applications.
- Encourages clear separation of state management and behavior, leading to cleaner code.
- Simplifies the handling of operations that should only be performed under certain conditions without cluttering the caller code with state checks.

Trade-offs:

- Can introduce complexity by obscuring the conditions under which actions are taken or ignored, potentially making the system harder to debug and understand.
- May lead to missed opportunities or actions if the state changes are not properly monitored or if the balking condition is too restrictive.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/balking/#related-java-design-patterns)

- [Double-Checked Locking](https://java-design-patterns.com/patterns/double-checked-locking/): Ensures that initialization occurs only when necessary and avoids unnecessary locking, which is related to Balking in terms of conditionally executing logic based on the object's state.
- [Guarded Suspension](https://java-design-patterns.com/patterns/guarded-suspension/): Similar in ensuring actions are only performed when an object is in a certain state, but typically involves waiting until the state is valid.
- [State](https://java-design-patterns.com/patterns/state/): The State pattern can be used in conjunction with Balking to manage the states and transitions of the object.

## [References and Credits](https://java-design-patterns.com/patterns/balking/#references-and-credits)

- [Concurrent Programming in Java : Design Principles and Patterns](https://amzn.to/4dIBqxL)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML](https://amzn.to/4bOtzwF)

---

## [concurrency/double-checked-locking] Double-Checked Locking
> 官方文档: https://java-design-patterns.com/patterns/double-checked-locking/

ConcurrencyLazy initializationOptimizationPerformanceThread managementAbout 2 min

* * *

## [Intent of Double-Checked Locking Design Pattern](https://java-design-patterns.com/patterns/double-checked-locking/#intent-of-double-checked-locking-design-pattern)

Reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion appears to be true does the actual locking logic proceed. Double-checked locking in Java helps in optimizing performance and ensuring thread safety.

## [Detailed Explanation of Double-Checked Locking Pattern with Real-World Examples](https://java-design-patterns.com/patterns/double-checked-locking/#detailed-explanation-of-double-checked-locking-pattern-with-real-world-examples)

Real-world example

> In a company with a high-value equipment room, employees first check a visible sign to see if the room is locked. If the sign shows it's unlocked, they enter directly; if locked, they use a security keycard for access. This two-step verification process efficiently manages security without unnecessary use of the electronic lock system, mirroring the Double-Checked Locking pattern used in software to minimize resource-intensive operations.

In plain words

> The Double-Checked Locking pattern in software minimizes costly locking operations by first checking the lock status in a low-cost manner before proceeding with a more resource-intensive lock, ensuring efficiency and thread safety during object initialization.

Wikipedia says

> In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock. Locking occurs only if the locking criterion check indicates that locking is required.

Flowchart

![Double-Checked Locking flowchart](https://java-design-patterns.com/assets/img/double-checked-locking-flowchart.9b8ef932.png)

## [Programmatic Example of Double-Checked Locking Pattern in Java](https://java-design-patterns.com/patterns/double-checked-locking/#programmatic-example-of-double-checked-locking-pattern-in-java)

The Double-Checked Locking pattern is used in the `HolderThreadSafe` class to ensure that the `Heavy` object is only created once, even when accessed from multiple threads. Here's how it works:

1. Check if the object is initialized (first check): If it is, return it immediately.

```java
if (heavy == null) {
  // ...
}
```

2. Synchronize the block of code where the object is created: This ensures that only one thread can create the object.

```java
synchronized (this) {
  // ...
}
```

3. Check again if the object is initialized. If another thread has already created the object by the time the current thread enters the synchronized block, return the created object.

```java
if (heavy == null) {
  heavy = new Heavy();
}
```

4. Return the created object.

```java
return heavy;
```

Here's the complete code for the `HolderThreadSafe` class:

```java
public class HolderThreadSafe {

  private Heavy heavy;

  public HolderThreadSafe() {
    LOGGER.info("Holder created");
  }

  public synchronized Heavy getHeavy() {
    if (heavy == null) {
      synchronized (this) {
        if (heavy == null) {
          heavy = new Heavy();
        }
      }
    }
    return heavy;
  }
}
```

In this code, the `Heavy` object is only created when the `getHeavy` method is called for the first time. This is known as lazy initialization. The double-checked locking pattern is used to ensure that the `Heavy` object is only created once, even when the `getHeavy` method is called from multiple threads simultaneously.

## [When to Use the Double-Checked Locking Pattern in Java](https://java-design-patterns.com/patterns/double-checked-locking/#when-to-use-the-double-checked-locking-pattern-in-java)

Use the Double-Checked Locking pattern in Java when all the following conditions are met:

- There is a singleton resource that is expensive to create.
- There is a need to reduce the overhead of acquiring a lock every time the resource is accessed.

## [Real-World Applications of Double-Checked Locking Pattern in Java](https://java-design-patterns.com/patterns/double-checked-locking/#real-world-applications-of-double-checked-locking-pattern-in-java)

- Singleton pattern implementation in multithreading environments.
- Lazy initialization of resource-intensive objects in Java applications.

## [Benefits and Trade-offs of Double-Checked Locking Pattern](https://java-design-patterns.com/patterns/double-checked-locking/#benefits-and-trade-offs-of-double-checked-locking-pattern)

Benefits:

- Performance gains from avoiding unnecessary locking after the object is initialized.
- Thread safety is maintained for critical initialization sections.

Trade-offs:

- Complex implementation can lead to mistakes, such as incorrect publishing of objects due to memory visibility issues.
- In Java, it can be redundant or broken in some versions unless volatile variables are used with care.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/double-checked-locking/#related-java-design-patterns)

- [Singleton](https://java-design-patterns.com/patterns/singleton/): Double-Checked Locking is often used in implementing thread-safe Singletons.
- [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Shares the concept of delaying object creation until necessary.

## [References and Credits](https://java-design-patterns.com/patterns/double-checked-locking/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/4aIAPKa)
- [Effective Java](https://amzn.to/3xx7KDh)

---

## [concurrency/event-based-asynchronous] Event-Based Asynchronous
> 官方文档: https://java-design-patterns.com/patterns/event-based-asynchronous/

ConcurrencyAsynchronousDecouplingEvent-drivenFault toleranceMessagingReactiveScalabilityAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/event-based-asynchronous/#also-known-as)

- Asynchronous Event Handling

## [Intent of Event-Based Asynchronous Design Pattern](https://java-design-patterns.com/patterns/event-based-asynchronous/#intent-of-event-based-asynchronous-design-pattern)

The Event-Based Asynchronous pattern allows a system to handle tasks that might take some time to complete without blocking the execution of the program. It enables better resource utilization by freeing up a thread that would otherwise be blocked waiting for the task to complete.

## [Detailed Explanation of Event-Based Asynchronous Pattern with Real-World Examples](https://java-design-patterns.com/patterns/event-based-asynchronous/#detailed-explanation-of-event-based-asynchronous-pattern-with-real-world-examples)

Real-world example

> A real-world analogy of the Event-Based Asynchronous design pattern is how a restaurant operates. When a customer places an order, the waiter records the order and passes it to the kitchen. Instead of waiting at the kitchen for the food to be prepared, the waiter continues to serve other tables. Once the kitchen completes the order, they signal (event) the waiter, who then delivers the food to the customer. This allows the waiter to handle multiple tasks efficiently without idle waiting, similar to how asynchronous programming handles tasks in parallel, enhancing overall efficiency and responsiveness.

In Plain Words

> The Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations.

Sequence diagram

![Event-Based Asynchronous sequence diagram](https://java-design-patterns.com/assets/img/event-based-asynchronous-sequence-diagram.0a523ec8.png)

## [Programmatic Example of Event-Based Asynchronous Pattern in Java](https://java-design-patterns.com/patterns/event-based-asynchronous/#programmatic-example-of-event-based-asynchronous-pattern-in-java)

Event-Based Asynchronous design pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations.

In the provided code, we have several key classes implementing this pattern:

- `App`: The main class that runs the application. It interacts with the `EventManager` to create, start, stop, and check the status of events.
- `EventManager`: Manages the lifecycle of events, including creating, starting, stopping, and checking the status of events. It maintains a map of event IDs to `Event` objects.
- `Event`: An abstract class that represents an event. It has two concrete subclasses: `AsyncEvent` and `SyncEvent`.
- `AsyncEvent` and `SyncEvent`: Represent asynchronous and synchronous events respectively.
- Custom exceptions: Thrown by the `EventManager` when certain conditions are not met.

Here's a simplified code example of how these classes interact:

```java
// Create an EventManager
EventManager eventManager = new EventManager();

// Create an asynchronous event that runs for 60 seconds
int asyncEventId = eventManager.createAsync(Duration.ofSeconds(60));

// Start the asynchronous event
eventManager.start(asyncEventId);

// Check the status of the asynchronous event
eventManager.status(asyncEventId);

// Stop the asynchronous event
eventManager.cancel(asyncEventId);
```

In this example, the `App` class creates an `EventManager`, then uses it to create, start, check the status of, and stop an asynchronous event. The `EventManager` creates an `AsyncEvent` object, starts it in a separate thread, checks its status, and stops it when requested.

The `EventManager` class is the core of the Event-Based Asynchronous pattern implementation. It manages the lifecycle of events, including creating, starting, stopping, and checking the status of events. It maintains a map of event IDs to `Event` objects. Here's a snippet of how it creates an asynchronous event:

```java
public int createAsync(Duration runtime) throws MaxNumOfEventsAllowedException, LongRunningEventException {
  int id = counter.incrementAndGet();
  events.put(id, new AsyncEvent(id, runtime));
  return id;
}
```

The `Event` class is an abstract class that represents an event. It has two concrete subclasses: `AsyncEvent` and `SyncEvent`. An `Event` has an ID, a runtime (how long it should run), and a status (whether it's running, completed, or ready to start). It also has methods to start and stop the event. Here's a snippet of how an `AsyncEvent` starts:

```java
@Override
public void start() {
  Thread thread = new Thread(() -> {
    try {
      handleRunStart();
      Thread.sleep(getRuntime().toMillis());
      handleRunComplete();
    } catch (InterruptedException e) {
      handleRunFailure(e.getMessage());
    }
  });
  thread.start();
}
```

In this snippet, when an `AsyncEvent` is started, it runs in a separate thread without blocking the main thread.

A synchronous event is created and managed similarly to an asynchronous event. Here's a snippet of how it creates and manages a synchronous event:

```java
// Create an EventManager
EventManager eventManager = new EventManager();

// Create a synchronous event that runs for 60 seconds
int syncEventId = eventManager.create(Duration.ofSeconds(60));

// Start the synchronous event
eventManager.start(syncEventId);

// Check the status of the synchronous event
eventManager.status(syncEventId);

// Stop the synchronous event
eventManager.cancel(syncEventId);
```

In the `EventManager` class, a synchronous event is created using the `create` method:

```java
public int create(Duration runtime) throws MaxNumOfEventsAllowedException, LongRunningEventException {
  int id = counter.incrementAndGet();
  events.put(id, new SyncEvent(id, runtime));
  return id;
}
```

The `SyncEvent` class is a subclass of `Event` that represents a synchronous event. When a `SyncEvent` is started, it runs on the main thread and blocks it until the event is completed. Here's a snippet of how a `SyncEvent` starts:

```java
@Override
public void start() {
  try {
    handleRunStart();
    Thread.sleep(getRuntime().toMillis());
    handleRunComplete();
  } catch (InterruptedException e) {
    handleRunFailure(e.getMessage());
  }
}
```

In this snippet, when a `SyncEvent` is started, it runs on the main thread, blocking it until the event is completed. This is in contrast to an `AsyncEvent`, which runs in a separate thread without blocking the main thread.

These are the key parts of the Event-Based Asynchronous design pattern as implemented in this code. The pattern allows tasks to be executed in the background, notifying the main program via events when completed, thereby enhancing system efficiency and responsiveness without blocking ongoing operations.

## [When to Use the Event-Based Asynchronous Pattern in Java](https://java-design-patterns.com/patterns/event-based-asynchronous/#when-to-use-the-event-based-asynchronous-pattern-in-java)

- When multiple tasks can be processed in parallel and independently.
- Systems that require responsiveness and cannot afford to have threads blocked waiting for an operation to complete.
- In GUI applications where user interface responsiveness is critical.
- Distributed systems where long network operations are involved.

## [Real-World Applications of Event-Based Asynchronous Pattern in Java](https://java-design-patterns.com/patterns/event-based-asynchronous/#real-world-applications-of-event-based-asynchronous-pattern-in-java)

- GUI libraries in Java (e.g., JavaFX, Swing with SwingWorker).
- Java Message Service (JMS) for handling asynchronous messaging.
- Java’s CompletableFuture and various Event-Driven Frameworks.

## [Benefits and Trade-offs of Event-Based Asynchronous Pattern](https://java-design-patterns.com/patterns/event-based-asynchronous/#benefits-and-trade-offs-of-event-based-asynchronous-pattern)

Benefits:

- Improves application scalability and responsiveness.
- Reduces the resources wasted on threads that would simply wait for I/O operations.
- Enhances fault tolerance through isolation of process execution.

Trade-offs:

- Increases complexity of error handling as errors may occur in different threads or at different times.
- Can lead to harder-to-follow code and debugging challenges due to the non-linear nature of asynchronous code execution.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/event-based-asynchronous/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Often used in conjunction where the observer reacts to events as they occur.
- Publish/Subscribe: Related in terms of event handling mechanisms, particularly for messaging and event distribution across components.
- [Command](https://java-design-patterns.com/patterns/command/): Useful for encapsulating all information needed to perform an action or trigger an event.

## [References and Credits](https://java-design-patterns.com/patterns/event-based-asynchronous/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/4cYY4kU)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3Uh7rW1)
- [Pro JavaFX 8: A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://amzn.to/3vHUqLL)
- [Event-based Asynchronous Pattern Overview (Microsoft)](https://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396)

---

## [concurrency/event-queue] Event Queue
> 官方文档: https://java-design-patterns.com/patterns/event-queue/

ConcurrencyAsynchronousDecouplingMessagingEvent-drivenScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/event-queue/#also-known-as)

- Event Stream
- Message Queue

## [Intent of Event Queue Design Pattern](https://java-design-patterns.com/patterns/event-queue/#intent-of-event-queue-design-pattern)

The Event Queue pattern is designed to manage tasks in an asynchronous manner, allowing applications to handle operations without blocking user interactions or other processes. This improves scalability and system performance.

## [Detailed Explanation of Event Queue Pattern with Real-World Examples](https://java-design-patterns.com/patterns/event-queue/#detailed-explanation-of-event-queue-pattern-with-real-world-examples)

Real-world example

> The modern emailing system is an example of the fundamental process behind the event-queue design pattern. When an email is sent, the sender continues their daily tasks without the necessity of an immediate response from the receiver. Additionally, the receiver has the freedom to access and process the email at their leisure. Therefore, this process decouples the sender and receiver so that they are not required to engage with the queue at the same time.

In plain words

> The buffer between sender and receiver improves maintainability and scalability of a system. Event queues are typically used to organize and carry out interprocess communication (IPC).

Wikipedia says

> Message queues (also known as event queues) implement an asynchronous communication pattern between two or more processes/threads whereby the sending and receiving party do not need to interact with the queue at the same time.

Sequence diagram

![Event Queue sequence diagram](https://java-design-patterns.com/assets/img/event-queue-sequence-diagram.b10b2e1d.png)

## [Programmatic Example of Event Queue Pattern in Java](https://java-design-patterns.com/patterns/event-queue/#programmatic-example-of-event-queue-pattern-in-java)

This example demonstrates an application using an event queue system to handle audio playback asynchronously.

The `App` class sets up an instance of `Audio`, plays two sounds, and waits for user input to exit. It demonstrates how an event queue could be used to manage asynchronous operations in a software application.

```java
public class App {

    public static void main(String[] args) throws UnsupportedAudioFileException, IOException,
            InterruptedException {
        var audio = Audio.getInstance();
        audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
        audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);

        LOGGER.info("Press Enter key to stop the program...");
        try (var br = new BufferedReader(new InputStreamReader(System.in))) {
            br.read();
        }
        audio.stopService();
    }
}
```

The `Audio` class holds the singleton pattern implementation, manages a queue of audio play requests, and controls thread operations for asynchronous processing.

```java
public class Audio {
    private static final Audio INSTANCE = new Audio();

    private static final int MAX_PENDING = 16;

    private int headIndex;

    private int tailIndex;

    private volatile Thread updateThread = null;

    private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING];

    Audio() {}

    public static Audio getInstance() {
        return INSTANCE;
    }
}
```

These methods manage the lifecycle of the thread used to process the audio events. The `init` and `startThread` methods ensure the thread is properly initialized and running.

```java
public synchronized void stopService() throws InterruptedException {
    if(updateThread != null) {
        updateThread.interrupt();
        updateThread.join();
        updateThread = null;
    }
}

public synchronized boolean isServiceRunning() {
    return updateThread != null && updateThread.isAlive();
}

public void init() {
    if(updateThread == null) {
        updateThread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                update();
            }
        });
        startThread();
    }
}

private synchronized void startThread() {
    if (!updateThread.isAlive()) {
        updateThread.start();
        headIndex = 0;
        tailIndex = 0;
    }
}
```

The `playSound` method checks if the audio is already in the queue and either updates the volume or enqueues a new request, demonstrating the management of asynchronous tasks within the event queue.

```java
public void playSound(AudioInputStream stream, float volume) {
    init();
    for(var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) {
        var playMessage = getPendingAudio()[i];
        if(playMessage.getStream() == stream) {
            playMessage.setVolume(Math.max(volume, playMessage.getVolume()));
            return;
        }
    }
    getPendingAudio()[tailIndex] = new PlayMessage(stream, volume);
    tailIndex = (tailIndex + 1) % MAX_PENDING;
}
```

## [When to Use the Event Queue Pattern in Java](https://java-design-patterns.com/patterns/event-queue/#when-to-use-the-event-queue-pattern-in-java)

This pattern is applicable in scenarios where tasks can be handled asynchronously outside the main application flow, such as in GUI applications, server-side event handling, or in systems that require task scheduling without immediate execution. In particular:

- The sender does not require a response from the receiver.
- You wish to decouple the sender & the receiver.
- You want to process events asynchronously.
- You have a limited accessibility resource and the asynchronous process is acceptable to reach that.

## [Real-World Applications of Event Queue Pattern in Java](https://java-design-patterns.com/patterns/event-queue/#real-world-applications-of-event-queue-pattern-in-java)

- Event-driven architectures
- GUI frameworks in Java (such as Swing and JavaFX)
- Server applications handling requests asynchronously

## [Benefits and Trade-offs of Event Queue Pattern](https://java-design-patterns.com/patterns/event-queue/#benefits-and-trade-offs-of-event-queue-pattern)

Benefits:

- Reduces system coupling.
- Enhances responsiveness of applications.
- Improves scalability by allowing event handling to be distributed across multiple threads or processors.

Trade-offs:

- Complexity in managing the event queue.
- Potential for difficult-to-track bugs due to asynchronous behavior.
- Overhead of maintaining event queue integrity and performance.
- As the event queue model decouples the sender-receiver relationship - this means that the event-queue design pattern is unsuitable for scenarios in which the sender requires a response. For example, this is a prominent feature within online multiplayer games, therefore, this approach requires thorough consideration.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/event-queue/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/) (for encapsulating request processing in a command object)
- [Observer](https://java-design-patterns.com/patterns/observer/) (for subscribing and notifying changes to multiple observers)
- [Reactor](https://java-design-patterns.com/patterns/reactor/) (handles requests in a non-blocking event-driven manner similar to Event Queue)

## [References and Credits](https://java-design-patterns.com/patterns/event-queue/#references-and-credits)

- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3xzSlC2)
- [Game Programming Patterns](https://amzn.to/3K96fOn)
- [Java Concurrency in Practice](https://amzn.to/3Ji16mX)
- [Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3U2hlcy)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3xtVtPJ)
- [Event Queue (Game Programming Patterns)](http://gameprogrammingpatterns.com/event-queue.html)

---

## [concurrency/fanout-fanin] Fan-Out Fan-In
> 官方文档: https://java-design-patterns.com/patterns/fanout-fanin/

ConcurrencyAsynchronousData processingDecouplingScalabilityAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/fanout-fanin/#also-known-as)

- Scatter-Gather

## [Intent of Fan-Out/Fan-In Design Pattern](https://java-design-patterns.com/patterns/fanout-fanin/#intent-of-fan-out-fan-in-design-pattern)

The Fan-Out/Fan-In design pattern in Java aims to improve concurrency and optimize processing time by dividing a task into multiple sub-tasks that can be processed in parallel (fan-out) and then combining the results of these sub-tasks into a single outcome (fan-in).

## [Detailed Explanation of Fan-Out/Fan-In Pattern with Real-World Examples](https://java-design-patterns.com/patterns/fanout-fanin/#detailed-explanation-of-fan-out-fan-in-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Fan-Out/Fan-In pattern in Java is a food delivery service like UberEats or DoorDash. When a customer places an order, the service (fan-out) sends out individual tasks to different restaurants to prepare the various items. Each restaurant works independently to prepare its part of the order. Once all restaurants have completed their tasks, the delivery service (fan-in) aggregates the items from different restaurants into a single order, ensuring that everything is delivered together to the customer. This parallel processing improves efficiency and ensures timely delivery.

In plain words

> The Fan-Out/Fan-In pattern distributes tasks across multiple concurrent processes or threads and then aggregates the results.

Wikipedia says

> In message-oriented middleware, the fan-out pattern models information exchange by delivering messages to one or multiple destinations in parallel, without waiting for responses. This allows a process to distribute tasks to various receivers simultaneously.
>
> The fan-in concept, on the other hand, typically refers to the aggregation of multiple inputs. In digital electronics, it describes the number of inputs a logic gate can handle. Combining these concepts, the Fan-Out/Fan-In pattern in software engineering involves distributing tasks (fan-out) and then aggregating the results (fan-in).

Sequence diagram

![Fan-Out/Fan-In flowchart](https://java-design-patterns.com/assets/img/fan-out-fan-in-flowchart.a1ca2ddd.png)

## [Programmatic Example of Fan-Out/Fan-In Pattern in Java](https://java-design-patterns.com/patterns/fanout-fanin/#programmatic-example-of-fan-out-fan-in-pattern-in-java)

The provided implementation involves a list of numbers with the objective to square them and aggregate the results. The `FanOutFanIn` class receives the list of numbers as `SquareNumberRequest` objects and a `Consumer` instance that collects the squared results as the requests complete. Each `SquareNumberRequest` squares its number with a random delay, simulating a long-running process that finishes at unpredictable times. The `Consumer` instance gathers the results from the various `SquareNumberRequest` objects as they become available at different times.

Here's the `FanOutFanIn` class in Java that demonstrates the Fan-Out/Fan-In pattern by asynchronously distributing the requests.

```java
public class FanOutFanIn {
    public static Long fanOutFanIn(final List<SquareNumberRequest> requests, final Consumer consumer) {

        ExecutorService service = Executors.newFixedThreadPool(requests.size());

        // fanning out
        List<CompletableFuture<Void>> futures = requests
                .stream()
                .map(request -> CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service))
                .collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        return consumer.getSumOfSquaredNumbers().get();
    }
}
```

`Consumer` is used a callback class that will be called when a request is completed. This will aggregate the result from all requests.

```java
public class Consumer {

    private final AtomicLong sumOfSquaredNumbers;

    Consumer(Long init) {
        sumOfSquaredNumbers = new AtomicLong(init);
    }

    public Long add(final Long num) {
        return sumOfSquaredNumbers.addAndGet(num);
    }
}
```

Request is represented as a `SquareNumberRequest` that squares the number with random delay and calls the `Consumer` once it is squared.

```java
public class SquareNumberRequest {

    private final Long number;

    public void delayedSquaring(final Consumer consumer) {

        var minTimeOut = 5000L;

        SecureRandom secureRandom = new SecureRandom();
        var randomTimeOut = secureRandom.nextInt(2000);

        try {
            // this will make the thread sleep from 5-7s.
            Thread.sleep(minTimeOut + randomTimeOut);
        } catch (InterruptedException e) {
            LOGGER.error("Exception while sleep ", e);
            Thread.currentThread().interrupt();
        } finally {
            consumer.add(number * number);
        }
    }
}
```

Here is the App class with main method to drive the example.

```java
public static void main(String[] args) {
    final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L);

    LOGGER.info("Numbers to be squared and get sum --> {}", numbers);

    final List<SquareNumberRequest> requests =
        numbers.stream().map(SquareNumberRequest::new).toList();

    var consumer = new Consumer(0L);

    // Pass the request and the consumer to fanOutFanIn or sometimes referred as Orchestrator
    // function
    final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer);

    LOGGER.info("Sum of all squared numbers --> {}", sumOfSquaredNumbers);
}
```

Running the example produces the following console output.

```
06:52:04.622 [main] INFO com.iluwatar.fanout.fanin.App -- Numbers to be squared and get sum --> [1, 3, 4, 7, 8]
06:52:11.465 [main] INFO com.iluwatar.fanout.fanin.App -- Sum of all squared numbers --> 139
```

## [When to Use the Fan-Out/Fan-In Pattern in Java](https://java-design-patterns.com/patterns/fanout-fanin/#when-to-use-the-fan-out-fan-in-pattern-in-java)

The Fan-Out/Fan-In design pattern in Java is appropriate in scenarios where tasks can be broken down and executed in parallel, especially suitable for data processing, batch processing, and situations requiring aggregation of results from various sources.

## [Fan-Out/Fan-In Pattern Java Tutorials](https://java-design-patterns.com/patterns/fanout-fanin/#fan-out-fan-in-pattern-java-tutorials)

- [Fan-out/fan-in scenario in Durable Functions - Cloud backup example (Microsoft)](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-cloud-backup)
- [Understanding Azure Durable Functions - Part 8: The Fan Out/Fan In Pattern (Don't Code Tired)](http://dontcodetired.com/blog/post/Understanding-Azure-Durable-Functions-Part-8-The-Fan-OutFan-In-Pattern)
- [Understanding the Fan-Out/Fan-In API Integration Pattern (DZone)](https://dzone.com/articles/understanding-the-fan-out-fan-in-api-integration-p)

## [Real-World Applications of Fan-Out/Fan-In Pattern in Java](https://java-design-patterns.com/patterns/fanout-fanin/#real-world-applications-of-fan-out-fan-in-pattern-in-java)

- The Fan-Out/Fan-In pattern in Java is widely used in large-scale data processing applications.
- Services requiring aggregation from multiple sources before delivering a response, such as in distributed caching or load balancing systems.

## [Benefits and Trade-offs of Fan-Out/Fan-In Pattern](https://java-design-patterns.com/patterns/fanout-fanin/#benefits-and-trade-offs-of-fan-out-fan-in-pattern)

Benefits:

- Enhances performance by parallel processing.
- Increases responsiveness of systems.
- Efficient utilization of multi-core processor architectures.

Trade-offs:

- Increased complexity in error handling.
- Potential for increased overhead due to task synchronization and result aggregation.
- Dependency on the underlying infrastructure's ability to support concurrent execution.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/fanout-fanin/#related-java-design-patterns)

- MapReduce: Similar to Fan-Out/Fan-In, MapReduce also involves distributing tasks across a number of workers (map) and aggregating the results (reduce), which is particularly useful for processing large data sets.
- [Command](https://java-design-patterns.com/patterns/command/): Command Pattern facilitates the decoupling of the sender and the receiver, akin to how Fan-Out/Fan-In decouples task submission from task processing.
- [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Works synergistically with Fan-Out/Fan-In by organizing task execution where producers distribute tasks that are processed by multiple consumers, and results are then combined, enhancing throughput and efficiency in data processing.

## [References and Credits](https://java-design-patterns.com/patterns/fanout-fanin/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/3vXytsb)
- [Patterns of Enterprise Application Architecture](https://amzn.to/49QQcPD)

---

## [concurrency/guarded-suspension] Guarded Suspension
> 官方文档: https://java-design-patterns.com/patterns/guarded-suspension/

ConcurrencyAsynchronousDecouplingResource managementSynchronizationThread managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/guarded-suspension/#also-known-as)

- Conditional Block
- Suspended Execution

## [Intent of Guarded Suspension Design Pattern](https://java-design-patterns.com/patterns/guarded-suspension/#intent-of-guarded-suspension-design-pattern)

The Guarded Suspension pattern is crucial in Java design patterns for managing operations that require both a lock and a condition to proceed. It optimizes concurrency control by allowing a thread to wait for the right condition efficiently.

## [Detailed Explanation of Guarded Suspension Pattern with Real-World Examples](https://java-design-patterns.com/patterns/guarded-suspension/#detailed-explanation-of-guarded-suspension-pattern-with-real-world-examples)

Real-world example

> A practical example of the Guarded Suspension pattern can be seen in a ride-sharing service. In this system, passengers wait for a car to become available, ensuring efficient resource use without continuous checking. When a passenger requests a ride, the request is suspended until a driver becomes available. The system monitors the availability of drivers, and once a driver is ready to take a new passenger, the system notifies the waiting passenger and resumes the ride request process. This ensures that passengers are not continuously checking for available drivers and that drivers are efficiently matched with passengers based on their availability.

In plain words

> Guarded Suspension pattern is used when one thread waits for the result of another thread's execution.

Wikipedia says

> In concurrent programming, Guarded Suspension manages operations requiring a lock and a precondition, delaying execution until the precondition is met.

Sequence diagram

![Guarded Suspension sequence diagram](https://java-design-patterns.com/assets/img/guarded-suspension-sequence-diagram.e3dd6ffb.png)

## [Programmatic Example of Guarded Suspension Pattern in Java](https://java-design-patterns.com/patterns/guarded-suspension/#programmatic-example-of-guarded-suspension-pattern-in-java)

The `GuardedQueue` class in Java showcases concurrent programming using the Guarded Suspension pattern. It includes synchronized methods that manage thread management and synchronization, demonstrating how threads wait for the right conditions to execute.

The `GuardedQueue` class demonstrates the Guarded Suspension pattern by encapsulating a queue and providing two synchronized methods, `get` and `put`. The `get` method waits if the queue is empty, while the `put` method adds an item to the queue and notifies any waiting threads.

```java
@Slf4j
public class GuardedQueue {
    private final Queue<Integer> sourceList = new LinkedList<>();

    // Synchronized get method waits until the queue is not empty
    public synchronized Integer get() {
        while (sourceList.isEmpty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                LOGGER.error("Error occurred: ", e);
            }
        }
        return sourceList.poll();
    }

    // Synchronized put method adds an item to the queue and notifies waiting threads
    public synchronized void put(Integer e) {
        sourceList.add(e);
        notify();
    }
}
```

- `get`: This method waits while the `sourceList` is empty. When an item is added and `notify` is called, the waiting thread is awakened to continue execution and retrieve the item.
- `put`: This method adds an item to the queue and calls `notify` to wake up any waiting thread that is suspended in the `get` method.

Here is the `App` class driving the example:

```java
public class App {
    public static void main(String[] args) {
        GuardedQueue guardedQueue = new GuardedQueue();
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // Thread to get from the guardedQueue
        executorService.execute(() -> {
            Integer item = guardedQueue.get();
            LOGGER.info("Retrieved: " + item);
        });

        // Simulating some delay before putting an item
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            LOGGER.error("Error occurred: ", e);
        }

        // Thread to put an item into the guardedQueue
        executorService.execute(() -> {
            guardedQueue.put(20);
            LOGGER.info("Item added to queue");
        });

        executorService.shutdown();
        try {
            executorService.awaitTermination(30, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOGGER.error("Error occurred: ", e);
        }
    }
}
```

- `ExecutorService` is used to manage a pool of threads.
- The first thread attempts to retrieve an item from the `GuardedQueue` and waits since the queue is initially empty.
- After a 2-second delay, the second thread adds an item to the queue, waking up the first thread.
- The first thread then retrieves the item and logs it.

Execution yields:

```
19:22:58.984 [pool-1-thread-1] INFO com.iluwatar.guarded.suspension.GuardedQueue -- waiting
19:23:00.993 [pool-1-thread-2] INFO com.iluwatar.guarded.suspension.GuardedQueue -- putting
19:23:00.994 [pool-1-thread-2] INFO com.iluwatar.guarded.suspension.GuardedQueue -- notifying
19:23:00.994 [pool-1-thread-1] INFO com.iluwatar.guarded.suspension.GuardedQueue -- getting
19:23:00.994 [pool-1-thread-1] INFO com.iluwatar.guarded.suspension.GuardedQueue -- Retrieved: 20
```

- The log output shows the sequence of events: the first thread waits, the second thread puts an item, and the first thread then retrieves the item. This demonstrates the Guarded Suspension pattern in action.

## [When to Use the Guarded Suspension Pattern in Java](https://java-design-patterns.com/patterns/guarded-suspension/#when-to-use-the-guarded-suspension-pattern-in-java)

This pattern is ideal for scenarios requiring a thread to wait for specific conditions, promoting efficient concurrency control and reducing busy waiting overhead.

## [Real-World Applications of Guarded Suspension Pattern in Java](https://java-design-patterns.com/patterns/guarded-suspension/#real-world-applications-of-guarded-suspension-pattern-in-java)

- Network servers waiting for client requests.
- Producer-consumer scenarios where the consumer must wait for the producer to provide data.
- Event-driven applications where actions are triggered only after specific events have occurred.

## [Benefits and Trade-offs of Guarded Suspension Pattern](https://java-design-patterns.com/patterns/guarded-suspension/#benefits-and-trade-offs-of-guarded-suspension-pattern)

Benefits:

- Reduces CPU consumption by preventing busy waiting.
- Increases system responsiveness by synchronizing actions to the availability of necessary conditions or resources.

Trade-offs:

- Complexity in implementation, especially when multiple conditions need to be managed.
- Potential for deadlocks if not carefully managed.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/guarded-suspension/#related-java-design-patterns)

- [Monitor](https://java-design-patterns.com/patterns/monitor/): Both patterns manage the synchronization of threads based on conditions. Guarded Suspension specifically deals with suspending threads until conditions are met, while Monitor Object encapsulates condition and mutual exclusion handling.
- [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Often implemented using Guarded Suspension to handle waiting consumers and producers efficiently.
- [Balking](https://java-design-patterns.com/patterns/balking/): Similar to Guarded Suspension, Balking is used when a thread checks a condition and only proceeds if the condition is favorable; if not, it immediately returns or bails out. This pattern complements Guarded Suspension by managing actions based on immediate condition checks without waiting.

## [References and Credits](https://java-design-patterns.com/patterns/guarded-suspension/#references-and-credits)

- [Concurrent Programming in Java : Design Principles and Patterns](https://amzn.to/4dIBqxL)
- [Java Concurrency in Practice](https://amzn.to/3JxnXek)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/49Ke1c9)

giscus

#### 0 reactions

#### 0 comments

WritePreview

[Styling with Markdown is supported](https://guides.github.com/features/mastering-markdown/ "Styling with Markdown is supported")

[Sign in with GitHub](https://giscus.app/api/oauth/authorize?redirect_uri=https%3A%2F%2Fjava-design-patterns.com%2Fpatterns%2Fguarded-suspension%2F)

---

## [concurrency/half-sync-half-async] Half-Sync/Half-Async
> 官方文档: https://java-design-patterns.com/patterns/half-sync-half-async/

ConcurrencyAsynchronousDecouplingSynchronizationThread managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/half-sync-half-async/#also-known-as)

- Async-Sync Bridge
- Half-Synchronous/Half-Asynchronous

## [Intent of Half-Sync/Half-Async Design Pattern](https://java-design-patterns.com/patterns/half-sync-half-async/#intent-of-half-sync-half-async-design-pattern)

The Half-Sync/Half-Async pattern in Java aims to decouple asynchronous and synchronous processing in concurrent systems, enhancing efficiency and performance. This pattern is particularly useful for managing complex concurrent operations in software systems.

## [Detailed Explanation of Half-Sync/Half-Async Pattern with Real-World Examples](https://java-design-patterns.com/patterns/half-sync-half-async/#detailed-explanation-of-half-sync-half-async-pattern-with-real-world-examples)

Real-world example

> Imagine a busy restaurant kitchen where order taking is asynchronous, allowing waiters to keep working while chefs cook each dish synchronously. Similarly, the Half-Sync/Half-Async pattern handles multiple asynchronous tasks and synchronous processing in Java applications efficiently. Meanwhile, the cooking (synchronous part) follows a specific sequence and requires waiting for each dish to be prepared before starting the next. This setup enables the restaurant to handle multiple customer orders efficiently, while ensuring each dish is cooked with the required attention and timing, much like the Half-Sync/Half-Async pattern manages asynchronous tasks and synchronous processing in software systems.

In plain words

> The Half-Sync/Half-Async pattern separates operations into asynchronous tasks that handle events without waiting, and synchronous tasks that process these events in an orderly and blocking manner.

Wikipedia says

> The Half-Sync/Half-Async design pattern is used to solve situations where one part of the application runs synchronously while another runs asynchronously, and the two modules need to communicate with each other.

Sequence diagram

![Half-Sync/Half-Async sequence diagram](https://java-design-patterns.com/assets/img/half-sync-half-async-sequence-diagram.d4d88890.png)

## [Programmatic Example of Half-Sync/Half-Async Pattern in Java](https://java-design-patterns.com/patterns/half-sync-half-async/#programmatic-example-of-half-sync-half-async-pattern-in-java)

The Half-Sync/Half-Async design pattern is a concurrency pattern that separates synchronous and asynchronous processing in a system, simplifying the programming model without affecting performance. It's particularly useful in scenarios where you have a mix of short, mid, and long duration tasks.

In the provided Java implementation, we can see an example of the Half-Sync/Half-Async pattern in the `App`, `AsynchronousService`, and `ArithmeticSumTask` classes.

The `App` class is the entry point of the application. It creates an instance of `AsynchronousService` and uses it to handle various tasks asynchronously.

```java
public class App {

  public static void main(String[] args) {
    var service = new AsynchronousService(new LinkedBlockingQueue<>());
    service.execute(new ArithmeticSumTask(1000));
    service.execute(new ArithmeticSumTask(500));
    service.execute(new ArithmeticSumTask(2000));
    service.execute(new ArithmeticSumTask(1));
    service.close();
  }
}
```

The `AsynchronousService` class is the asynchronous part of the system. It manages a queue of tasks and processes them in a separate thread.

```java
public class AsynchronousService {
  // Implementation details...
}
```

The `ArithmeticSumTask` class represents a task that can be processed asynchronously. It implements the `AsyncTask` interface, which defines methods for pre-processing, post-processing, and error handling.

```java
static class ArithmeticSumTask implements AsyncTask<Long> {
  private final long numberOfElements;

  public ArithmeticSumTask(long numberOfElements) {
    this.numberOfElements = numberOfElements;
  }

  @Override
  public Long call() throws Exception {
    return ap(numberOfElements);
  }

  @Override
  public void onPreCall() {
    if (numberOfElements < 0) {
      throw new IllegalArgumentException("n is less than 0");
    }
  }

  @Override
  public void onPostCall(Long result) {
    LOGGER.info(result.toString());
  }

  @Override
  public void onError(Throwable throwable) {
    throw new IllegalStateException("Should not occur");
  }
}
```

This is the `main` function in the `App` class.

```java
public static void main(String[] args) {

    var service = new AsynchronousService(new LinkedBlockingQueue<>());

    service.execute(new ArithmeticSumTask(1000));

    service.execute(new ArithmeticSumTask(500));
    service.execute(new ArithmeticSumTask(2000));
    service.execute(new ArithmeticSumTask(1));

    service.close();
}
```

In this example, the `App` class enqueues tasks to the `AsynchronousService`, which processes them asynchronously. The `ArithmeticSumTask` class defines the task to be processed, including pre-processing, the actual processing, and post-processing steps.

Running the code produces:

```
10:56:33.922 [pool-1-thread-4] INFO com.iluwatar.halfsynchalfasync.App -- 1
10:56:34.425 [pool-1-thread-2] INFO com.iluwatar.halfsynchalfasync.App -- 125250
10:56:34.925 [pool-1-thread-1] INFO com.iluwatar.halfsynchalfasync.App -- 500500
10:56:35.925 [pool-1-thread-3] INFO com.iluwatar.halfsynchalfasync.App -- 2001000
```

This is a basic example of the Half-Sync/Half-Async pattern, where tasks are enqueued and processed asynchronously, while the main thread continues to handle other tasks.

## [When to Use the Half-Sync/Half-Async Pattern in Java](https://java-design-patterns.com/patterns/half-sync-half-async/#when-to-use-the-half-sync-half-async-pattern-in-java)

Use the Half-Sync/Half-Async pattern in scenarios where:

- High performance and efficient concurrency are crucial, such as in Java's standard libraries and network servers managing concurrent connections.
- The system needs to effectively utilize multicore architectures to balance tasks between asynchronous and synchronous processing.
- Decoupling of asynchronous tasks from synchronous processing is necessary to simplify the design and implementation.

## [Real-World Applications of Half-Sync/Half-Async Pattern in Java](https://java-design-patterns.com/patterns/half-sync-half-async/#real-world-applications-of-half-sync-half-async-pattern-in-java)

- The Half-Sync/Half-Async pattern is utilized in various frameworks and systems, including BSD Unix networking, Real-Time CORBA, and Android's AsyncTask framework.
- Java's standard libraries utilize this pattern with thread pools and execution queues in the concurrency utilities (e.g., java.util.concurrent).
- Network servers handling concurrent connections where IO operations are handled asynchronously and processing of requests is done synchronously.

## [Benefits and Trade-offs of Half-Sync/Half-Async Pattern](https://java-design-patterns.com/patterns/half-sync-half-async/#benefits-and-trade-offs-of-half-sync-half-async-pattern)

Benefits:

- This pattern improves system responsiveness and throughput by isolating blocking operations from non-blocking ones, making it a valuable design pattern in Java concurrency.
- Simplifies programming model by isolating asynchronous and synchronous processing layers.

Trade-offs:

- Adds complexity in managing two different processing modes.
- Requires careful design to avoid bottlenecks between the synchronous and asynchronous parts.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/half-sync-half-async/#related-java-design-patterns)

- [Leader/Followers](https://java-design-patterns.com/patterns/leader-followers/): Both patterns manage thread assignments and concurrency, but Leader/Followers uses a single thread to handle all I/O events, dispatching work to others.
- [Producer/Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Can be integrated with Half-Sync/Half-Async to manage work queues between the async and sync parts.
- [Reactor](https://java-design-patterns.com/patterns/reactor/): Often used with Half-Sync/Half-Async to handle multiple service requests delivered to a service handler without blocking the handler.

## [References and Credits](https://java-design-patterns.com/patterns/half-sync-half-async/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)
- [Half-Sync/Half-Async (Douglas C. Schmidt and Charles D. Cranor)](https://www.dre.vanderbilt.edu/~schmidt/PDF/PLoP-95.pdf)

---

## [concurrency/leader-election] Leader Election
> 官方文档: https://java-design-patterns.com/patterns/leader-election/

ConcurrencyAPI designCloud distributedFault toleranceScalabilitySynchronizationAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/leader-election/#also-known-as)

- Coordinator Election
- Master Election

## [Intent of Leader Election Design Pattern](https://java-design-patterns.com/patterns/leader-election/#intent-of-leader-election-design-pattern)

The Leader Election design pattern is crucial for enabling a system to elect a leader from a group of nodes, ensuring the leader is consistently recognized and able to coordinate tasks while other nodes remain followers. This pattern is fundamental in distributed systems, particularly for achieving fault tolerance and high availability.

## [Detailed Explanation of Leader Election Pattern with Real-World Examples](https://java-design-patterns.com/patterns/leader-election/#detailed-explanation-of-leader-election-pattern-with-real-world-examples)

Real-world example

> A real-world analogy to the Leader Election pattern is the election of a team captain in sports. All team members (nodes) participate in the election process, following a set of agreed-upon rules (protocol). Once a captain (leader) is chosen, they assume responsibility for coordinating strategies, giving directions, and representing the team in discussions. If the captain is injured or unavailable, the team holds a new election or appoints a vice-captain (failover mechanism) to ensure that leadership and direction are maintained consistently.

In plain words

> The leader election pattern is a design approach that enables a distributed system to select one node as the coordinator or leader to manage tasks and maintain order, while other nodes operate as followers.

Wikipedia says

> In distributed computing, leader election is the process of designating a single process as the organizer of some task distributed among several computers (nodes). Before the task has begun, all network nodes are either unaware which node will serve as the "leader" (or coordinator) of the task, or unable to communicate with the current coordinator. After a leader election algorithm has been run, however, each node throughout the network recognizes a particular, unique node as the task leader.

Sequence diagram

![Leader Election Sequence Diagram](https://java-design-patterns.com/assets/img/leader-election-sequence-diagram.abffb452.png)

## [Programmatic Example of Leader Election Pattern in Java](https://java-design-patterns.com/patterns/leader-election/#programmatic-example-of-leader-election-pattern-in-java)

The Leader Election pattern is a design approach that enables a distributed system to select one node as the coordinator or leader to manage tasks and maintain order, while other nodes operate as followers. This pattern is particularly useful in distributed systems where one node needs to act as a central coordinator for a specific function or decision-making process.

In the provided code, we have an `AbstractMessageManager` class and `AbstractInstance` class. The `AbstractMessageManager` class is responsible for managing messages between instances and finding the next instance (potential leader) based on certain conditions. The `AbstractInstance` class represents a node in the distributed system.

Let's break down the code and explain how it works:

```java
public abstract class AbstractMessageManager implements MessageManager {

  protected Map<Integer, Instance> instanceMap;

  public AbstractMessageManager(Map<Integer, Instance> instanceMap) {
    this.instanceMap = instanceMap;
  }

  protected Instance findNextInstance(int currentId) {
    // Implementation details...
  }

}
```

The `AbstractMessageManager` class manages the instances in the system. It contains a map of instances, where the key is the instance ID and the value is the instance itself. The `findNextInstance` method is used to find the next instance with the smallest ID that is alive. This method can be used in the leader election process to determine the next leader if the current leader fails.

```java
public abstract class AbstractInstance implements Instance {

  protected int id;
  protected boolean alive;
  protected MessageManager messageManager;

  public AbstractInstance(MessageManager messageManager, int id) {
    this.messageManager = messageManager;
    this.id = id;
    this.alive = true;
  }

  public boolean isAlive() {
    return alive;
  }

  public void setAlive(boolean alive) {
    this.alive = alive;
  }

  public void onMessage(Message message) {
    // Implementation details...
  }

}
```

The `AbstractInstance` class represents a node in the distributed system. Each instance can check if it's alive, set its health status, and consume messages from other instances.

Now, let's look at the `BullyApp` and `RingApp` classes, which implement two different leader election algorithms:

```java
public class BullyApp {

  public static void main(String[] args) {

    Map<Integer, Instance> instanceMap = new HashMap<>();
    var messageManager = new BullyMessageManager(instanceMap);

    var instance1 = new BullyInstance(messageManager, 1, 1);
    // ... more instances ...

    instanceMap.put(1, instance1);
    // ... more instances ...

    instance1.setAlive(false);
  }
}
```

The `BullyApp` class implements the Bully algorithm for leader election. In this algorithm, when a node notices the leader is down, it starts an election by sending an election message to all nodes with higher IDs. If it doesn't receive a response, it declares itself the leader and sends a victory message to all nodes with lower IDs.

```java
public class RingApp {

  public static void main(String[] args) {

    Map<Integer, Instance> instanceMap = new HashMap<>();
    var messageManager = new RingMessageManager(instanceMap);

    var instance1 = new RingInstance(messageManager, 1, 1);
    // ... more instances ...

    instanceMap.put(1, instance1);
    // ... more instances ...

    instance1.setAlive(false);
  }
}
```

The `RingApp` class implements the Ring algorithm for leader election. In this algorithm, each node sends an election message to its neighbor in a logical ring topology. When a node receives an election message, it passes it on if the ID in the message is higher than its own. The process continues until the message has made a full circle, at which point the node with the highest ID becomes the leader.

These examples demonstrate how the Leader Election pattern can be implemented in different ways to suit the specific requirements of a distributed system.

## [When to Use the Leader Election Pattern in Java](https://java-design-patterns.com/patterns/leader-election/#when-to-use-the-leader-election-pattern-in-java)

Use the Leader Election pattern in Java applications where:

- A distributed system needs one node to act as the central coordinator for a specific function or decision-making process.
- High availability is essential, and the leader should be replaceable in case of failure.
- Coordination is required across different nodes in a cluster, particularly in cloud environments.

## [Real-World Applications of Leader Election Pattern in Java](https://java-design-patterns.com/patterns/leader-election/#real-world-applications-of-leader-election-pattern-in-java)

- Apache ZooKeeper: Provides leader election for distributed services.
- Kubernetes: Elects a leader pod to manage stateful workloads.
- Hazelcast: Distributed data grid uses leader election for cluster management.

## [Benefits and Trade-offs of Leader Election Pattern](https://java-design-patterns.com/patterns/leader-election/#benefits-and-trade-offs-of-leader-election-pattern)

Benefits:

- Consistency: Ensures a single, consistent leader handles coordination tasks.
- Fault Tolerance: Allows for leader replacement if the current leader fails.
- Scalability: Works effectively in large, distributed systems where multiple nodes are present.

Trade-offs:

- Complexity: Requires careful implementation to handle network partitions and latency.
- Overhead: Election processes may introduce performance overhead.
- Single Point of Failure: Even with redundancy, the leader can become a bottleneck if not carefully designed.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/leader-election/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Followers can observe changes from the leader to stay updated.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): The leader functions as a single instance, acting as a unique decision-maker.
- [State](https://java-design-patterns.com/patterns/state/): Helps in managing state transitions, particularly in switching leadership roles.

## [References and Credits](https://java-design-patterns.com/patterns/leader-election/#references-and-credits)

- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z)
- [Distributed Systems: Principles and Paradigms](https://amzn.to/3UN2vbH)
- [Site Reliability Engineering: How Google Runs Production Systems](https://amzn.to/4brjBRI)
- [Leader Election pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/leader-election)

---

## [concurrency/leader-followers] Leader-Followers
> 官方文档: https://java-design-patterns.com/patterns/leader-followers/

ConcurrencyDecouplingPerformanceSynchronizationThread managementAbout 3 min

* * *

## [Intent of Leader/Followers Design Pattern](https://java-design-patterns.com/patterns/leader-followers/#intent-of-leader-followers-design-pattern)

To efficiently manage a set of worker threads, the Leader-Followers pattern enables multiple threads to take turns sharing a set of event sources, optimizing resource utilization and improving performance compared to a one-thread-per-source approach.

## [Detailed Explanation of Leader/Followers Pattern with Real-World Examples](https://java-design-patterns.com/patterns/leader-followers/#detailed-explanation-of-leader-followers-pattern-with-real-world-examples)

Real-world Example

> Imagine managing a busy restaurant with multiple servers and a single host. The host acts as the "leader" and is responsible for greeting guests, managing the waitlist, and seating guests. Once the guests are seated, the host returns to the entrance to manage new arrivals. The servers, or "followers," wait for the host to assign them tables. This assignment is done on a rotational basis where the next available server takes the next group of guests. This system ensures that the host efficiently handles the incoming flow of guests while servers focus on providing service, similar to how the Leader and Followers pattern manages threads and tasks in a software system. This approach optimizes resource utilization (in this case, staff) and ensures smooth operations during peak times, much like it optimizes thread usage in computing environments.

In plain words

> The Leader-Followers design pattern utilizes a single leader thread to distribute work among multiple follower threads, effectively managing task delegation, thread synchronization, and improving resource efficiency in concurrent programming.

[martinfowler.com](https://martinfowler.com/articles/patterns-of-distributed-systems/leader-follower.html) says

> Select one server in the cluster as a leader. The leader is responsible for taking decisions on behalf of the entire cluster and propagating the decisions to all the other servers.

Sequence diagram

![Leader-Followers Sequence Diagram](https://java-design-patterns.com/assets/img/leader-followers-sequence-diagram.2351fc85.png)

## [Programmatic Example of Leader-Followers Pattern in Java](https://java-design-patterns.com/patterns/leader-followers/#programmatic-example-of-leader-followers-pattern-in-java)

The Leader-Followers pattern is a concurrency design pattern where one thread (the leader) waits for work to arrive, de-multiplexes, dispatches, and processes the work, thereby enhancing CPU cache affinity and reducing event dispatching latency. Once the leader finishes processing the work, it promotes one of the follower threads to be the new leader. This pattern is useful for enhancing CPU cache affinity, minimizing locking overhead, and reducing event dispatching latency.

In the provided code, we have a `WorkCenter` class that manages a group of `Worker` threads. One of these workers is designated as the leader and is responsible for receiving and processing tasks. Once a task is processed, the leader promotes a new leader from the remaining workers.

```java
// WorkCenter class
public class WorkCenter {

  @Getter
  private Worker leader;
  private final List<Worker> workers = new CopyOnWriteArrayList<>();

  // Method to create workers and set the initial leader
  public void createWorkers(int numberOfWorkers, TaskSet taskSet, TaskHandler taskHandler) {
    for (var id = 1; id <= numberOfWorkers; id++) {
      var worker = new Worker(id, this, taskSet, taskHandler);
      workers.add(worker);
    }
    promoteLeader();
  }

  // Method to promote a new leader
  public void promoteLeader() {
    Worker leader = null;
    if (!workers.isEmpty()) {
      leader = workers.get(0);
    }
    this.leader = leader;
  }
}
```

In the `Worker` class, each worker is a thread that waits for tasks to process. If the worker is the leader, it processes the task and then promotes a new leader.

```java
// Worker class
public class Worker implements Runnable {

  private final long id;
  private final WorkCenter workCenter;
  private final TaskSet taskSet;
  private final TaskHandler taskHandler;

  @Override
  public void run() {
    while (!Thread.interrupted()) {
      try {
        if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) {
          synchronized (workCenter) {
            if (workCenter.getLeader() != null && !workCenter.getLeader().equals(this)) {
              workCenter.wait();
              continue;
            }
          }
        }
        final Task task = taskSet.getTask();
        synchronized (workCenter) {
          workCenter.removeWorker(this);
          workCenter.promoteLeader();
          workCenter.notifyAll();
        }
        taskHandler.handleTask(task);
        workCenter.addWorker(this);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return;
      }
    }
  }
}
```

In the `App` class, we create a `WorkCenter`, add tasks to a `TaskSet`, and then start the workers. The leader worker will start processing the tasks, and once it finishes a task, it will promote a new leader.

```java
// App class
public class App {

  public static void main(String[] args) throws InterruptedException {
    var taskSet = new TaskSet();
    var taskHandler = new TaskHandler();
    var workCenter = new WorkCenter();
    workCenter.createWorkers(4, taskSet, taskHandler);
    addTasks(taskSet);
    startWorkers(workCenter);
  }

  private static void addTasks(TaskSet taskSet) throws InterruptedException {
    var rand = new SecureRandom();
    for (var i = 0; i < 5; i++) {
      var time = Math.abs(rand.nextInt(1000));
      taskSet.addTask(new Task(time));
    }
  }

  private static void startWorkers(WorkCenter workCenter) throws InterruptedException {
    var workers = workCenter.getWorkers();
    var exec = Executors.newFixedThreadPool(workers.size());
    workers.forEach(exec::submit);
    exec.awaitTermination(2, TimeUnit.SECONDS);
    exec.shutdownNow();
  }
}
```

This is a basic example of the Leader/Followers pattern. The leader worker processes tasks and promotes a new leader once it finishes a task. The new leader then starts processing the next task, and the cycle continues.

## [When to Use the Leader/Followers Pattern in Java](https://java-design-patterns.com/patterns/leader-followers/#when-to-use-the-leader-followers-pattern-in-java)

- The Leader-Followers pattern is useful in scenarios requiring efficient handling of multiple services on a single thread, avoiding resource thrashing, and improving scalability in concurrent programming environments.
- Applicable in server environments where multiple client requests must be handled concurrently with minimal resource consumption.

## [Real-World Applications of Leader-Followers Pattern in Java](https://java-design-patterns.com/patterns/leader-followers/#real-world-applications-of-leader-followers-pattern-in-java)

- Network servers handling multiple incoming connections.
- Event-driven applications that manage a large number of input/output sources.

## [Benefits and Trade-offs of Leader/Followers Pattern](https://java-design-patterns.com/patterns/leader-followers/#benefits-and-trade-offs-of-leader-followers-pattern)

Benefits:

- Reduces the number of threads and context switching, leading to better performance and lower resource utilization.
- Improves system scalability and responsiveness.

Trade-offs:

- Increased complexity in managing the synchronization between leader and followers.
- Potential for underutilization of resources if not correctly implemented.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/leader-followers/#related-java-design-patterns)

- [Half-Sync/Half-Async](https://java-design-patterns.com/patterns/half-sync-half-async/): Leader and Followers can be seen as a variation where the synchronization aspect is divided between the leader (synchronous handling) and followers (waiting asynchronously).
- [Thread Pool](https://java-design-patterns.com/patterns/thread-pool/): Both patterns manage a pool of worker threads, but Thread Pool assigns tasks to any available thread rather than using a leader to distribute work.

## [References and Credits](https://java-design-patterns.com/patterns/leader-followers/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)

---

## [concurrency/lockable-object] Lockable Object
> 官方文档: https://java-design-patterns.com/patterns/lockable-object/

ConcurrencyDecouplingEncapsulationSecuritySynchronizationThread managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/lockable-object/#also-known-as)

- Resource Lock
- Mutual Exclusion Object

## [Intent of Lockable Object Design Pattern](https://java-design-patterns.com/patterns/lockable-object/#intent-of-lockable-object-design-pattern)

The Lockable Object pattern in Java aims to control access to a shared resource in a multithreaded environment, ensuring thread safety by providing a mechanism for resource locking, ensuring that only one thread can access the resource at a time.

## [Detailed Explanation of Lockable Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/lockable-object/#detailed-explanation-of-lockable-object-pattern-with-real-world-examples)

Real-world example

> Imagine a shared printer in a busy office as an analogous real-world example of the Lockable Object design pattern in Java. This pattern ensures that only one thread can access the resource at a time, thus maintaining concurrency control and synchronization. Multiple employees need to print documents throughout the day, but the printer can only handle one print job at a time. To manage this, there's a locking system in place—much like a lockable object in programming—that ensures when one person is printing, others must wait their turn. This prevents print jobs from overlapping or interfering with each other, ensuring that each document is printed correctly and in the order it was sent, mirroring the concept of thread synchronization and resource locking in software development.

In plain words

> The Lockable Object design pattern ensures safe access to a shared resource in a multithreaded environment by allowing only one thread to access the resource at a time through locking mechanisms.

Wikipedia says

> In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive that prevents state from being modified or accessed by multiple threads of execution at once. Locks enforce mutual exclusion concurrency control policies, and with a variety of possible methods there exist multiple unique implementations for different applications.

Sequence diagram

![Lockable Object Sequence Diagram](https://java-design-patterns.com/assets/img/lockable-object-sequence-diagram.c2d6ccfe.png)

## [Programmatic Example of Lockable Object Pattern in Java](https://java-design-patterns.com/patterns/lockable-object/#programmatic-example-of-lockable-object-pattern-in-java)

The Lockable Object pattern is a concurrency control design pattern in Java that allows only one thread to access a shared resource at a time, ensuring mutual exclusion and preventing data corruption. Instead of using the `synchronized` keyword on the methods to be synchronized, the object which implements the Lockable interface handles the request.

In this example, we have a `SwordOfAragorn` object that implements the `Lockable` interface. Multiple `Creature` objects, represented by `Elf`, `Orc`, and `Human` classes, are trying to acquire the sword. Each `Creature` is wrapped in a `Feind` object that implements `Runnable`, allowing each creature to attempt to acquire the sword in a separate thread.

Here's the `Lockable` interface:

```java
public interface Lockable {
  boolean isLocked();
  Creature getLocker();
  boolean acquire(Creature creature);
  void release(Creature creature);
}
```

The `SwordOfAragorn` class implements this interface:

```java
public class SwordOfAragorn implements Lockable {
  // Implementation details...
}
```

The `Creature` class and its subclasses (`Elf`, `Orc`, `Human`) represent different creatures that can try to acquire the sword:

```java
public abstract class Creature {
  // Implementation details...
}

public class Elf extends Creature {
  // Implementation details...
}

public class Orc extends Creature {
  // Implementation details...
}

public class Human extends Creature {
  // Implementation details...
}
```

The `Feind` class wraps a `Creature` and a `Lockable` object, and implements `Runnable`:

```java
public class Feind implements Runnable {
  private final Creature creature;
  private final Lockable target;

  public Feind(@NonNull Creature feind, @NonNull Lockable target) {
    this.creature = feind;
    this.target = target;
  }

  @Override
  public void run() {
    if (!creature.acquire(target)) {
      fightForTheSword(creature, target.getLocker(), target);
    } else {
      LOGGER.info("{} has acquired the sword!", target.getLocker().getName());
    }
  }

  // Additional methods...
}
```

In the `App` class, multiple `Feind` objects are created and submitted to an `ExecutorService`, each in a separate thread:

```java
public class App implements Runnable {
  @Override
  public void run() {
    var sword = new SwordOfAragorn();
    List<Creature> creatures = new ArrayList<>();
    // Creation of creatures...
    ExecutorService service = Executors.newFixedThreadPool(totalFiends);
    for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) {
      service.submit(new Feind(creatures.get(i), sword));
      service.submit(new Feind(creatures.get(i + 1), sword));
      service.submit(new Feind(creatures.get(i + 2), sword));
    }
    // Additional code...
  }
}
```

This example demonstrates the Lockable Object pattern by showing how multiple threads can attempt to acquire a lock on a shared resource, with only one thread being able to acquire the lock at a time.

## [When to Use the Lockable Object Pattern in Java](https://java-design-patterns.com/patterns/lockable-object/#when-to-use-the-lockable-object-pattern-in-java)

- Use the Lockable Object pattern in Java when you need to prevent data corruption by multiple threads accessing a shared resource concurrently, ensuring thread safety and robust shared resource management.
- Suitable for systems where thread safety is critical and data integrity must be maintained across various operations.

## [Real-World Applications of Lockable Object Pattern in Java](https://java-design-patterns.com/patterns/lockable-object/#real-world-applications-of-lockable-object-pattern-in-java)

- Java’s synchronized keyword and the Lock interfaces in the java.util.concurrent.locks package implement lockable objects to manage synchronization.

## [Benefits and Trade-offs of Lockable Object Pattern](https://java-design-patterns.com/patterns/lockable-object/#benefits-and-trade-offs-of-lockable-object-pattern)

Benefits:

- Ensures data consistency and prevents race conditions.
- Provides clear structure for managing access to shared resources.

Trade-offs:

- Can lead to decreased performance due to overhead of acquiring and releasing locks.
- Potential for deadlocks if not implemented and managed carefully.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/lockable-object/#related-java-design-patterns)

- [Monitor Object](https://java-design-patterns.com/patterns/monitor/): Both patterns manage access to shared resources; Monitor Object combines synchronization and encapsulation of the condition variable.
- [Read/Write Lock](https://java-design-patterns.com/patterns/reader-writer-lock/): Specialization of Lockable Object for scenarios where read operations outnumber write operations.

## [References and Credits](https://java-design-patterns.com/patterns/lockable-object/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)

---

## [concurrency/master-worker] Master-Worker
> 官方文档: https://java-design-patterns.com/patterns/master-worker/

ConcurrencyMultithreadingPerformanceScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/master-worker/#also-known-as)

- Master-Slave
- Controller-Worker

## [Intent of Master-Worker Design Pattern](https://java-design-patterns.com/patterns/master-worker/#intent-of-master-worker-design-pattern)

The Master-Worker design pattern is designed to perform parallel computations by distributing tasks between a master process and multiple worker processes. This pattern enhances concurrency, performance, and scalability in software systems.

## [Detailed Explanation of Master-Worker Pattern with Real-World Examples](https://java-design-patterns.com/patterns/master-worker/#detailed-explanation-of-master-worker-pattern-with-real-world-examples)

Real-world example

> The Master-Worker pattern optimizes parallel task processing and throughput. For instance, in a restaurant kitchen, the head chef (master) delegates tasks to line cooks (workers), who work concurrently to prepare the order. The head chef receives the orders from the dining area and breaks down each order into specific tasks, such as grilling meat, preparing salads, and cooking desserts. Each task is assigned to a different line cook based on their expertise and current workload. The line cooks work in parallel to prepare their portion of the order, while the head chef oversees the process, ensuring everything is prepared correctly and timely. Once each component of the order is ready, the head chef gathers all parts, gives them a final check, and then plates the dishes for service. This kitchen operation mimics the Master-Worker pattern by distributing and managing tasks to optimize efficiency and output.

In plain words

> The Master-Worker pattern involves a master process delegating tasks to multiple worker processes, which execute them concurrently and report back, optimizing parallel task processing and throughput.

Wikipedia says

> Master–slave is a model of asymmetric communication or control where one device or process (the master) controls one or more other devices or processes (the slaves) and serves as their communication hub. In some systems, a master is selected from a group of eligible devices, with the other devices acting in the role of slaves.

Sequence diagram

![Master-Worker sequence diagram](https://java-design-patterns.com/assets/img/master-worker-sequence-diagram.9805eb77.png)

## [Programmatic Example of Master-Worker Pattern in Java](https://java-design-patterns.com/patterns/master-worker/#programmatic-example-of-master-worker-pattern-in-java)

In the provided code, the `MasterWorker` class initiates the concurrent computation process. The `Master` class divides the work among `Worker` objects, each performing its task in parallel, thus optimizing task processing and enhancing system efficiency.

```java
// The MasterWorker class acts as the main entry point for the Master-Worker system.
public class MasterWorker {
  private Master master;

  public MasterWorker(Master master) {
    this.master = master;
  }

  public Result getResult(Input input) {
    return master.computeResult(input);
  }
}
```

In this code, the `MasterWorker` class is initialized with a `Master` object. The `getResult` method is used to start the computation process.

```java
// The Master class is responsible for dividing the work among the workers.
public abstract class Master {
  protected List<Worker> workers;

  public Master(List<Worker> workers) {
    this.workers = workers;
  }

  public abstract Result computeResult(Input input);
}
```

The `Master` class has a list of `Worker` objects. The `computeResult` method is abstract and should be implemented in a subclass to define how the work is divided and how the results are aggregated.

```java
// The Worker class is responsible for performing the actual computation.
public abstract class Worker extends Thread {
  protected Input input;

  public void setInput(Input input) {
    this.input = input;
  }

  public abstract Result compute();
}
```

The `Worker` class extends `Thread`, allowing it to perform computations in parallel. The `compute` method is abstract and should be implemented in a subclass to define the actual computation logic.

```java
// The Input and Result classes are used to encapsulate the input data and the result data.
public abstract class Input<T> {
  public final T data;

  public Input(T data) {
    this.data = data;
  }

  public abstract List<Input<T>> divideData(int num);
}

public abstract class Result<T> {
  public final T data;

  public Result(T data) {
    this.data = data;
  }
}
```

The `Input` class has a `divideData` method that is used to divide the input data into subtasks. The `Result` class simply encapsulates the result data.

## [When to Use the Master-Worker Pattern in Java](https://java-design-patterns.com/patterns/master-worker/#when-to-use-the-master-worker-pattern-in-java)

- Suitable for scenarios where a task can be decomposed into smaller, independent tasks.
- Useful in applications requiring concurrent execution to enhance performance.
- Applicable in distributed computing where tasks need to be processed by multiple processors or machines.

## [Master-Worker Pattern Java Tutorials](https://java-design-patterns.com/patterns/master-worker/#master-worker-pattern-java-tutorials)

- [Master-Worker Pattern (Gigaspaces)](https://docs.gigaspaces.com/sbp/master-worker-pattern.html)

## [Real-World Applications of Master-Worker Pattern in Java](https://java-design-patterns.com/patterns/master-worker/#real-world-applications-of-master-worker-pattern-in-java)

- Implemented in distributed systems to manage tasks across different computing resources.
- Used in server architectures to process multiple client requests simultaneously.
- Utilized in scientific computation frameworks where large datasets require parallel processing.

## [Benefits and Trade-offs of Master-Worker Pattern](https://java-design-patterns.com/patterns/master-worker/#benefits-and-trade-offs-of-master-worker-pattern)

Benefits:

- Enhances performance by parallelizing tasks.
- Increases responsiveness of systems handling large volumes of requests.
- Provides a clear separation of concerns between task coordination and task execution, simplifying design.

Trade-offs:

- Complexity in managing synchronization and state consistency between master and workers.
- Overhead of managing communication between master and workers, especially in distributed environments.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/master-worker/#related-java-design-patterns)

- Task Parallelism and Data Parallelism: Master-Worker utilizes these patterns to divide work into tasks or data segments.
- [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Similar in structure but focuses on balancing production and consumption rates; Master-Worker is more about task distribution and aggregation.
- [Pipeline](https://java-design-patterns.com/patterns/pipeline/): Both organize processing steps but Pipeline arranges them linearly whereas Master-Worker may not impose such a sequence.

## [References and Credits](https://java-design-patterns.com/patterns/master-worker/#references-and-credits)

- [Distributed Systems: Principles and Paradigms](https://amzn.to/3UN2vbH)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)

---

## [concurrency/monitor] Monitor
> 官方文档: https://java-design-patterns.com/patterns/monitor/

ConcurrencyEncapsulationFault toleranceIsolationSynchronizationThread managementAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/monitor/#also-known-as)

- Synchronized Block

## [Intent of Monitor Design Pattern](https://java-design-patterns.com/patterns/monitor/#intent-of-monitor-design-pattern)

The Monitor design pattern in Java is essential for synchronizing concurrent operations, ensuring thread safety and preventing race conditions.

## [Detailed Explanation of Monitor Pattern with Real-World Examples](https://java-design-patterns.com/patterns/monitor/#detailed-explanation-of-monitor-pattern-with-real-world-examples)

Real-world example

> Imagine a shared office printer that several employees need to use. The printer can only handle one print job at a time to avoid mixing up pages from different documents. This scenario is analogous to the Monitor design pattern in programming.
>
> In this example, the printer represents the shared resource, and the employees are analogous to threads. A system is set up where each employee must request access to the printer before starting their print job. This system ensures that only one employee (or "thread") can use the printer at a time, preventing any overlap or interference between jobs. Once a print job is complete, the next employee in the queue can access the printer. This mechanism mirrors the Monitor pattern's way of controlling access to a shared resource, ensuring orderly and safe use by multiple "threads" (employees).

In plain words

> Monitor pattern is used to enforce single-threaded access to data. Only one thread at a time is allowed to execute code within the monitor object.

Wikipedia says

> In concurrent programming (also known as parallel programming), a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false. Monitors also have a mechanism for signaling other threads that their condition has been met.

Sequence diagram

![Monitor sequence diagram](https://java-design-patterns.com/assets/img/monitor-sequence-diagram.235cb4b0.png)

## [Programmatic Example of Monitor Pattern in Java](https://java-design-patterns.com/patterns/monitor/#programmatic-example-of-monitor-pattern-in-java)

The Monitor design pattern is a synchronization technique used in concurrent programming to ensure that only one thread can execute a particular section of code at a time. It is a method of wrapping and hiding the synchronization primitives (like semaphores or locks) within the methods of an object. This pattern is useful in situations where race conditions could occur.

The Java Monitor design pattern can be seen in the `Bank` class example. By using synchronized methods, the `Bank` class ensures that only one thread can perform transactions at any given time, illustrating effective use of the Monitor pattern in real-world applications.

Here is a simplified version of the `Bank` class with additional comments:

```java
public class Bank {

    @Getter
    private final int[] accounts;

    public Bank(int accountNum, int baseAmount) {
        accounts = new int[accountNum];
        Arrays.fill(accounts, baseAmount);
    }

    public synchronized void transfer(int accountA, int accountB, int amount) {
        // Only one thread can execute this method at a time due to the 'synchronized' keyword.
        if (accounts[accountA] >= amount && accountA != accountB) {
            accounts[accountB] += amount;
            accounts[accountA] -= amount;
        }
    }

    public synchronized int getBalance() {
        // Only one thread can execute this method at a time due to the 'synchronized' keyword.
        int balance = 0;
        for (int account : accounts) {
            balance += account;
        }
        return balance;
    }

    public synchronized int getBalance(int accountNumber) {
        // Only one thread can execute this method at a time due to the 'synchronized' keyword.
        return accounts[accountNumber];
    }
}
```

In the `Main` class, multiple threads are created to perform transactions on the bank accounts. The `Bank` class, acting as a monitor, ensures that these transactions are performed in a thread-safe manner.

```java
public class Main {

    private static final int NUMBER_OF_THREADS = 5;
    private static final int BASE_AMOUNT = 1000;
    private static final int ACCOUNT_NUM = 4;

    public static void runner(Bank bank, CountDownLatch latch) {
        try {
            SecureRandom random = new SecureRandom();
            Thread.sleep(random.nextInt(1000));
            for (int i = 0; i < 1000000; i++) {
                bank.transfer(random.nextInt(4), random.nextInt(4), random.nextInt(0, BASE_AMOUNT));
            }
            latch.countDown();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        var bank = new Bank(ACCOUNT_NUM, BASE_AMOUNT);
        var latch = new CountDownLatch(NUMBER_OF_THREADS);
        var executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

        for (int i = 0; i < NUMBER_OF_THREADS; i++) {
            executorService.execute(() -> runner(bank, latch));
        }

        latch.await();
    }
}
```

In this example, the `Bank` class is the monitor, and the `transfer` method is the critical section that needs to be executed in a mutually exclusive manner. The `synchronized` keyword in Java is used to implement the Monitor pattern, ensuring that only one thread can execute the `transfer` method at a time.

## [When to Use the Monitor Pattern in Java](https://java-design-patterns.com/patterns/monitor/#when-to-use-the-monitor-pattern-in-java)

The Monitor design pattern should be used in situations where you have shared resources that need to be accessed and manipulated by multiple threads or processes concurrently. This pattern is particularly useful in scenarios where synchronization is necessary to prevent race conditions, data corruption, and inconsistent states. Here are some situations where you should consider using the Monitor pattern:

1. **Shared Data**: When your application involves shared data structures, variables, or resources that need to be accessed and updated by multiple threads. Monitors ensure that only one thread can access the shared resource at a time, preventing conflicts and ensuring data consistency.

2. **Critical Sections**: When you have critical sections of code that need to be executed by only one thread at a time. Critical sections are portions of code where shared resources are manipulated, and concurrent access could lead to problems. Monitors help ensure that only one thread can execute the critical section at any given time.

3. **Thread Safety**: When you need to ensure thread safety without relying solely on low-level synchronization mechanisms like locks and semaphores. Monitors provide a higher-level abstraction that encapsulates synchronization and resource management.

4. **Waiting and Signaling**: When you have scenarios where threads need to wait for certain conditions to be met before proceeding. Monitors often include mechanisms for threads to wait for specific conditions and for other threads to notify them when the conditions are satisfied.

5. **Deadlock Prevention**: When you want to prevent deadlocks by providing a structured way to acquire and release locks on shared resources. Monitors help avoid common deadlock scenarios by ensuring that resource access is well-managed.

6. **Concurrent Data Structures**: When you're implementing concurrent data structures, such as queues, stacks, or hash tables, where multiple threads need to manipulate the structure while maintaining its integrity.

7. **Resource Sharing**: When multiple threads need to share limited resources, like connections to a database or access to a network socket. Monitors can help manage the allocation and release of these resources in a controlled manner.

8. **Improved Maintainability**: When you want to encapsulate synchronization logic and shared resource management within a single object, improving code organization and making it easier to reason about concurrency-related code.


However, it's important to note that the Monitor pattern might not be the best fit for all concurrency scenarios. In some cases, other synchronization mechanisms like locks, semaphores, or concurrent data structures might be more suitable. Additionally, modern programming languages and frameworks often provide higher-level concurrency constructs that abstract away the complexities of low-level synchronization.

Before applying the Monitor pattern, it's recommended to thoroughly analyze your application's concurrency requirements and choose the synchronization approach that best suits your needs, taking into consideration factors like performance, complexity, and available language features.

## [Real-World Applications of Monitor Pattern in Java](https://java-design-patterns.com/patterns/monitor/#real-world-applications-of-monitor-pattern-in-java)

Common implementations of the Monitor design pattern in Java include synchronized methods and blocks, as well as concurrent data structures like `Vector` and `Hashtable`.

## [Benefits and Trade-offs of Monitor Pattern](https://java-design-patterns.com/patterns/monitor/#benefits-and-trade-offs-of-monitor-pattern)

Benefits:

- Ensures mutual exclusion, preventing race conditions.
- Simplifies the complexity of thread management by providing a clear structure for resource access.

Trade-offs:

- Can lead to decreased performance due to locking overhead.
- Potential for deadlocks if not carefully designed.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/monitor/#related-java-design-patterns)

Semaphore: Used to control access to a common resource by multiple threads; Monitor uses a binary semaphore concept at its core.

Mutex: Another mechanism for ensuring mutual exclusion; Monitor is a higher-level construct often implemented using mutexes.

## [References and Credits](https://java-design-patterns.com/patterns/monitor/#references-and-credits)

- [Concurrency: State Models & Java Programs](https://amzn.to/4dxxjUX)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)

---

## [concurrency/poison-pill] Poison Pill
> 官方文档: https://java-design-patterns.com/patterns/poison-pill/

ConcurrencyDecouplingFault toleranceMessagingThread managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/poison-pill/#also-known-as)

- Shutdown Signal

## [Intent of Poison Pill Design Pattern](https://java-design-patterns.com/patterns/poison-pill/#intent-of-poison-pill-design-pattern)

The Poison Pill design pattern is used to gracefully shut down a service or a producer-consumer system by sending a special message (the "poison pill") to message queue which indicates that no more messages will be sent, allowing the consumers to terminate.

## [Detailed Explanation of Poison Pill Pattern with Real-World Examples](https://java-design-patterns.com/patterns/poison-pill/#detailed-explanation-of-poison-pill-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Poison Pill design pattern is the use of a "closed" sign in a retail store. When the store is ready to close for the day, the manager places a "closed" sign on the door. This sign acts as a signal to any new customers that no more customers will be admitted, but it doesn't immediately force out the customers already inside. The store staff will then attend to the remaining customers, allowing them to complete their purchases before finally locking up and turning off the lights. Similarly, in the Poison Pill pattern, a special "poison pill" message signals consumers to stop accepting new tasks while allowing them to finish processing the current tasks before shutting down gracefully.

In plain words

> Poison Pill is a known message structure that ends the message exchange.

Sequence diagram

![Poison Pill sequence diagram](https://java-design-patterns.com/assets/img/poison-pill-sequence-diagram.1fd1a9ed.png)

## [Programmatic Example of Poison Pill Pattern in Java](https://java-design-patterns.com/patterns/poison-pill/#programmatic-example-of-poison-pill-pattern-in-java)

In this Java example, the Poison Pill serves as a shutdown signal within message queues, demonstrating effective thread management and consumer communication.

Let's define the message structure first. There's interface `Message` and implementation `SimpleMessage`.

```java
public interface Message {

  // Other properties and methods...

  enum Headers {
    DATE, SENDER
  }

  void addHeader(Headers header, String value);

  String getHeader(Headers header);

  Map<Headers, String> getHeaders();

  void setBody(String body);

  String getBody();
}

public class SimpleMessage implements Message {

  private final Map<Headers, String> headers = new HashMap<>();
  private String body;

  @Override
  public void addHeader(Headers header, String value) {
    headers.put(header, value);
  }

  @Override
  public String getHeader(Headers header) {
    return headers.get(header);
  }

  @Override
  public Map<Headers, String> getHeaders() {
    return Collections.unmodifiableMap(headers);
  }

  @Override
  public void setBody(String body) {
    this.body = body;
  }

  @Override
  public String getBody() {
    return body;
  }
}
```

To pass messages we are using message queues. Here we define the types related to the message queue: `MqPublishPoint`, `MqSubscribePoint` and `MessageQueue`. `SimpleMessageQueue` implements all these interfaces.

```java
public interface MqPublishPoint {
  void put(Message msg) throws InterruptedException;
}

public interface MqSubscribePoint {
  Message take() throws InterruptedException;
}

public interface MessageQueue extends MqPublishPoint, MqSubscribePoint {}

public class SimpleMessageQueue implements MessageQueue {

  private final BlockingQueue<Message> queue;

  public SimpleMessageQueue(int bound) {
    queue = new ArrayBlockingQueue<>(bound);
  }

  @Override
  public void put(Message msg) throws InterruptedException {
    queue.put(msg);
  }

  @Override
  public Message take() throws InterruptedException {
    return queue.take();
  }
}
```

Next, we need message `Producer` and `Consumer`. Internally they use the message queues from above. It's important to notice that when `Producer` stops, it sends out the poison pill to inform `Consumer` that the messaging has finished.

```java
public class Producer {

  // Other properties and methods...

  public void send(String body) {
    if (isStopped) {
      throw new IllegalStateException(String.format(
          "Producer %s was stopped and fail to deliver requested message [%s].", body, name));
    }
    var msg = new SimpleMessage();
    msg.addHeader(Headers.DATE, new Date().toString());
    msg.addHeader(Headers.SENDER, name);
    msg.setBody(body);

    try {
      queue.put(msg);
    } catch (InterruptedException e) {
      // allow thread to exit
      LOGGER.error("Exception caught.", e);
    }
  }

  public void stop() {
    isStopped = true;
    try {
      queue.put(Message.POISON_PILL);
    } catch (InterruptedException e) {
      // allow thread to exit
      LOGGER.error("Exception caught.", e);
    }
  }
}

public class Consumer {

  // Other properties and methods...

  public void consume() {
    while (true) {
      try {
        var msg = queue.take();
        if (Message.POISON_PILL.equals(msg)) {
          LOGGER.info("Consumer {} receive request to terminate.", name);
          break;
        }
        var sender = msg.getHeader(Headers.SENDER);
        var body = msg.getBody();
        LOGGER.info("Message [{}] from [{}] received by [{}]", body, sender, name);
      } catch (InterruptedException e) {
        // allow thread to exit
        LOGGER.error("Exception caught.", e);
        return;
      }
    }
  }
}
```

Finally, we are ready to present the whole example in action.

```java
  public static void main(String[] args) {
    var queue = new SimpleMessageQueue(10000);

    final var producer = new Producer("PRODUCER_1", queue);
    final var consumer = new Consumer("CONSUMER_1", queue);

    new Thread(consumer::consume).start();

    new Thread(() -> {
        producer.send("hand shake");
        producer.send("some very important information");
        producer.send("bye!");
        producer.stop();
    }).start();
}
```

Program output:

```
07:43:01.518 [Thread-0] INFO com.iluwatar.poison.pill.Consumer -- Message [hand shake] from [PRODUCER_1] received by [CONSUMER_1]
07:43:01.520 [Thread-0] INFO com.iluwatar.poison.pill.Consumer -- Message [some very important information] from [PRODUCER_1] received by [CONSUMER_1]
07:43:01.520 [Thread-0] INFO com.iluwatar.poison.pill.Consumer -- Message [bye!] from [PRODUCER_1] received by [CONSUMER_1]
07:43:01.520 [Thread-0] INFO com.iluwatar.poison.pill.Consumer -- Consumer CONSUMER_1 receive request to terminate.
```

## [When to Use the Poison Pill Pattern in Java](https://java-design-patterns.com/patterns/poison-pill/#when-to-use-the-poison-pill-pattern-in-java)

Use the Poison Pill idiom when:

- Systems require robust fault tolerance and seamless consumer shutdown in multithreaded environments.
- In producer-consumer scenarios where consumers need to be informed about the end of message processing.
- To ensure that consumers can finish processing remaining messages before shutting down.

## [Real-World Applications of Poison Pill Pattern in Java](https://java-design-patterns.com/patterns/poison-pill/#real-world-applications-of-poison-pill-pattern-in-java)

- Java ExecutorService shutdown using a special task to signal shutdown.
- Messaging systems where a specific message indicates the end of the queue processing.
- [Akka framework](https://doc.akka.io/japi/akka/2.5/akka/actor/typed/internal/PoisonPill.html)

## [Benefits and Trade-offs of Poison Pill Pattern](https://java-design-patterns.com/patterns/poison-pill/#benefits-and-trade-offs-of-poison-pill-pattern)

Benefits:

- Simplifies the shutdown process of consumers.
- Ensures that all pending tasks are completed before termination.
- Decouples the shutdown logic from the main processing logic.

Trade-offs:

- Requires consumers to check for the poison pill, adding some overhead.
- If not managed properly, could lead to consumers not recognizing the poison pill, causing indefinite blocking.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/poison-pill/#related-java-design-patterns)

- [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Works in tandem with the Poison Pill pattern to handle the communication and shutdown of consumers.
- Message Queue: Often uses poison pills to signal the end of message processing in the queue.
- [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify subscribers about the shutdown event.

## [References and Credits](https://java-design-patterns.com/patterns/poison-pill/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Effective Java](https://amzn.to/4cGk2Jz)

---

## [concurrency/producer-consumer] Producer-Consumer
> 官方文档: https://java-design-patterns.com/patterns/producer-consumer/

ConcurrencyAsynchronousBufferingDecouplingMessagingSynchronizationThread managementAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/producer-consumer/#also-known-as)

- Bounded Buffer
- Consumer-Producer

## [Intent of Producer-Consumer Design Pattern](https://java-design-patterns.com/patterns/producer-consumer/#intent-of-producer-consumer-design-pattern)

The Producer-Consumer design pattern, a critical component for concurrent Java applications, is used to decouple the tasks of producing and consuming data, enabling a producer to generate data and a consumer to process that data concurrently without direct dependency on each other.

## [Detailed Explanation of Producer-Consumer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/producer-consumer/#detailed-explanation-of-producer-consumer-pattern-with-real-world-examples)

Real-world example

> In a typical car manufacturing setup, the Producer-Consumer pattern facilitates synchronous operations, ensuring efficient assembly and installation processes. Imagine a car manufacturing plant where different stages of production occur. The "producer" could be the station that assembles car engines, while the "consumer" could be the station that installs the engines into car bodies. The engines are placed onto a conveyor belt (acting as a buffer) once they are assembled. The installation station takes engines off the conveyor belt to install them into cars. This allows the engine assembly and engine installation processes to operate independently, with the conveyor belt managing the synchronization between these two stages. If the assembly station produces engines faster than the installation station can install them, the excess engines are temporarily stored on the conveyor belt. Conversely, if the installation station needs engines but the assembly station is temporarily halted, it can still work on the engines available on the belt.

In plain words

> It provides a way to share data between multiple loops running at different rates.

Wikipedia says

> Dijkstra wrote about the case: "We consider two processes, which are called the 'producer' and the 'consumer' respectively. The producer is a cyclic process that produces a certain portion of information, that has to be processed by the consumer. The consumer is also a cyclic process that needs to process the next portion of information, as has been produced by the producer. We assume the two processes to be connected for this purpose via a buffer with unbounded capacity."

Sequence diagram

![Producer-Consumer sequence diagram](https://java-design-patterns.com/assets/img/producer-consumer-sequence-diagram.70492f95.png)

## [Programmatic Example of Producer-Consumer Pattern in Java](https://java-design-patterns.com/patterns/producer-consumer/#programmatic-example-of-producer-consumer-pattern-in-java)

Consider a manufacturing process of item, the producer will need to pause the production when manufacturing pipeline is full and the consumer will need to pause the consumption of item when the manufacturing pipeline is empty. We can separate the process of production and consumption which work together and pause at separate times.

In this Java example, `Producers` generate items stored in `ItemQueue`, demonstrating efficient thread management and data synchronization essential for high-performance Java applications.

We have a simple `Item` record. They are stored in `ItemQueue`.

```java
public record Item(String producer, int id) {}
```

```java
public class ItemQueue {

    private final BlockingQueue<Item> queue;

    public ItemQueue() {
        queue = new LinkedBlockingQueue<>(5);
    }

    public void put(Item item) throws InterruptedException {
        queue.put(item);
    }

    public Item take() throws InterruptedException {
        return queue.take();
    }
}
```

`Producer` produces items to the `ItemQueue`.

```java
public class Producer {

  private static final SecureRandom RANDOM = new SecureRandom();
  private final ItemQueue queue;
  private final String name;
  private int itemId;

  public Producer(String name, ItemQueue queue) {
    this.name = name;
    this.queue = queue;
  }

  public void produce() throws InterruptedException {

    var item = new Item(name, itemId++);
    queue.put(item);
    Thread.sleep(RANDOM.nextInt(2000));
  }
}
```

Then, we have the `Consumer` class that takes items from the `ItemQueue`.

```java
@Slf4j
public class Consumer {

  private final ItemQueue queue;
  private final String name;

  public Consumer(String name, ItemQueue queue) {
    this.name = name;
    this.queue = queue;
  }

  public void consume() throws InterruptedException {
    var item = queue.take();
    LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name,
        item.getId(), item.getProducer());

  }
}
```

Now, during the manufacturing pipeline, we can instantiate objects from both the `Producer` and `Consumer` classes as they produce and consume items from the queue.

```java
  public static void main(String[] args) {

    var queue = new ItemQueue();

    var executorService = Executors.newFixedThreadPool(5);
    for (var i = 0; i < 2; i++) {

        final var producer = new Producer("Producer_" + i, queue);
        executorService.submit(() -> {
            while (true) {
                producer.produce();
            }
        });
    }

    for (var i = 0; i < 3; i++) {
        final var consumer = new Consumer("Consumer_" + i, queue);
        executorService.submit(() -> {
            while (true) {
                consumer.consume();
            }
        });
    }

    executorService.shutdown();
    try {
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdownNow();
    } catch (InterruptedException e) {
        LOGGER.error("Error waiting for ExecutorService shutdown");
    }
}
```

Program output:

```
08:10:08.008 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [0] produced by [Producer_1]
08:10:08.008 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [0] produced by [Producer_0]
08:10:08.517 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [1] produced by [Producer_0]
08:10:08.952 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [1] produced by [Producer_1]
08:10:09.208 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [2] produced by [Producer_0]
08:10:09.354 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [2] produced by [Producer_1]
08:10:10.214 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [3] produced by [Producer_1]
08:10:10.585 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [3] produced by [Producer_0]
08:10:11.530 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [4] produced by [Producer_1]
08:10:11.682 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [4] produced by [Producer_0]
08:10:11.781 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [5] produced by [Producer_0]
08:10:12.209 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [5] produced by [Producer_1]
08:10:13.045 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [6] produced by [Producer_0]
08:10:13.861 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [6] produced by [Producer_1]
08:10:14.739 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [7] produced by [Producer_1]
08:10:14.842 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [7] produced by [Producer_0]
08:10:15.975 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [8] produced by [Producer_0]
08:10:16.378 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [8] produced by [Producer_1]
08:10:16.967 [pool-1-thread-3] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_0] consume item [9] produced by [Producer_0]
08:10:17.417 [pool-1-thread-4] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_1] consume item [9] produced by [Producer_1]
08:10:17.483 [pool-1-thread-5] INFO com.iluwatar.producer.consumer.Consumer -- Consumer [Consumer_2] consume item [10] produced by [Producer_1]
```

## [When to Use the Producer-Consumer Pattern in Java](https://java-design-patterns.com/patterns/producer-consumer/#when-to-use-the-producer-consumer-pattern-in-java)

- When you need to manage a buffer or queue where producers add data and consumers take data, often in a multithreaded environment.
- When decoupling the production and consumption of data is beneficial for the application's design, performance, or maintainability.
- Suitable for scenarios requiring synchronized access to a shared resource or data structure.

## [Real-World Applications of Producer-Consumer Pattern in Java](https://java-design-patterns.com/patterns/producer-consumer/#real-world-applications-of-producer-consumer-pattern-in-java)

- Thread pools where worker threads act as consumers processing tasks produced by another thread.
- Logging frameworks where log messages are produced by various parts of an application and consumed by a logging service.
- Message queues in distributed systems for asynchronous communication between services.

## [Benefits and Trade-offs of Producer-Consumer Pattern](https://java-design-patterns.com/patterns/producer-consumer/#benefits-and-trade-offs-of-producer-consumer-pattern)

Benefits:

- Decoupling: Producers and consumers can operate independently, simplifying the system design.
- Improved Performance: Allows multiple producer and consumer threads to work concurrently, improving throughput.
- Flexibility: Easily extendable to add more producers or consumers without significant changes to the existing system.

Trade-offs:

- Complexity: Requires careful handling of synchronization and potential deadlocks.
- Resource Management: Properly managing the buffer size to avoid overflow or underflow conditions.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/producer-consumer/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): While both deal with notifying or handling events, the Observer pattern is more about event subscription and notification, whereas Producer-Consumer focuses on decoupled data production and consumption.
- [Thread Pool](https://java-design-patterns.com/patterns/thread-pool/): Uses a similar decoupling approach where tasks are produced and consumed by a pool of worker threads.

## [References and Credits](https://java-design-patterns.com/patterns/producer-consumer/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)

---

## [concurrency/promise] Promise
> 官方文档: https://java-design-patterns.com/patterns/promise/

ConcurrencyAsynchronousDecouplingMessagingSynchronizationThread managementAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/promise/#also-known-as)

- Deferred
- Future

## [Intent of Promise Design Pattern](https://java-design-patterns.com/patterns/promise/#intent-of-promise-design-pattern)

The Promise design pattern is used to handle asynchronous operations by providing a placeholder for a result that is initially unknown but will be resolved in the future.

## [Detailed Explanation of Promise Pattern with Real-World Examples](https://java-design-patterns.com/patterns/promise/#detailed-explanation-of-promise-pattern-with-real-world-examples)

Real-world example

> In an online pizza ordering system, when a customer places an order, the system immediately acknowledges the order and provides a tracking number (the promise). The pizza preparation and delivery process happens asynchronously in the background. The customer can check the status of their order at any time using the tracking number. Once the pizza is prepared and out for delivery, the customer receives a notification (promise resolved) about the delivery status. If there are any issues, such as an unavailable ingredient or delivery delay, the customer is notified about the error (promise rejected).
>
> This analogy illustrates how the Promise design pattern manages asynchronous tasks, decoupling the initial request from the eventual outcome, and handling both results and errors efficiently.

In plain words

> Promise is a placeholder for an asynchronous operation that is ongoing.

Wikipedia says

> In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is not yet complete.

Sequence diagram

![Promise sequence diagram](https://java-design-patterns.com/assets/img/promise-sequence-diagram.866df90e.png)

## [Programmatic Example of Promise Pattern in Java](https://java-design-patterns.com/patterns/promise/#programmatic-example-of-promise-pattern-in-java)

The Promise design pattern is a software design pattern that's often used in concurrent programming to handle asynchronous operations. It represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

In the provided example, a Promise is used to download files and perform operations like line counting and character frequency analysis asynchronously, showcasing the pattern's utility in practical applications.

```java
@Slf4j
public class App {

  private static final String DEFAULT_URL =
      "https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md";
  private final ExecutorService executor;

  private App() {
    // Create a thread pool with 2 threads
    executor = Executors.newFixedThreadPool(2);
  }

  public static void main(String[] args) {
    var app = new App();
    app.promiseUsage();
  }

  private void promiseUsage() {
    calculateLineCount();
    calculateLowestFrequencyChar();
  }

  private void calculateLowestFrequencyChar() {
    // Create a promise to calculate the lowest frequency character
    lowestFrequencyChar().thenAccept(
        charFrequency -> {
          LOGGER.info("Char with lowest frequency is: {}", charFrequency);
        }
    );
  }

  private void calculateLineCount() {
    // Create a promise to calculate the line count
    countLines().thenAccept(
        count -> {
          LOGGER.info("Line count is: {}", count);
        }
    );
  }

  private Promise<Character> lowestFrequencyChar() {
    // Create a promise to calculate the character frequency and then find the lowest frequency character
    return characterFrequency().thenApply(Utility::lowestFrequencyChar);
  }

  private Promise<Map<Character, Long>> characterFrequency() {
    // Create a promise to download a file and then calculate the character frequency
    return download(DEFAULT_URL).thenApply(Utility::characterFrequency);
  }

  private Promise<Integer> countLines() {
    // Create a promise to download a file and then count the lines
    return download(DEFAULT_URL).thenApply(Utility::countLines);
  }

  private Promise<String> download(String urlString) {
    // Create a promise to download a file
    return new Promise<String>()
        .fulfillInAsync(
            () -> Utility.downloadFile(urlString), executor)
        .onError(
            throwable -> {
              LOGGER.error("An error occurred: ", throwable);
            }
        );
  }
}
```

In this code, the `Promise` class is used to create promises for various operations. The `thenApply` method is used to chain promises, meaning that the result of one promise is used as the input for the next promise. The `thenAccept` method is used to handle the result of a promise. The `fulfillInAsync` method is used to fulfill a promise asynchronously, and the `onError` method is used to handle any errors that occur while fulfilling the promise.

Program output:

```
08:19:33.036 [pool-1-thread-2] INFO com.iluwatar.promise.Utility -- Downloading contents from url: https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md
08:19:33.036 [pool-1-thread-1] INFO com.iluwatar.promise.Utility -- Downloading contents from url: https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md
08:19:33.419 [pool-1-thread-2] INFO com.iluwatar.promise.Utility -- File downloaded at: /var/folders/sg/9_st37nn5hq_bfhp8hw2dcrw0000gp/T/promise_pattern12403918065536844551.tmp
08:19:33.419 [pool-1-thread-1] INFO com.iluwatar.promise.Utility -- File downloaded at: /var/folders/sg/9_st37nn5hq_bfhp8hw2dcrw0000gp/T/promise_pattern11215446820862558571.tmp
08:19:33.419 [pool-1-thread-1] INFO com.iluwatar.promise.App -- Line count is: 164
08:19:33.426 [pool-1-thread-2] INFO com.iluwatar.promise.App -- Char with lowest frequency is: ’
```

## [When to Use the Promise Pattern in Java](https://java-design-patterns.com/patterns/promise/#when-to-use-the-promise-pattern-in-java)

- When you need to perform asynchronous tasks and handle their results or errors at a later point.
- In scenarios where tasks can be executed in parallel and their outcomes need to be handled once they are completed.
- Suitable for improving the readability and maintainability of asynchronous code.

## [Promise Pattern Java Tutorials](https://java-design-patterns.com/patterns/promise/#promise-pattern-java-tutorials)

- [Functional-Style Callbacks Using Java 8's CompletableFuture (InfoQ)](https://www.infoq.com/articles/Functional-Style-Callbacks-Using-CompletableFuture)
- [Guide To CompletableFuture (Baeldung)](https://www.baeldung.com/java-completablefuture)
- [You are missing the point to Promises (Domenic Denicola)](https://gist.github.com/domenic/3889970)

## [Real-World Applications of Promise Pattern in Java](https://java-design-patterns.com/patterns/promise/#real-world-applications-of-promise-pattern-in-java)

- Java's CompletableFuture and Future classes.
- JavaScript’s Promise object for managing asynchronous operations.
- Many asynchronous frameworks and libraries such as RxJava and Vert.x.
- [Guava ListenableFuture](https://github.com/google/guava/wiki/ListenableFutureExplained)

## [Benefits and Trade-offs of Promise Pattern](https://java-design-patterns.com/patterns/promise/#benefits-and-trade-offs-of-promise-pattern)

Benefits:

- Improved Readability: Simplifies complex asynchronous code, making it easier to understand and maintain.
- Decoupling: Decouples the code that initiates the asynchronous operation from the code that processes the result.
- Error Handling: Provides a unified way to handle both results and errors from asynchronous operations.

Trade-offs:

- Complexity: Can add complexity to the codebase if overused or misused.
- Debugging: Asynchronous code can be harder to debug compared to synchronous code due to the non-linear flow of execution.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/promise/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Promises can be used in conjunction with the Observer pattern to notify subscribers about the completion of asynchronous operations.
- [Callback](https://java-design-patterns.com/patterns/callback/): Promises often replace callback mechanisms by providing a more structured and readable way to handle asynchronous results.
- [Async Method Invocation](https://java-design-patterns.com/patterns/async-method-invocation/): Promises are often used to handle the results of asynchronous method invocations, allowing for non-blocking execution and result handling.

## [References and Credits](https://java-design-patterns.com/patterns/promise/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://amzn.to/3VhwetF)

---

## [concurrency/reactor] Reactor
> 官方文档: https://java-design-patterns.com/patterns/reactor/

ConcurrencyAsynchronousEvent-drivenFault toleranceMessagingReactiveScalabilitySynchronizationThread managementAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/reactor/#also-known-as)

- Dispatcher
- Notifier

## [Intent of Reactor Design Pattern](https://java-design-patterns.com/patterns/reactor/#intent-of-reactor-design-pattern)

The Reactor pattern is designed to handle concurrent service requests efficiently, using a single or limited number of threads, making it a cornerstone for asynchronous, event-driven systems.

## [Detailed Explanation of Reactor Pattern with Real-World Examples](https://java-design-patterns.com/patterns/reactor/#detailed-explanation-of-reactor-pattern-with-real-world-examples)

Real-world example

> This design pattern is analogous to a head chef in a busy kitchen, demonstrating its ability to manage high-scalability demands and maintain efficient task distribution in multithreaded environments. Instead of each chef handling one order at a time, there is a head chef who acts as the dispatcher. The head chef receives all the orders and decides which chef will handle which part of each order, ensuring that all chefs are utilized efficiently. This way, the kitchen can handle many orders simultaneously, ensuring that dishes are prepared quickly and efficiently without any one chef becoming a bottleneck. This setup is analogous to the Reactor pattern, where the head chef dispatches tasks (events) to various chefs (event handlers) to process multiple tasks concurrently.

In plain words

> The Reactor pattern efficiently handles multiple concurrent service requests by dispatching them to appropriate event handlers using a single or a limited number of threads.

Wikipedia says

> The reactor software design pattern is an event handling strategy that can respond to many potential service requests concurrently. The pattern's key component is an event loop, running in a single thread or process, which demultiplexes incoming requests and dispatches them to the correct request handler.

Sequence diagram

![Reactor Sequence diagram](https://java-design-patterns.com/assets/img/reactor-sequence-diagram.556c2c18.png)

## [Programmatic Example of Reactor Pattern in Java](https://java-design-patterns.com/patterns/reactor/#programmatic-example-of-reactor-pattern-in-java)

The Reactor design pattern is a concurrency model that efficiently handles multiple simultaneous I/O operations using a single or a limited number of threads. It is particularly useful in scenarios where an application needs to handle multiple clients sending service requests concurrently.

In the given code, the Reactor pattern is implemented using Java's NIO (Non-blocking I/O) framework. The key components of this pattern in the code are:

1. **Reactor**: This is the event loop that demultiplexes the incoming requests and dispatches them to the appropriate handlers. In our example, `NioReactor` is the reactor.

2. **Dispatcher**: This is responsible for managing the execution of the tasks that are triggered by the events. In our example, `Dispatcher` is the dispatcher and `ThreadPoolDispatcher` is a concrete implementation of it.

3. **Handles**: These are resources that are managed by the reactor. They are associated with specific events and are used by the reactor to identify the event handlers to which the events should be dispatched. In our example, `AbstractNioChannel` represents a handle.

4. **Event Handlers**: These are associated with specific handles and are responsible for handling the events that occur on those handles. In our example, `ChannelHandler` is an event handler and `LoggingHandler` is a concrete implementation of it.

5. **Synchronous Event Demultiplexer**: This is a system-level component (not shown in the code) that provides a blocking call that waits for events to occur on any of the handles. In our example, this is part of the Java NIO framework.

6. **Concrete Event Handlers**: These are application-specific implementations of the event handlers. In our example, `LoggingHandler` is a concrete event handler.

7. **Initiation Dispatcher**: This is a component that initializes the association between event handlers and handles. In our example, this is done by the `registerChannel` method in the `NioReactor` class.


**Part 1: Creating the Dispatcher**

The first part of our example involves creating a dispatcher. The dispatcher is responsible for managing the execution of the tasks that are triggered by the events.

```java
// Create a dispatcher
Dispatcher dispatcher = new ThreadPoolDispatcher(2);
```

In this snippet, we're creating a `ThreadPoolDispatcher` with 2 threads. This dispatcher will use a thread pool to execute the tasks.

**Part 2: Creating the Reactor**

Next, we create a reactor with the dispatcher. The reactor is the core component of the Reactor pattern. It waits for events on multiple channels registered to it in an event loop and dispatches them to the appropriate handlers.

```java
// Create a reactor with the dispatcher
NioReactor reactor = new NioReactor(dispatcher);
```

Here, we're creating a `NioReactor` and passing the dispatcher we created earlier to its constructor.

**Part 3: Creating the Handler**

Now, we create a handler for handling events. The handler is responsible for processing the events that occur on the channels.

```java
// Create a handler for handling events
ChannelHandler loggingHandler = new LoggingHandler();
```

In this snippet, we're creating a `LoggingHandler`. This handler will log the events that occur on the channels.

**Part 4: Registering Channels with the Reactor**

Next, we register channels with the reactor. These channels are the sources of the events that the reactor will handle.

```java
// Register channels with the reactor
reactor.registerChannel(new NioServerSocketChannel(16666, loggingHandler));
reactor.registerChannel(new NioDatagramChannel(16668, loggingHandler));
```

Here, we're registering a `NioServerSocketChannel` and a `NioDatagramChannel` with the reactor. These channels are associated with the `LoggingHandler` we created earlier.

**Part 5: Starting the Reactor**

Finally, we start the reactor. Once started, the reactor begins to listen for events on the registered channels.

```java
// Start the reactor
reactor.start();
```

In this snippet, we're starting the reactor. From this point on, the reactor will start handling events from the registered channels.

**Part 6: Creating the App Class**

The `App` class is the entry point of our application. It creates the reactor, registers the channels, and starts the reactor.

```java
public class App {

    public static void main(String[] args) {
        // Create a dispatcher
        Dispatcher dispatcher = new ThreadPoolDispatcher(2);

        // Create a reactor with the dispatcher
        NioReactor reactor = new NioReactor(dispatcher);

        // Create a handler for handling events
        ChannelHandler loggingHandler = new LoggingHandler();

        // Register channels with the reactor
        reactor.registerChannel(new NioServerSocketChannel(16666, loggingHandler));
        reactor.registerChannel(new NioDatagramChannel(16668, loggingHandler));

        // Start the reactor
        reactor.start();
    }
}
```

In this snippet, we're creating an instance of the `App` class. Inside the `main` method, we're following the same steps as before: creating a dispatcher, creating a reactor with the dispatcher, creating a handler, registering channels with the reactor, and finally starting the reactor.

This `App` class demonstrates how an application interacts with the reactor. It sets up the necessary components (dispatcher, reactor, handler, channels) and starts the reactor. Once the reactor is started, it will handle events from the registered channels using the specified handler.

Running the code produces the following output:

```
09:50:08.317 [main] INFO com.iluwatar.reactor.framework.NioServerSocketChannel -- Bound TCP socket at port: 16666
09:50:08.320 [main] INFO com.iluwatar.reactor.framework.NioServerSocketChannel -- Bound TCP socket at port: 16667
09:50:08.323 [main] INFO com.iluwatar.reactor.framework.NioDatagramChannel -- Bound UDP socket at port: 16668
09:50:08.324 [main] INFO com.iluwatar.reactor.framework.NioDatagramChannel -- Bound UDP socket at port: 16669
09:50:08.324 [pool-2-thread-1] INFO com.iluwatar.reactor.framework.NioReactor -- Reactor started, waiting for events...
```

This concludes our detailed explanation of the Reactor design pattern. The Reactor pattern allows us to handle multiple simultaneous I/O operations efficiently using a single or a limited number of threads.

## [When to Use the Reactor Pattern in Java](https://java-design-patterns.com/patterns/reactor/#when-to-use-the-reactor-pattern-in-java)

Employ the Reactor pattern in scenarios requiring low-latency and high-throughput in server-side applications, making it an essential strategy for modern networking frameworks and web servers.

## [Real-World Applications of Reactor Pattern in Java](https://java-design-patterns.com/patterns/reactor/#real-world-applications-of-reactor-pattern-in-java)

- Netty: An asynchronous event-driven network application framework for rapid development of maintainable high-performance protocol servers and clients.
- Akka: A toolkit and runtime for building concurrent, distributed, and fault-tolerant applications on the JVM.
- Java NIO (New I/O): Provides non-blocking I/O operations, allowing a single thread to manage multiple channels.

## [Benefits and Trade-offs of Reactor Pattern](https://java-design-patterns.com/patterns/reactor/#benefits-and-trade-offs-of-reactor-pattern)

Benefits:

- Improves application performance by efficiently handling multiple simultaneous connections.
- Reduces resource consumption by using a small number of threads to handle many I/O operations.
- Enhances scalability by allowing applications to serve many clients with minimal threads.

Trade-offs:

- Increased complexity in managing state and event handling.
- Debugging and maintaining asynchronous code can be challenging.
- Potential difficulty in ensuring thread safety and avoiding race conditions.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/reactor/#related-java-design-patterns)

- [Observer](https://java-design-patterns.com/patterns/observer/): Reactor uses the Observer pattern for handling events where event handlers are notified of changes.
- Proactor: Similar to Reactor but handles asynchronous I/O completion rather than readiness.
- [Command](https://java-design-patterns.com/patterns/command/): Encapsulates a request as an object, allowing parameterization and queuing of requests.

## [References and Credits](https://java-design-patterns.com/patterns/reactor/#references-and-credits)

- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)
- [Reactive Programming with RxJava: Creating Asynchronous, Event-Based Applications](https://amzn.to/4dNTLJC)
- [Scalable IO in Java - Doug Lea](http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf)
- [Reactor - An Object Behavioral Pattern for Demultiplexing and Dispatching Handles for Synchronous Events (Douglas C. Schmidt)](https://www.dre.vanderbilt.edu/~schmidt/PDF/Reactor.pdf)

---

## [concurrency/thread-pool-executor] Thread-Pool Executor
> 官方文档: https://java-design-patterns.com/patterns/thread-pool-executor/

ConcurrencyPerformanceResource ManagementConcurrencyMultithreadingScalabilityAbout 4 min

* * *

## [Intent of Thread-Pool Executor Design Pattern](https://java-design-patterns.com/patterns/thread-pool-executor/#intent-of-thread-pool-executor-design-pattern)

The Thread-Pool Executor pattern maintains a pool of worker threads to execute tasks concurrently,

optimizing resource usage by reusing existing threads instead of creating new ones for each task.

## [Detailed Explanation of Thread-Pool Executor Pattern with Real-World Examples](https://java-design-patterns.com/patterns/thread-pool-executor/#detailed-explanation-of-thread-pool-executor-pattern-with-real-world-examples)

### [Real-world example](https://java-design-patterns.com/patterns/thread-pool-executor/#real-world-example)

> Imagine a busy airport security checkpoint where instead of opening a new lane for each traveler,
>
> a fixed number of security lanes (threads) are open to process all passengers. Each security
>
> officer (thread) processes one passenger (task) at a time, and when finished, immediately calls the
>
> next passenger in line. During peak travel times, passengers wait in a queue, but the system is much
>
> more efficient than trying to open a new security lane for each individual traveler. The airport can
>
> handle fluctuating passenger traffic throughout the day with consistent staffing, optimizing both
>
> resource utilization and passenger throughput.

### [In plain words](https://java-design-patterns.com/patterns/thread-pool-executor/#in-plain-words)

> Thread-Pool Executor keeps a set of reusable threads that process multiple tasks throughout their
>
> lifecycle, rather than creating a new thread for each task.

### [Wikipedia says](https://java-design-patterns.com/patterns/thread-pool-executor/#wikipedia-says)

> A thread pool is a software design pattern for achieving concurrency of execution in a computer
>
> program. Often also called a replicated workers or worker-crew model, a thread pool maintains
>
> multiple threads waiting for tasks to be allocated for concurrent execution by the supervising
>
> program.

### [Class diagram](https://java-design-patterns.com/patterns/thread-pool-executor/#class-diagram)

![Thread-pool-executor Class diagram](https://java-design-patterns.com/assets/img/thread-pool-executor.urm.ceb992b3.png)

## [Programmatic Example of Thread-Pool Executor Pattern in Java](https://java-design-patterns.com/patterns/thread-pool-executor/#programmatic-example-of-thread-pool-executor-pattern-in-java)

Imagine a hotel front desk.

The number of employees (thread pool) is limited, but guests (tasks) keep arriving endlessly.

The Thread-Pool Executor pattern efficiently handles a large number of requests by reusing a small

set of threads.

```java
@Slf4j
public class HotelFrontDesk {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // Hire 3 front desk employees (threads)
        ExecutorService frontDesk = Executors.newFixedThreadPool(3);

        LOGGER.info("Hotel front desk operation started!");

        // 7 regular guests checking in (Runnable)
        for (int i = 1; i <= 7; i++) {
            String guestName = "Guest-" + i;
            frontDesk.submit(() -> {
                String employeeName = Thread.currentThread().getName();
                LOGGER.info("{} is checking in {}...", employeeName, guestName);
                try {
                    Thread.sleep(2000); // Simulate check-in time
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                LOGGER.info("{} has been successfully checked in!", guestName);
            });
        }

        // 3 VIP guests checking in (Callable with result)
        Callable<String> vipGuest1 = createVipGuest("VIP-Guest-1");
        Callable<String> vipGuest2 = createVipGuest("VIP-Guest-2");
        Callable<String> vipGuest3 = createVipGuest("VIP-Guest-3");

        Future<String> vipResult1 = frontDesk.submit(vipGuest1);
        Future<String> vipResult2 = frontDesk.submit(vipGuest2);
        Future<String> vipResult3 = frontDesk.submit(vipGuest3);

        // Shutdown after submitting all tasks
        frontDesk.shutdown();

        if (frontDesk.awaitTermination(1, TimeUnit.HOURS)) {
            // Print VIP guests' check-in results
            LOGGER.info("VIP Check-in Results:");
            LOGGER.info(vipResult1.get());
            LOGGER.info(vipResult2.get());
            LOGGER.info(vipResult3.get());
            LOGGER.info("All guests have been successfully checked in. Front desk is now closed.");
        } else {
            LOGGER.info("Check-in timeout. Forcefully shutting down the front desk.");
        }
    }

    private static Callable<String> createVipGuest(String vipGuestName) {
        return () -> {
            String employeeName = Thread.currentThread().getName();
            LOGGER.info("{} is checking in VIP guest {}...", employeeName, vipGuestName);
            Thread.sleep(1000); // VIPs are faster to check in
            return vipGuestName + " has been successfully checked in!";
        };
    }
}
```

Here's the console output:

```markdown
Hotel front desk operation started!
pool-1-thread-3 is checking in Guest-3...
pool-1-thread-2 is checking in Guest-2...
pool-1-thread-1 is checking in Guest-1...
Guest-2 has been successfully checked in!
Guest-1 has been successfully checked in!
Guest-3 has been successfully checked in!
pool-1-thread-2 is checking in Guest-5...
pool-1-thread-3 is checking in Guest-4...
pool-1-thread-1 is checking in Guest-6...
Guest-5 has been successfully checked in!
pool-1-thread-2 is checking in Guest-7...
Guest-4 has been successfully checked in!
pool-1-thread-3 is checking in VIP guest VIP-Guest-1...
Guest-6 has been successfully checked in!
pool-1-thread-1 is checking in VIP guest VIP-Guest-2...
pool-1-thread-3 is checking in VIP guest VIP-Guest-3...
Guest-7 has been successfully checked in!
VIP Check-in Results:
VIP-Guest-1 has been successfully checked in!
VIP-Guest-2 has been successfully checked in!
VIP-Guest-3 has been successfully checked in!
All guests have been successfully checked in. Front desk is now closed.
```

**Note:** Since this example demonstrates asynchronous thread execution, **the actual output may vary between runs**. The order of execution and timing can differ due to thread scheduling, system load, and other factors that affect concurrent processing. The core behavior of the thread pool (limiting concurrent tasks to the number of threads and reusing threads) will remain consistent, but the exact sequence of log messages may change with each execution.

## [When to Use the Thread-Pool Executor Pattern in Java](https://java-design-patterns.com/patterns/thread-pool-executor/#when-to-use-the-thread-pool-executor-pattern-in-java)

- When you need to limit the number of threads running simultaneously to avoid resource exhaustion
- For applications that process a large number of short-lived independent tasks
- To improve performance by reducing thread creation/destruction overhead
- When implementing server applications that handle multiple client requests concurrently
- To execute recurring tasks at fixed rates or with fixed delays

## [Thread-Pool Executor Pattern Java Tutorial](https://java-design-patterns.com/patterns/thread-pool-executor/#thread-pool-executor-pattern-java-tutorial)

- [Thread-Pool Executor Pattern Tutorial (Baeldung)](https://www.baeldung.com/thread-pool-java-and-guava)

## [Real-World Applications of Thread-Pool Executor Pattern in Java](https://java-design-patterns.com/patterns/thread-pool-executor/#real-world-applications-of-thread-pool-executor-pattern-in-java)

- Application servers like Tomcat and Jetty use thread pools to handle HTTP requests
- Database connection pools in JDBC implementations
- Background job processing frameworks like Spring Batch
- Task scheduling systems like Quartz Scheduler
- Java EE's Managed Executor Service for enterprise applications

## [Benefits and Trade-offs of Thread-Pool Executor Pattern](https://java-design-patterns.com/patterns/thread-pool-executor/#benefits-and-trade-offs-of-thread-pool-executor-pattern)

### [Benefits](https://java-design-patterns.com/patterns/thread-pool-executor/#benefits)

- Improves performance by reusing existing threads instead of creating new ones
- Provides better resource management by limiting the number of active threads
- Simplifies thread lifecycle management and cleanup
- Facilitates easy implementation of task prioritization and scheduling
- Enhances application stability by preventing resource exhaustion

### [Trade-offs](https://java-design-patterns.com/patterns/thread-pool-executor/#trade-offs)

- May lead to thread starvation if improperly configured (too few threads)
- Potential for resource underutilization if improperly sized (too many threads)
- Requires careful shutdown handling to prevent task loss or resource leaks

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/thread-pool-executor/#related-java-design-patterns)

- [Master-Worker Pattern](https://java-design-patterns.com/patterns/master-worker/): Tasks between a

master and multiple workers.
- [Producer-Consumer Pattern](https://java-design-patterns.com/patterns/producer-consumer/):

Separates task production and task consumption, typically using a blocking queue.
- [Object Pool Pattern](https://java-design-patterns.com/patterns/object-pool/): Reuses a set of

objects (e.g., threads) instead of creating/destroying them repeatedly.

## [References and Credits](https://java-design-patterns.com/patterns/thread-pool-executor/#references-and-credits)

- [Java Documentation for ThreadPoolExecutor](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ThreadPoolExecutor.html)
- [Java Concurrency in Practice](https://jcip.net/) by Brian Goetz
- [Effective Java](https://www.oreilly.com/library/view/effective-java-3rd/9780134686097/) by Joshua

Bloch

---

## [concurrency/thread-specific-storage] Thread-Specific Storage
> 官方文档: https://java-design-patterns.com/patterns/thread-specific-storage/

ConcurrencyConcurrencyMultithreadingThread SafetyData IsolationMemory ManagementAbout 4 min

* * *

## [Intent of Thread-Specific Storage Design Pattern](https://java-design-patterns.com/patterns/thread-specific-storage/#intent-of-thread-specific-storage-design-pattern)

The Thread-Specific Storage pattern ensures that each thread has its own isolated instance of shared data,

preventing concurrency issues by eliminating the need for synchronization. It achieves this by using

ThreadLocal variables to store data that is specific to each thread.

## [Detailed Explanation of Thread-Specific Storage Pattern with Real-World Examples](https://java-design-patterns.com/patterns/thread-specific-storage/#detailed-explanation-of-thread-specific-storage-pattern-with-real-world-examples)

### [Real-world example](https://java-design-patterns.com/patterns/thread-specific-storage/#real-world-example)

> Think of a customer service center where each agent has their own notepad to record information
>
> about the customer they're currently helping. Even if multiple agents are helping customers
>
> simultaneously, each agent's notes are completely separate from the others'. When an agent finishes
>
> with one customer and moves to the next, they start with a fresh notepad. This approach eliminates
>
> the need for agents to coordinate their note-taking, as each agent's notes are private to their
>
> current customer interaction.

### [In plain words](https://java-design-patterns.com/patterns/thread-specific-storage/#in-plain-words)

> Thread-Specific Storage provides each thread with its own private copy of data, isolating thread
>
> interactions and avoiding the need for synchronization mechanisms.

### [Wikipedia says](https://java-design-patterns.com/patterns/thread-specific-storage/#wikipedia-says)

> Thread-local storage (TLS) is a computer programming method that uses static or global memory
>
> local to a thread. TLS is a common technique for avoiding race conditions when multiple threads
>
> need to access the same data. Each thread has its own copy of the data, so there is no need for
>
> synchronization.

### [Class diagram](https://java-design-patterns.com/patterns/thread-specific-storage/#class-diagram)

![Thread-Specific Storage diagram](https://java-design-patterns.com/assets/img/ThreadSpecificStorageUML.cdfb3da4.png)

## [Programmatic Example of Thread-Specific Storage Pattern in Java](https://java-design-patterns.com/patterns/thread-specific-storage/#programmatic-example-of-thread-specific-storage-pattern-in-java)

Imagine a web application that needs to track the current user's context across different stages of request processing.

Each request is handled by a separate thread, and we need to maintain user-specific information without

synchronization overhead.

The Thread-Specific Storage pattern efficiently handles this by providing each thread with its own copy

of the user context data.

```java
@Slf4j
public class APP {
  public static void main(String[] args) {
    // Simulate concurrent requests from multiple users
    for (int i = 1; i <= 5; i++) {
      // Simulate tokens for different users
      String token = "token::" + (i % 3 + 1); // 3 distinct users

      new Thread(() -> {
        // Simulate request processing flow
        RequestHandler handler = new RequestHandler(token);
        handler.process();
      }).start();

      // Slightly stagger request times
      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
```

Here's how the request handler processes each request:

```java
@Slf4j
public class RequestHandler {
  private final String token;

  public RequestHandler(String token) {
    this.token = token;
  }

  public void process() {
    LOGGER.info("Start handling request with token: {}", token);

    try {
      // Step 1: Parse token to get userId
      Long userId = parseToken(token);

      // Step 2: Save userId in ThreadLocal storage
      UserContextProxy.set(new UserContext(userId));

      // Simulate delay between stages of request handling
      Thread.sleep(200);

      // Step 3: Retrieve userId later in the request flow
      Long retrievedId = UserContextProxy.get().getUserId();
      Random random = new Random();
      String accountInfo = retrievedId + "'s account: " + random.nextInt(400);
      LOGGER.info(accountInfo);

    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      // Step 4: Clear ThreadLocal to avoid potential memory leaks
      UserContextProxy.clear();
    }
  }

  // ... parseToken method implementation
}
```

The UserContextProxy acts as a thread-safe accessor to the ThreadLocal storage:

```java
public class UserContextProxy {
  // Underlying TSObjectCollection (ThreadLocalMap) managed by JVM.
  // This ThreadLocal acts as the Key for the map.
  private static final ThreadLocal<UserContext> userContextHolder = new ThreadLocal<>();

  /**
   * Private constructor to prevent instantiation of this utility class.
   */
  private UserContextProxy() {}

  /** Set UserContext for the current thread */
  public static void set(UserContext context) {
    userContextHolder.set(context);
  }

  /** Get UserContext for the current thread */
  public static UserContext get() {
    return userContextHolder.get();
  }

  /** Clear UserContext to prevent potential memory leaks */
  public static void clear() {
    userContextHolder.remove();
  }
}
```

Here's a sample console output:

```
Start handling request with token: token::1
Start handling request with token: token::2
Start handling request with token: token::3
Start handling request with token: token::1
1's account: 234
Start handling request with token: token::2
2's account: 157
3's account: 89
1's account: 342
2's account: 76
```

**Note:** Since this example demonstrates concurrent thread execution, **the actual output may vary between runs**. The order of execution and timing can differ due to thread scheduling, system load, and other factors that affect concurrent processing. However, each thread will correctly maintain its own user context without interference from other threads.

## [When to Use the Thread-Specific Storage Pattern in Java](https://java-design-patterns.com/patterns/thread-specific-storage/#when-to-use-the-thread-specific-storage-pattern-in-java)

- When you need to maintain per-thread state without synchronization overhead
- For applications that process requests in multiple stages and need to share data across those stages
- To avoid concurrency issues when working with non-thread-safe objects like SimpleDateFormat
- When implementing logging or security context that needs to be accessible throughout a request processing
- To maintain thread-specific caches or counters without risk of data corruption

## [Thread-Specific Storage Pattern Java Tutorial](https://java-design-patterns.com/patterns/thread-specific-storage/#thread-specific-storage-pattern-java-tutorial)

- [Thread-Specific Storage Pattern Tutorial (Baeldung)](https://www.baeldung.com/java-threadlocal)

## [Real-World Applications of Thread-Specific Storage Pattern in Java](https://java-design-patterns.com/patterns/thread-specific-storage/#real-world-applications-of-thread-specific-storage-pattern-in-java)

- Servlet containers use ThreadLocal to maintain the current request and response objects
- Spring Framework uses ThreadLocal for managing transaction contexts and security contexts
- Logging frameworks use ThreadLocal to associate log messages with the current thread's context
- Database connection management where each thread needs its own connection or maintains a connection pool per thread
- User session management in web applications where session data is accessed across multiple layers

## [Benefits and Trade-offs of Thread-Specific Storage Pattern](https://java-design-patterns.com/patterns/thread-specific-storage/#benefits-and-trade-offs-of-thread-specific-storage-pattern)

### [Benefits](https://java-design-patterns.com/patterns/thread-specific-storage/#benefits)

- Eliminates the need for synchronization mechanisms, improving performance
- Provides complete isolation of data between threads, preventing concurrency issues
- Simplifies code by removing the need to pass context objects through method parameters
- Enables safe use of non-thread-safe classes in multi-threaded environments
- Reduces object creation overhead by reusing thread-local instances

### [Trade-offs](https://java-design-patterns.com/patterns/thread-specific-storage/#trade-offs)

- Can lead to increased memory consumption as each thread maintains its own copy of data
- Requires careful cleanup to prevent memory leaks, especially in long-running applications
- May complicate debugging as data is not visible across threads
- Can cause issues in environments with thread pooling where threads are reused (data from previous tasks may persist)

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/thread-specific-storage/#related-java-design-patterns)

- [Context Object Pattern](https://java-design-patterns.com/patterns/context-object/): Encapsulates

request-specific information into a context object that can be passed between components.
- [Thread Pool Pattern](https://java-design-patterns.com/patterns/thread-pool-executor/):

Maintains a pool of worker threads to execute tasks concurrently, optimizing resource usage.
- [Singleton Pattern](https://java-design-patterns.com/patterns/singleton/): Ensures a class has only

one instance and provides global access to it, similar to how ThreadLocal provides per-thread access.

## [References and Credits](https://java-design-patterns.com/patterns/thread-specific-storage/#references-and-credits)

- [Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects](https://www.amazon.com/Pattern-Oriented-Software-Architecture-Concurrent-Networked/dp/0471606952)
- [Java Documentation for ThreadLocal](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ThreadLocal.html)
- [Java Concurrency in Practice](https://jcip.net/) by Brian Goetz

---

<!-- ============================================ -->
<!-- Data Access 数据访问模式 (12 个) -->
<!-- ============================================ -->

## [data-access/metadata-mapping] Metadata Mapping
> 官方文档: https://java-design-patterns.com/patterns/metadata-mapping/

Data accessDecouplingEnterprise patternsObject mappingPersistenceAbout 5 min

* * *

## [Intent of Metadata Mapping Design Pattern](https://java-design-patterns.com/patterns/metadata-mapping/#intent-of-metadata-mapping-design-pattern)

Metadata Mapping Design Pattern is designed to manage the mapping between database records and Java objects in a way that keeps the database schema and object model decoupled and manageable.

## [Detailed Explanation of Metadata Mapping Pattern with Real-World Examples](https://java-design-patterns.com/patterns/metadata-mapping/#detailed-explanation-of-metadata-mapping-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Metadata Mapping design pattern can be seen in online retail systems. In such systems, products often have varying attributes depending on their category. For instance, electronics might have attributes like battery life and screen size, while clothing might have attributes like size and fabric type. Using Metadata Mapping, the system can dynamically map these varying attributes to the product objects without modifying the underlying class structure. This flexibility allows for easy updates and management of product attributes as new categories and attributes are introduced, ensuring that the system can evolve with the changing product landscape.

In plain words

> Metadata Mapping specifies the mapping between classes and tables so that we could treat a table of any database like a Java class.

Wikipedia says

> Create a "virtual [object database](https://en.wikipedia.org/wiki/Object_database)" that can be used from within the programming language.

Flowchart

![Metadata Mapping flowchart](https://java-design-patterns.com/assets/img/metadata-mapping-flowchart.0fd86437.png)

## [Programmatic Example of Metadata Mapping Pattern in Java](https://java-design-patterns.com/patterns/metadata-mapping/#programmatic-example-of-metadata-mapping-pattern-in-java)

Hibernate ORM Tool uses Metadata Mapping Pattern to specify the mapping between classes and tables either using XML or annotations in code.

We give an example about visiting the information of `user_account` table in `h2` database. Firstly, we create `user_account` table with `h2`:

```java
@Slf4j
public class DatabaseUtil {
  private static final String DB_URL = "jdbc:h2:mem:metamapping";
  private static final String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS `user_account`;"
      + "CREATE TABLE `user_account` (\n"
      + "  `id` int(11) NOT NULL AUTO_INCREMENT,\n"
      + "  `username` varchar(255) NOT NULL,\n"
      + "  `password` varchar(255) NOT NULL,\n"
      + "  PRIMARY KEY (`id`)\n"
      + ");";

  static {
    LOGGER.info("create h2 database");
    var source = new JdbcDataSource();
    source.setURL(DB_URL);
    try (var statement = source.getConnection().createStatement()) {
      statement.execute(CREATE_SCHEMA_SQL);
    } catch (SQLException e) {
      LOGGER.error("unable to create h2 data source", e);
    }
  }
}
```

Correspondingly, here's the basic `User` entity.

```java
@Setter
@Getter
@ToString
public class User {
  private Integer id;
  private String username;
  private String password;

  public User(String username, String password) {
    this.username = username;
    this.password = password;
  }
}
```

Then we write a `xml` file to show the mapping between the table and the object:

```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="com.iluwatar.metamapping.model.User" table="user_account">
    <id name="id" type="java.lang.Integer" column="id">
      <generator class="native"/>
    </id>
    <property name="username" column="username" type="java.lang.String"/>
    <property name="password" column="password" type="java.lang.String"/>
  </class>
</hibernate-mapping>
```

We use `Hibernate` to resolve the mapping and connect to our database, here's its configuration:

```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!-- JDBC Database connection settings -->
    <property name="connection.url">jdbc:h2:mem:metamapping</property>
    <property name="connection.driver_class">org.h2.Driver</property>
    <!-- JDBC connection pool settings ... using built-in test pool -->
    <property name="connection.pool_size">1</property>
    <!-- Select our SQL dialect -->
    <property name="dialect">org.hibernate.dialect.H2Dialect</property>
    <!-- Echo the SQL to stdout -->
    <property name="show_sql">false</property>
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create-drop</property>
    <mapping resource="com/iluwatar/metamapping/model/User.hbm.xml" />
  </session-factory>
</hibernate-configuration>
```

Then we can get access to the table just like an object with `Hibernate`, here's some CRUDs:

```java
@Slf4j
public class UserService {
  private static final SessionFactory factory = HibernateUtil.getSessionFactory();

  public List<User> listUser() {
    LOGGER.info("list all users.");
    List<User> users = new ArrayList<>();
    try (var session = factory.openSession()) {
      var tx = session.beginTransaction();
      List<User> userIter = session.createQuery("FROM User").list();
      for (var iterator = userIter.iterator(); iterator.hasNext();) {
        users.add(iterator.next());
      }
      tx.commit();
    } catch (HibernateException e) {
      LOGGER.debug("fail to get users", e);
    }
    return users;
  }

  // other CRUDs ->
  // ...

  public void close() {
    HibernateUtil.shutdown();
  }
}
```

Here is our `App` class with `main` function for running the example.

```java
@Slf4j
public class App {

  public static void main(String[] args) {
    // get service
    var userService = new UserService();
    // use create service to add users
    for (var user : generateSampleUsers()) {
      var id = userService.createUser(user);
      LOGGER.info("Add user" + user + "at" + id + ".");
    }
    // use list service to get users
    var users = userService.listUser();
    LOGGER.info(String.valueOf(users));
    // use get service to get a user
    var user = userService.getUser(1);
    LOGGER.info(String.valueOf(user));
    // change password of user 1
    user.setPassword("new123");
    // use update service to update user 1
    userService.updateUser(1, user);
    // use delete service to delete user 2
    userService.deleteUser(2);
    // close service
    userService.close();
  }

  public static List<User> generateSampleUsers() {
    final var user1 = new User("ZhangSan", "zhs123");
    final var user2 = new User("LiSi", "ls123");
    final var user3 = new User("WangWu", "ww123");
    return List.of(user1, user2, user3);
  }
}
```

Console output:

```
14:44:17.792 [main] INFO  org.hibernate.Version - HHH000412: Hibernate ORM core version 5.6.12.Final
14:44:17.977 [main] INFO  o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
14:44:18.216 [main] WARN  o.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
14:44:18.217 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:mem:metamapping]
14:44:18.217 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {}
14:44:18.217 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
14:44:18.219 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 1 (min=1)
14:44:18.276 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
14:44:18.463 [main] INFO  o.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@73a8e994] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
14:44:18.465 [main] INFO  o.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@7affc159] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
14:44:18.470 [main] INFO  o.h.e.t.j.p.i.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
14:44:18.473 [main] INFO  c.i.metamapping.service.UserService - create user: ZhangSan
14:44:18.508 [main] INFO  c.i.metamapping.service.UserService - create user ZhangSan at 1
14:44:18.508 [main] INFO  com.iluwatar.metamapping.App - Add userUser(id=1, username=ZhangSan, password=zhs123)at1.
14:44:18.508 [main] INFO  c.i.metamapping.service.UserService - create user: LiSi
14:44:18.509 [main] INFO  c.i.metamapping.service.UserService - create user LiSi at 2
14:44:18.509 [main] INFO  com.iluwatar.metamapping.App - Add userUser(id=2, username=LiSi, password=ls123)at2.
14:44:18.509 [main] INFO  c.i.metamapping.service.UserService - create user: WangWu
14:44:18.512 [main] INFO  c.i.metamapping.service.UserService - create user WangWu at 3
14:44:18.512 [main] INFO  com.iluwatar.metamapping.App - Add userUser(id=3, username=WangWu, password=ww123)at3.
14:44:18.512 [main] INFO  c.i.metamapping.service.UserService - list all users.
14:44:18.542 [main] INFO  com.iluwatar.metamapping.App - [User(id=1, username=ZhangSan, password=zhs123), User(id=2, username=LiSi, password=ls123), User(id=3, username=WangWu, password=ww123)]
14:44:18.542 [main] INFO  c.i.metamapping.service.UserService - get user at: 1
14:44:18.545 [main] INFO  com.iluwatar.metamapping.App - User(id=1, username=ZhangSan, password=zhs123)
14:44:18.545 [main] INFO  c.i.metamapping.service.UserService - update user at 1
14:44:18.548 [main] INFO  c.i.metamapping.service.UserService - delete user at: 2
14:44:18.550 [main] INFO  o.h.t.s.i.SchemaDropperImpl$DelayedDropActionImpl - HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
14:44:18.550 [main] INFO  o.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@7b5cc918] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
14:44:18.551 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001008: Cleaning up connection pool [jdbc:h2:mem:metamapping]
```

## [When to Use the Metadata Mapping Pattern in Java](https://java-design-patterns.com/patterns/metadata-mapping/#when-to-use-the-metadata-mapping-pattern-in-java)

Use the Metadata Mapping Design Pattern when you need to bridge the gap between an object-oriented domain model and a relational database in Java applications, without hard-coding database queries into the domain logic.

## [Real-World Applications of Metadata Mapping Pattern in Java](https://java-design-patterns.com/patterns/metadata-mapping/#real-world-applications-of-metadata-mapping-pattern-in-java)

- Object-Relational Mapping (ORM) frameworks like Hibernate, JPA, EclipseLink, and MyBatis frequently utilize the Metadata Mapping Design Pattern to map Java objects to database tables.
- Mapping database rows to domain objects in enterprise applications.

## [Benefits and Trade-offs of Metadata Mapping Pattern](https://java-design-patterns.com/patterns/metadata-mapping/#benefits-and-trade-offs-of-metadata-mapping-pattern)

Benefits:

- Decouples object model and database schema, allowing independent evolution.
- Reduces boilerplate code associated with data access.
- Centralizes mapping logic, making changes more manageable.

Trade-offs:

- Adds complexity due to an additional layer of abstraction.
- Can impact performance if not properly optimized.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/metadata-mapping/#related-java-design-patterns)

- [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Metadata Mapping is often used within the broader Data Mapper pattern to facilitate the mapping process.
- Active Record: Differently from Active Record, Metadata Mapping separates the data access logic from the domain entities.
- [Repository](https://java-design-patterns.com/patterns/repository/): Works well with the Repository pattern by abstracting data access further, allowing more complex domain logic to be cleanly separated from data mapping.

## [References and Credits](https://java-design-patterns.com/patterns/metadata-mapping/#references-and-credits)

- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Pro JPA 2: Mastering the Java Persistence API](https://amzn.to/4b7UoMC)

---

## [data-access/optimistic-offline-lock] Optimistic Offline Lock
> 官方文档: https://java-design-patterns.com/patterns/optimistic-offline-lock/

Data accessConcurrencyData accessFault toleranceIsolationPersistenceTransactionsAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/optimistic-offline-lock/#also-known-as)

- Optimistic Concurrency Control

## [Intent of Optimistic Offline Lock Design Pattern](https://java-design-patterns.com/patterns/optimistic-offline-lock/#intent-of-optimistic-offline-lock-design-pattern)

The Optimistic Offline Lock pattern in Java is specifically designed to manage concurrent data modifications without the need for long-duration database locks, thus enhancing system performance and scalability.

## [Detailed Explanation of Optimistic Offline Lock Pattern with Real-World Examples](https://java-design-patterns.com/patterns/optimistic-offline-lock/#detailed-explanation-of-optimistic-offline-lock-pattern-with-real-world-examples)

Real-world example

> Imagine a library with multiple users checking out and returning books. Instead of locking each book while a user is browsing or deciding whether to borrow it, the library uses an optimistic approach. Each book has a timestamp or version number. When a user decides to borrow a book, they check the book's version number. If it matches the current version, the transaction proceeds. If another user has borrowed the book in the meantime, causing a version mismatch, the first user is informed to retry. This approach allows multiple users to browse and attempt to borrow books concurrently, improving the library's efficiency and user satisfaction without locking the entire catalog.

In plain words

> The Optimistic Offline Lock pattern manages concurrent data modifications by allowing transactions to proceed without locks, resolving conflicts only when they occur to enhance performance and scalability.

Wikipedia says

> Optimistic concurrency control (OCC), also known as optimistic locking, is a concurrency control method applied to transactional systems such as relational database management systems and software transactional memory.

Sequence diagram

![Optimistic Offline Lock sequence diagram](https://java-design-patterns.com/assets/img/optimistic-offline-lock-sequence-diagram.90ac1efc.png)

## [Programmatic Example of Optimistic Offline Lock Pattern in Java](https://java-design-patterns.com/patterns/optimistic-offline-lock/#programmatic-example-of-optimistic-offline-lock-pattern-in-java)

In this section, we delve into the practical implementation of the Optimistic Offline Lock in Java. By following these steps, you can ensure that your application handles data conflicts and concurrency with minimal overhead.

The Optimistic Offline Lock pattern is a concurrency control method that allows multiple transactions to proceed without locks, resolving conflicts only when they occur. This pattern is useful in scenarios where the likelihood of conflicting transactions is low and long-duration locks could hamper performance and scalability.

First, we have a `Card` entity that represents a bank card with a sum of money and a version number.

```java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Card {

    private long id;

    private long personId;

    private float sum;

    private int version;
}
```

The `CardUpdateService` class implements the `UpdateService` interface and provides a method `doUpdate` to update the Card entity. The `doUpdate` method first retrieves the current version of the `Card` entity. It then performs some business logic to update the sum of money in the `Card`. Before updating the `Card` in the database, it checks if the version of the `Card` in the database is the same as the initial version it retrieved. If the versions match, it proceeds with the update. If the versions do not match, it means that another transaction has updated the `Card` in the meantime, and it throws an `ApplicationException`.

```java

@RequiredArgsConstructor
public class CardUpdateService implements UpdateService<Card> {

    private final JpaRepository<Card> cardJpaRepository;

    @Override
    @Transactional(rollbackFor = ApplicationException.class) //will roll back transaction in case ApplicationException
    public Card doUpdate(Card card, long cardId) {
        float additionalSum = card.getSum();
        Card cardToUpdate = cardJpaRepository.findById(cardId);
        int initialVersion = cardToUpdate.getVersion();
        float resultSum = cardToUpdate.getSum() + additionalSum;
        cardToUpdate.setSum(resultSum);
        //Maybe more complex business-logic e.g. HTTP-requests and so on

        if (initialVersion != cardJpaRepository.getEntityVersionById(cardId)) {
            String exMessage = String.format("Entity with id %s were updated in another transaction", cardId);
            throw new ApplicationException(exMessage);
        }

        cardJpaRepository.update(cardToUpdate);
        return cardToUpdate;
    }
}
```

In this code snippet, the doUpdate method in the CardUpdateService class is a programmatic example of the Optimistic Offline Lock pattern. It allows the Card entity to be updated without locks and resolves conflicts by checking the version of the Card before the update.

## [When to Use the Optimistic Offline Lock Pattern in Java](https://java-design-patterns.com/patterns/optimistic-offline-lock/#when-to-use-the-optimistic-offline-lock-pattern-in-java)

- When multiple transactions need to access and modify the same data simultaneously without causing data inconsistencies.
- In systems where the likelihood of conflicting transactions is low.
- When you want to avoid long-duration locks that could hamper performance and scalability.

## [Optimistic Offline Lock Pattern Java Tutorials](https://java-design-patterns.com/patterns/optimistic-offline-lock/#optimistic-offline-lock-pattern-java-tutorials)

- [Offline Concurrency Control (Baeldung)](https://www.baeldung.com/cs/offline-concurrency-control)
- [Optimistic Locking in JPA (Baeldung)](https://www.baeldung.com/jpa-optimistic-locking)

## [Real-World Applications of Optimistic Offline Lock Pattern in Java](https://java-design-patterns.com/patterns/optimistic-offline-lock/#real-world-applications-of-optimistic-offline-lock-pattern-in-java)

- Web-based applications with high-read, low-write access patterns.
- Distributed systems where locking resources for long durations is not feasible.
- Java enterprise applications using JPA or Hibernate for data persistence.

## [Benefits and Trade-offs of Optimistic Offline Lock Pattern](https://java-design-patterns.com/patterns/optimistic-offline-lock/#benefits-and-trade-offs-of-optimistic-offline-lock-pattern)

Benefits:

- Reduces the need for locking resources, which improves performance.
- Increases system scalability by allowing more transactions to proceed concurrently.
- Simplifies transaction management by handling conflicts only when they occur.

Trade-offs:

- Requires additional logic (versioning, rollback/retry) to handle conflicts, which can complicate the application code.
- Can lead to more frequent retries of transactions if conflicts are common.
- Not suitable for high-conflict scenarios where frequent data modification collisions occur.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/optimistic-offline-lock/#related-java-design-patterns)

- Pessimistic Offline Lock: Unlike the Optimistic Offline Lock, this pattern uses locks to prevent conflicts by locking the data during the entire transaction. It is useful in high-conflict scenarios.
- [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Helps in managing a set of changes as a single transaction, ensuring data integrity. It can be used in conjunction with Optimistic Offline Lock to handle complex transactions.
- [Version Number](https://java-design-patterns.com/patterns/version-number/): A common technique used in Optimistic Offline Lock to detect conflicts by maintaining a version number for each data entity.

## [References and Credits](https://java-design-patterns.com/patterns/optimistic-offline-lock/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Optimistic Offline Lock (Martin Fowler)](https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html)

---

## [data-access/repository] Repository
> 官方文档: https://java-design-patterns.com/patterns/repository/

Data accessAbstractionData accessDecouplingPersistenceAbout 4 min

* * *

## [Intent of Repository Design Pattern](https://java-design-patterns.com/patterns/repository/#intent-of-repository-design-pattern)

The Repository design pattern acts as a central hub for managing all Java data access logic, abstracting the details of data storage and retrieval from the rest of the application.

## [Detailed Explanation of Repository Pattern with Real-World Examples](https://java-design-patterns.com/patterns/repository/#detailed-explanation-of-repository-pattern-with-real-world-examples)

Real-world example

> Imagine a library system where a librarian acts as the repository. Instead of each library patron searching through the entire library for a book (the data), they go to the librarian (the repository) who knows exactly where each book is located, regardless of whether it's on a shelf, in the storeroom, or borrowed by someone else. The librarian abstracts the complexities of book storage, allowing patrons to request books without needing to understand the storage system. This setup simplifies the process for patrons (clients) and centralizes the management of books (data access logic).

In plain words

> The Repository pattern provides a central place for handling all data access logic, abstracting the complexities of data storage and retrieval from the rest of the application.

[Microsoft documentation](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design) says

> Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.

Sequence diagram

![Repository sequence diagram](https://java-design-patterns.com/assets/img/repository-sequence-diagram.8d9d7cc1.png)

## [Programmatic Example of Repository Pattern in Java](https://java-design-patterns.com/patterns/repository/#programmatic-example-of-repository-pattern-in-java)

Let's first look at the person entity that we need to persist.

```java

@ToString
@EqualsAndHashCode
@Setter
@Getter
@Entity
@NoArgsConstructor
public class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String surname;
    private int age;

    public Person(String name, String surname, int age) {
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}
```

We are using Spring Data to create the `PersonRepository`, so it becomes really simple.

```java
@Repository
public interface PersonRepository extends CrudRepository<Person, Long>, JpaSpecificationExecutor<Person> {
    Person findByName(String name);
}
```

Additionally, we define a helper class `PersonSpecifications` for specification queries.

```java
public class PersonSpecifications {

    public static class AgeBetweenSpec implements Specification<Person> {

        private final int from;
        private final int to;

        public AgeBetweenSpec(int from, int to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.between(root.get("age"), from, to);
        }
    }

    public static class NameEqualSpec implements Specification<Person> {

        public String name;

        public NameEqualSpec(String name) {
            this.name = name;
        }

        public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.equal(root.get("name"), this.name);
        }
    }
}
```

And here's the repository example in action.

```java
  public static void main(String[] args) {

    var context = new ClassPathXmlApplicationContext("applicationContext.xml");
    var repository = context.getBean(PersonRepository.class);

    var peter = new Person("Peter", "Sagan", 17);
    var nasta = new Person("Nasta", "Kuzminova", 25);
    var john = new Person("John", "lawrence", 35);
    var terry = new Person("Terry", "Law", 36);

    // Add new Person records
    repository.save(peter);
    repository.save(nasta);
    repository.save(john);
    repository.save(terry);

    // Count Person records
    LOGGER.info("Count Person records: {}", repository.count());

    // Print all records
    var persons = (List<Person>) repository.findAll();
    persons.stream().map(Person::toString).forEach(LOGGER::info);

    // Update Person
    nasta.setName("Barbora");
    nasta.setSurname("Spotakova");
    repository.save(nasta);

    repository.findById(2L).ifPresent(p -> LOGGER.info("Find by id 2: {}", p));

    // Remove record from Person
    repository.deleteById(2L);

    // count records
    LOGGER.info("Count Person records: {}", repository.count());

    // find by name
    repository
            .findOne(new PersonSpecifications.NameEqualSpec("John"))
            .ifPresent(p -> LOGGER.info("Find by John is {}", p));

    // find by age
    persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));

    LOGGER.info("Find Person with age between 20,40: ");
    persons.stream().map(Person::toString).forEach(LOGGER::info);

    repository.deleteAll();

    context.close();
}
```

Program output:

```
INFO  [2024-05-27 07:00:32,847] com.iluwatar.repository.App: Count Person records: 4
INFO  [2024-05-27 07:00:32,859] com.iluwatar.repository.App: Person(id=1, name=Peter, surname=Sagan, age=17)
INFO  [2024-05-27 07:00:32,859] com.iluwatar.repository.App: Person(id=2, name=Nasta, surname=Kuzminova, age=25)
INFO  [2024-05-27 07:00:32,859] com.iluwatar.repository.App: Person(id=3, name=John, surname=lawrence, age=35)
INFO  [2024-05-27 07:00:32,859] com.iluwatar.repository.App: Person(id=4, name=Terry, surname=Law, age=36)
INFO  [2024-05-27 07:00:32,869] com.iluwatar.repository.App: Find by id 2: Person(id=2, name=Barbora, surname=Spotakova, age=25)
INFO  [2024-05-27 07:00:32,873] com.iluwatar.repository.App: Count Person records: 3
INFO  [2024-05-27 07:00:32,878] com.iluwatar.repository.App: Find by John is Person(id=3, name=John, surname=lawrence, age=35)
INFO  [2024-05-27 07:00:32,881] com.iluwatar.repository.App: Find Person with age between 20,40:
INFO  [2024-05-27 07:00:32,881] com.iluwatar.repository.App: Person(id=3, name=John, surname=lawrence, age=35)
INFO  [2024-05-27 07:00:32,881] com.iluwatar.repository.App: Person(id=4, name=Terry, surname=Law, age=36)
```

## [When to Use the Repository Pattern in Java](https://java-design-patterns.com/patterns/repository/#when-to-use-the-repository-pattern-in-java)

- Apply the Repository pattern when aiming to decouple business logic from data access layers in Java applications, ensuring more flexible and maintainable code.
- Suitable for scenarios where multiple data sources might be used and the business logic should remain unaware of the data source specifics.
- Ideal for testing purposes as it allows the use of mock repositories.

## [Repository Pattern Java Tutorials](https://java-design-patterns.com/patterns/repository/#repository-pattern-java-tutorials)

- [Don’t use DAO, use Repository (Thinking in Objects)](http://thinkinginobjects.com/2012/08/26/dont-use-dao-use-repository/)
- [Advanced Spring Data JPA - Specifications and Querydsl (Spring)](https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/)
- [Repository Pattern Benefits and Spring Implementation (Stack Overflow)](https://stackoverflow.com/questions/40068965/repository-pattern-benefits-and-spring-implementation)
- [Design patterns that I often avoid: Repository pattern (InfoWorld)](https://www.infoworld.com/article/3117713/design-patterns-that-i-often-avoid-repository-pattern.html)

## [Real-World Applications of Repository Pattern in Java](https://java-design-patterns.com/patterns/repository/#real-world-applications-of-repository-pattern-in-java)

- Spring Data JPA exemplifies the Repository pattern by providing a robust repository abstraction layer over JPA implementations, tailored for Java.
- Hibernate: Often used with DAOs that act as repositories for accessing and managing data entities.
- Java EE applications frequently utilize repository patterns to separate business logic from data access code.

## [Benefits and Trade-offs of Repository Pattern](https://java-design-patterns.com/patterns/repository/#benefits-and-trade-offs-of-repository-pattern)

Benefits:

- Improves code maintainability and readability by centralizing data access logic.
- Enhances testability by allowing mock implementations of repositories.
- Promotes loose coupling between business logic and data access layers.

Trade-offs:

- Introduces additional layers of abstraction which might add complexity.
- Potential performance overhead due to the abstraction layer.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/repository/#related-java-design-patterns)

- [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): While Repository handles data access, Data Mapper is responsible for transferring data between objects and a database, maintaining the data integrity.
- [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/): Often used alongside Repository to manage transactions and track changes to the data.

## [References and Credits](https://java-design-patterns.com/patterns/repository/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [data-access/serialized-entity] Serialized Entity
> 官方文档: https://java-design-patterns.com/patterns/serialized-entity/

Data accessData accessData transferPersistenceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/serialized-entity/#also-known-as)

- Object Serialization

## [Intent of Serialized Entity Design Pattern](https://java-design-patterns.com/patterns/serialized-entity/#intent-of-serialized-entity-design-pattern)

The Serialized Entity pattern in Java allows for the object serialization to simplify data transfer and storage. It enables easy conversion of Java objects to and from a serialized format, allowing them to be efficiently stored and transferred.

## [Detailed Explanation of Serialized Entity Pattern with Real-World Examples](https://java-design-patterns.com/patterns/serialized-entity/#detailed-explanation-of-serialized-entity-pattern-with-real-world-examples)

Real-world example

> An example of the Serialized Entity design pattern in the real world can be found in the process of saving and loading game state in video games. When a player decides to save their progress, the current state of the game, including the player's position, inventory, and achievements, is serialized into a file format such as JSON or binary. This file can then be stored on the player's device or on a cloud server. When the player wants to resume their game, the serialized data is deserialized back into the game's objects, allowing the player to continue from where they left off. This mechanism ensures that complex game states can be easily saved and restored, providing a seamless gaming experience.

In plain words

> The Serialized Entity design pattern enables the conversion of Java objects to and from a serialized format for easy storage and transfer.

Wikipedia says

> In computing, serialization is the process of translating a data structure or object state into a format that can be stored (e.g. files in secondary storage devices, data buffers in primary storage devices) or transmitted (e.g. data streams over computer networks) and reconstructed later (possibly in a different computer environment). When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward. Serialization of objects does not include any of their associated methods with which they were previously linked.

Flowchart

![Serialized Entity flowchart](https://java-design-patterns.com/assets/img/serialized-entity-flowchart.90a64587.png)

## [Programmatic Example of Serialized Entity Pattern in Java](https://java-design-patterns.com/patterns/serialized-entity/#programmatic-example-of-serialized-entity-pattern-in-java)

The Serialized Entity design pattern is a way to easily persist Java objects to the database. It uses the `Serializable` interface and the DAO (Data Access Object) pattern. The pattern first uses `Serializable` to convert a Java object into a set of bytes, then it uses the DAO pattern to store this set of bytes as a BLOB (Binary Large OBject) in the database.

First, we have the `Country` class, which is a simple POJO (Plain Old Java Object) that represents the data that will be serialized and stored in the database. Implementing the Java `Serializable` interface is crucial in the Serialized Entity design pattern, which means that the object can be converted to a byte stream and restored from it.

```java
@Getter
@Setter
@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class Country implements Serializable {

    private int code;
    private String name;
    private String continents;
    private String language;
    @Serial
    private static final long serialVersionUID = 7149851;
}
```

Next, we have the `CountryDao` interface, which defines the methods for persisting and retrieving `Country` objects from the database.

```java
public interface CountryDao {
    int insertCountry() throws IOException;
    int selectCountry() throws IOException, ClassNotFoundException;
}
```

The `CountrySchemaSql` class implements the `CountryDao` interface. It uses a `DataSource` to connect to the database and a `Country` object that it will serialize and store in the database.

```java
@Slf4j
public class CountrySchemaSql implements CountryDao {

    public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS WORLD (ID INT PRIMARY KEY, COUNTRY BLOB)";
    public static final String DELETE_SCHEMA_SQL = "DROP TABLE WORLD IF EXISTS";

    private Country country;
    private DataSource dataSource;

    public CountrySchemaSql(Country country, DataSource dataSource) {
        this.country = new Country(
                country.getCode(),
                country.getName(),
                country.getContinents(),
                country.getLanguage()
        );
        this.dataSource = dataSource;
    }

    @Override
    public int insertCountry() throws IOException {
        var sql = "INSERT INTO WORLD (ID, COUNTRY) VALUES (?, ?)";
        try (var connection = dataSource.getConnection();
             var preparedStatement = connection.prepareStatement(sql);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oss = new ObjectOutputStream(baos)) {

            oss.writeObject(country);
            oss.flush();

            preparedStatement.setInt(1, country.getCode());
            preparedStatement.setBlob(2, new ByteArrayInputStream(baos.toByteArray()));
            preparedStatement.execute();
            return country.getCode();
        } catch (SQLException e) {
            LOGGER.info("Exception thrown " + e.getMessage());
        }
        return -1;
    }

    @Override
    public int selectCountry() throws IOException, ClassNotFoundException {
        var sql = "SELECT ID, COUNTRY FROM WORLD WHERE ID = ?";
        try (var connection = dataSource.getConnection();
             var preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, country.getCode());

            try (ResultSet rs = preparedStatement.executeQuery()) {
                if (rs.next()) {
                    Blob countryBlob = rs.getBlob("country");
                    ByteArrayInputStream baos = new ByteArrayInputStream(countryBlob.getBytes(1, (int) countryBlob.length()));
                    ObjectInputStream ois = new ObjectInputStream(baos);
                    country = (Country) ois.readObject();
                    LOGGER.info("Country: " + country);
                }
                return rs.getInt("id");
            }
        } catch (SQLException e) {
            LOGGER.info("Exception thrown " + e.getMessage());
        }
        return -1;
    }
}
```

Finally, in the `App` class, we create `Country` objects and `CountrySchemaSql` objects. We then call the `insertCountry` method to serialize the `Country` objects and store them in the database. We also call the `selectCountry` method to retrieve the serialized `Country` objects from the database and deserialize them back into `Country` objects.

```java
public static void main(String[] args) throws IOException, ClassNotFoundException {
    final var dataSource = createDataSource();

    deleteSchema(dataSource);
    createSchema(dataSource);

    final var China = new Country(86, "China", "Asia", "Chinese");
    final var UnitedArabEmirates = new Country(971, "United Arab Emirates", "Asia", "Arabic");

    final var serializedChina = new CountrySchemaSql(China, dataSource);
    final var serializedUnitedArabEmirates = new CountrySchemaSql(UnitedArabEmirates, dataSource);

    serializedChina.insertCountry();
    serializedUnitedArabEmirates.insertCountry();

    serializedChina.selectCountry();
    serializedUnitedArabEmirates.selectCountry();
}
```

Console output:

```
11:55:32.842 [main] INFO com.iluwatar.serializedentity.CountrySchemaSql -- Country: Country(code=86, name=China, continents=Asia, language=Chinese)
11:55:32.870 [main] INFO com.iluwatar.serializedentity.CountrySchemaSql -- Country: Country(code=971, name=United Arab Emirates, continents=Asia, language=Arabic)
```

This is a basic example of the Serialized Entity design pattern. It shows how to serialize Java objects, store them in a database, and then retrieve and deserialize them.

## [When to Use the Serialized Entity Pattern in Java](https://java-design-patterns.com/patterns/serialized-entity/#when-to-use-the-serialized-entity-pattern-in-java)

- This pattern is especially useful for applications requiring data persistence across various states in Java environments.
- Useful in scenarios where objects need to be shared over a network or saved to a file.

## [Real-World Applications of Serialized Entity Pattern in Java](https://java-design-patterns.com/patterns/serialized-entity/#real-world-applications-of-serialized-entity-pattern-in-java)

- Java's built-in serialization mechanism using `Serializable` interface.
- Storing session data in web applications.
- Caching objects to improve performance.
- Transferring objects in distributed systems using RMI or other RPC mechanisms.

## [Benefits and Trade-offs of Serialized Entity Pattern](https://java-design-patterns.com/patterns/serialized-entity/#benefits-and-trade-offs-of-serialized-entity-pattern)

Benefits:

- Simplifies the process of saving and restoring object state.
- Facilitates object transfer across different parts of a system.
- Reduces boilerplate code for manual serialization and deserialization.

Trade-offs:

- Can introduce security risks if not handled properly (e.g., deserialization attacks).
- Serialized formats may not be easily readable or editable by humans.
- Changes to the class structure may break compatibility with previously serialized data.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/serialized-entity/#related-java-design-patterns)

- [Data Transfer Object (DTO)](https://java-design-patterns.com/patterns/data-transfer-object/): Used to encapsulate data and send it over the network. Often serialized for transmission.
- [Memento](https://java-design-patterns.com/patterns/memento/): Provides a way to capture and restore an object's state, often using serialization.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Proxies can serialize requests to interact with remote objects.

## [References and Credits](https://java-design-patterns.com/patterns/serialized-entity/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)

---

## [data-access/serialized-lob] Serialized LOB
> 官方文档: https://java-design-patterns.com/patterns/serialized-lob/

Data accessData accessData processingPersistenceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/serialized-lob/#also-known-as)

- Serialized Large Object
- Serialized BLOB
- Serialized CLOB

## [Intent of Serialized LOB Design Pattern](https://java-design-patterns.com/patterns/serialized-lob/#intent-of-serialized-lob-design-pattern)

Efficiently manage and store large data objects, such as multimedia files and extensive text strings, using the Serialized LOB pattern in Java, a strategy for robust database optimization.

## [Detailed Explanation of Serialized LOB Pattern with Real-World Examples](https://java-design-patterns.com/patterns/serialized-lob/#detailed-explanation-of-serialized-lob-pattern-with-real-world-examples)

Real-world example

> Imagine a social media platform optimized for performance, where users can upload and seamlessly share multimedia content, leveraging Java's Serialized LOB pattern for enhanced data handling. Instead of storing these large multimedia files on a separate file server, the platform uses the Serialized LOB design pattern to store the files directly in the database. Each uploaded image or video is serialized into a binary large object (BLOB) and stored within the user's record. This approach ensures that the multimedia files are managed within the same transactional context as other user data, providing consistency and simplifying data access and retrieval.

In plain words

> The Serialized LOB design pattern manages the storage of large objects, such as files or multimedia, by serializing and storing them directly within a database.

Flowchart

![Serialized LOB flowchart](https://java-design-patterns.com/assets/img/serialized-lob-flowchart.0c588089.png)

## [Programmatic Example of Serialized LOB Pattern in Java](https://java-design-patterns.com/patterns/serialized-lob/#programmatic-example-of-serialized-lob-pattern-in-java)

The Serialized Large Object (LOB) design pattern is a way to handle large objects in a database. It involves serializing an object graph into a single large object (a BLOB or CLOB, for Binary Large Object or Character Large Object, respectively) and storing it in the database. When the object graph needs to be retrieved, it is read from the database and deserialized back into the original object graph.

Here's a programmatic example of the Serialized LOB design pattern:

```java
public abstract class LobSerializer implements AutoCloseable {
  // ... omitted for brevity
  public abstract Object serialize(Forest toSerialize) throws Exception;
  public abstract Forest deSerialize(Object toDeserialize) throws Exception;
  // ... omitted for brevity
}
```

The `LobSerializer` class is an abstract class that provides the structure for serializing and deserializing objects. It has two abstract methods: `serialize` and `deSerialize`. These methods are implemented by the subclasses `ClobSerializer` and `BlobSerializer`.

```java
public class ClobSerializer extends LobSerializer {
  // ... omitted for brevity
  @Override
  public Object serialize(Forest forest) throws ParserConfigurationException, TransformerException {
    // ... omitted for brevity
  }

  @Override
  public Forest deSerialize(Object toDeserialize)
      throws ParserConfigurationException, IOException, SAXException {
    // ... omitted for brevity
  }
}
```

The `ClobSerializer` class provides an implementation for serializing and deserializing objects into XML strings. The `serialize` method converts a `Forest` object into an XML string, and the `deSerialize` method converts an XML string back into a `Forest` object.

```java
public class BlobSerializer extends LobSerializer {
  // ... omitted for brevity
  @Override
  public Object serialize(Forest toSerialize) throws IOException {
    // ... omitted for brevity
  }

  @Override
  public Forest deSerialize(Object toDeserialize) throws IOException, ClassNotFoundException {
    // ... omitted for brevity
  }
}
```

The `BlobSerializer` class provides an implementation for serializing and deserializing objects into binary data. The `serialize` method converts a `Forest` object into binary data, and the `deSerialize` method converts binary data back into a `Forest` object.

Finally, here is the `App` class with `main` method that can be used to execute the serialization example.

```java
public class App {

  public static final String CLOB = "CLOB";
  private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

  public static void main(String[] args) throws SQLException {
    Forest forest = createForest();
    LobSerializer serializer = createLobSerializer(args);
    executeSerializer(forest, serializer);
  }

  private static LobSerializer createLobSerializer(String[] args) throws SQLException {
    LobSerializer serializer;
    if (args.length > 0 && Objects.equals(args[0], CLOB)) {
      serializer = new ClobSerializer();
    } else {
      serializer = new BlobSerializer();
    }
    return serializer;
  }

  private static Forest createForest() {
    Plant grass = new Plant("Grass", "Herb");
    Plant oak = new Plant("Oak", "Tree");

    Animal zebra = new Animal("Zebra", Set.of(grass), Collections.emptySet());
    Animal buffalo = new Animal("Buffalo", Set.of(grass), Collections.emptySet());
    Animal lion = new Animal("Lion", Collections.emptySet(), Set.of(zebra, buffalo));

    return new Forest("Amazon", Set.of(lion, buffalo, zebra), Set.of(grass, oak));
  }

  private static void executeSerializer(Forest forest, LobSerializer lobSerializer) {
    try (LobSerializer serializer = lobSerializer) {

      Object serialized = serializer.serialize(forest);
      int id = serializer.persistToDb(1, forest.getName(), serialized);

      Object fromDb = serializer.loadFromDb(id, Forest.class.getSimpleName());
      Forest forestFromDb = serializer.deSerialize(fromDb);

      LOGGER.info(forestFromDb.toString());
    } catch (SQLException | IOException | TransformerException | ParserConfigurationException
             | SAXException
             | ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
}
```

Console output:

```
12:01:21.061 [main] INFO com.iluwatar.slob.App --
Forest Name = Amazon
Animals found in the Amazon Forest:

--------------------------

Animal Name = Lion
	Animals Eaten by Lion:

Animal Name = Buffalo

	Plants Eaten by Buffalo:
		Name = Grass,Type = Herb

Animal Name = Zebra

	Plants Eaten by Zebra:
		Name = Grass,Type = Herb

--------------------------

--------------------------

Animal Name = Buffalo

	Plants Eaten by Buffalo:
		Name = Grass,Type = Herb
--------------------------

--------------------------

Animal Name = Zebra

	Plants Eaten by Zebra:
		Name = Grass,Type = Herb
--------------------------

Plants in the Amazon Forest:

--------------------------
Name = Oak,Type = Tree
--------------------------

--------------------------
Name = Grass,Type = Herb
--------------------------
```

## [When to Use the Serialized LOB Pattern in Java](https://java-design-patterns.com/patterns/serialized-lob/#when-to-use-the-serialized-lob-pattern-in-java)

- Use when you need to store large objects in a database and want to optimize data access and storage.
- Ideal for applications that deal with large binary or character data such as multimedia files, logs, or documents.

## [Real-World Applications of Serialized LOB Pattern in Java](https://java-design-patterns.com/patterns/serialized-lob/#real-world-applications-of-serialized-lob-pattern-in-java)

- Storing and retrieving images or multimedia files in a database.
- Managing large text documents or logs in enterprise applications.
- Handling binary data in applications that require efficient data retrieval and storage.

## [Benefits and Trade-offs of Serialized LOB Pattern](https://java-design-patterns.com/patterns/serialized-lob/#benefits-and-trade-offs-of-serialized-lob-pattern)

Benefits:

- Simplifies the handling of large objects by leveraging Java serialization.
- Reduces the need for external file storage systems.
- Ensures consistency by storing LOBs within the same transactional context as other data.

Trade-offs:

- Increases database size due to the storage of serialized data.
- Potential performance overhead during serialization and deserialization.
- Requires careful management of serialization format to maintain backward compatibility.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/serialized-lob/#related-java-design-patterns)

- [DAO (Data Access Object)](https://java-design-patterns.com/patterns/dao/): Often used in conjunction with Serialized LOB to encapsulate data access logic.
- Active Record: Can use Serialized LOB for managing large data within the same record.
- [Repository](https://java-design-patterns.com/patterns/repository/): Uses Serialized LOB to handle complex queries and data manipulation involving large objects.

## [References and Credits](https://java-design-patterns.com/patterns/serialized-lob/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Serialized LOB (Martin Fowler)](https://martinfowler.com/eaaCatalog/serializedLOB.html)

---

## [data-access/sharding] Sharding
> 官方文档: https://java-design-patterns.com/patterns/sharding/

Data accessData accessOptimizationScalabilityAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/sharding/#also-known-as)

- Data Partitioning
- Horizontal Partitioning

## [Intent of Sharding Design Pattern](https://java-design-patterns.com/patterns/sharding/#intent-of-sharding-design-pattern)

Sharding, a pivotal Java design pattern, significantly boosts database scalability and performance through horizontal partitioning.

## [Detailed Explanation of Sharding Pattern with Real-World Examples](https://java-design-patterns.com/patterns/sharding/#detailed-explanation-of-sharding-pattern-with-real-world-examples)

Real-world example

> Consider a large e-commerce website with millions of users and transactions. To handle the immense amount of data and ensure the system remains responsive, the user data is sharded across multiple database servers. For instance, users with IDs ending in 0-4 might be stored on one server, and those ending in 5-9 on another. This distribution allows the system to handle a higher load by parallelizing read and write operations across multiple servers.

In plain words

> Separates the processing logic from the view in web applications to improve maintainability and scalability.

Wikipedia says

> Horizontal partitioning is a database design principle whereby rows of a database table are held separately, rather than being split into columns (which is what normalization and vertical partitioning do, to differing extents). Each partition forms part of a shard, which may in turn be located on a separate database server or physical location.
>
> There are numerous advantages to the horizontal partitioning approach. Since the tables are divided and distributed into multiple servers, the total number of rows in each table in each database is reduced. This reduces index size, which generally improves search performance. A database shard can be placed on separate hardware, and multiple shards can be placed on multiple machines. This enables a distribution of the database over a large number of machines, greatly improving performance. In addition, if the database shard is based on some real-world segmentation of the data (e.g., European customers v. American customers) then it may be possible to infer the appropriate shard membership easily and automatically, and query only the relevant shard.

Flowchart

![Sharding flowchart](https://java-design-patterns.com/assets/img/sharding-flowchart.14aa56fe.png)

## [Programmatic Example of Sharding Pattern in Java](https://java-design-patterns.com/patterns/sharding/#programmatic-example-of-sharding-pattern-in-java)

Sharding is a type of database partitioning that separates very large databases into smaller, faster, more easily managed parts called data shards. The word shard means a small part of a whole. In software architecture, it refers to a horizontal partition in a database or search engine. Each individual partition is referred to as a shard or database shard.

In the given code, we have a `ShardManager` class that manages the shards. It has two subclasses `HashShardManager` and `RangeShardManager` that implement different sharding strategies. The `Shard` class represents a shard that stores data. The `Data` class represents the data to be stored in the shards.

The `ShardManager` is an abstract class that provides the basic structure for managing shards. It has a `storeData` method that stores data in a shard and an `allocateShard` method that determines which shard to store the data in. The `allocateShard` method is abstract and must be implemented by subclasses.

```java
public abstract class ShardManager {
  protected Map<Integer, Shard> shardMap = new HashMap<>();

  public abstract int storeData(Data data);

  protected abstract int allocateShard(Data data);
}
```

The `HashShardManager` is a subclass of `ShardManager` that implements a hash-based sharding strategy. In the `allocateShard` method, it calculates a hash of the data key and uses it to determine the shard to store the data in.

```java
public class HashShardManager extends ShardManager {

  @Override
  protected int allocateShard(Data data) {
    var shardCount = shardMap.size();
    var hash = data.getKey() % shardCount;
    return hash == 0 ? hash + shardCount : hash;
  }
}
```

The `RangeShardManager` is another subclass of `ShardManager` that implements a range-based sharding strategy. In the `allocateShard` method, it uses the data type to determine the shard to store the data in.

```java
public class RangeShardManager extends ShardManager {

  @Override
  protected int allocateShard(Data data) {
    var type = data.getType();
    return switch (type) {
      case TYPE_1 -> 1;
      case TYPE_2 -> 2;
      case TYPE_3 -> 3;
    };
  }
}
```

The `Shard` class represents a shard. It has a `storeData` method that stores data in the shard and a `getDataById` method that retrieves data from the shard by its id.

```java
public class Shard {

  @Getter
  private final int id;

  private final Map<Integer, Data> dataStore;

  public Shard(final int id) {
    this.id = id;
    this.dataStore = new HashMap<>();
  }

  public void storeData(Data data) {
    dataStore.put(data.getKey(), data);
  }

  public Data getDataById(final int id) {
    return dataStore.get(id);
  }
}
```

The `Data` class represents the data to be stored in the shards. It has a key, a value, and a type.

```java
@Getter
@Setter
public class Data {

  private int key;

  private String value;

  private DataType type;

  public Data(final int key, final String value, final DataType type) {
    this.key = key;
    this.value = value;
    this.type = type;
  }

  enum DataType {
    TYPE_1, TYPE_2, TYPE_3
  }
}
```

This is the `main` function of the example demonstrating three different sharding strategies: lookup, range, and hash. Each strategy determines which shard to store the data in a different way. The lookup strategy uses a lookup table, the range strategy uses the data type, and the hash strategy uses a hash of the data key.

```java
public static void main(String[] args) {

    var data1 = new Data(1, "data1", Data.DataType.TYPE_1);
    var data2 = new Data(2, "data2", Data.DataType.TYPE_2);
    var data3 = new Data(3, "data3", Data.DataType.TYPE_3);
    var data4 = new Data(4, "data4", Data.DataType.TYPE_1);

    var shard1 = new Shard(1);
    var shard2 = new Shard(2);
    var shard3 = new Shard(3);

    var manager = new LookupShardManager();
    manager.addNewShard(shard1);
    manager.addNewShard(shard2);
    manager.addNewShard(shard3);
    manager.storeData(data1);
    manager.storeData(data2);
    manager.storeData(data3);
    manager.storeData(data4);

    shard1.clearData();
    shard2.clearData();
    shard3.clearData();

    var rangeShardManager = new RangeShardManager();
    rangeShardManager.addNewShard(shard1);
    rangeShardManager.addNewShard(shard2);
    rangeShardManager.addNewShard(shard3);
    rangeShardManager.storeData(data1);
    rangeShardManager.storeData(data2);
    rangeShardManager.storeData(data3);
    rangeShardManager.storeData(data4);

    shard1.clearData();
    shard2.clearData();
    shard3.clearData();

    var hashShardManager = new HashShardManager();
    hashShardManager.addNewShard(shard1);
    hashShardManager.addNewShard(shard2);
    hashShardManager.addNewShard(shard3);
    hashShardManager.storeData(data1);
    hashShardManager.storeData(data2);
    hashShardManager.storeData(data3);
    hashShardManager.storeData(data4);

    shard1.clearData();
    shard2.clearData();
    shard3.clearData();
}
```

Finally, here is the program output:

```
18:32:26.503 [main] INFO com.iluwatar.sharding.LookupShardManager -- Data {key=1, value='data1', type=TYPE_1} is stored in Shard 2
18:32:26.505 [main] INFO com.iluwatar.sharding.LookupShardManager -- Data {key=2, value='data2', type=TYPE_2} is stored in Shard 2
18:32:26.505 [main] INFO com.iluwatar.sharding.LookupShardManager -- Data {key=3, value='data3', type=TYPE_3} is stored in Shard 1
18:32:26.505 [main] INFO com.iluwatar.sharding.LookupShardManager -- Data {key=4, value='data4', type=TYPE_1} is stored in Shard 1
18:32:26.506 [main] INFO com.iluwatar.sharding.RangeShardManager -- Data {key=1, value='data1', type=TYPE_1} is stored in Shard 1
18:32:26.506 [main] INFO com.iluwatar.sharding.RangeShardManager -- Data {key=2, value='data2', type=TYPE_2} is stored in Shard 2
18:32:26.506 [main] INFO com.iluwatar.sharding.RangeShardManager -- Data {key=3, value='data3', type=TYPE_3} is stored in Shard 3
18:32:26.506 [main] INFO com.iluwatar.sharding.RangeShardManager -- Data {key=4, value='data4', type=TYPE_1} is stored in Shard 1
18:32:26.506 [main] INFO com.iluwatar.sharding.HashShardManager -- Data {key=1, value='data1', type=TYPE_1} is stored in Shard 1
18:32:26.506 [main] INFO com.iluwatar.sharding.HashShardManager -- Data {key=2, value='data2', type=TYPE_2} is stored in Shard 2
18:32:26.506 [main] INFO com.iluwatar.sharding.HashShardManager -- Data {key=3, value='data3', type=TYPE_3} is stored in Shard 3
18:32:26.506 [main] INFO com.iluwatar.sharding.HashShardManager -- Data {key=4, value='data4', type=TYPE_1} is stored in Shard 1
```

## [When to Use the Sharding Pattern in Java](https://java-design-patterns.com/patterns/sharding/#when-to-use-the-sharding-pattern-in-java)

- Use when dealing with large datasets that exceed the capacity of a single database.
- Ideal for Java applications requiring robust scalability, sharding improves performance by distributing database loads effectively.
- Useful for applications requiring high availability and fault tolerance.
- Effective in environments where read and write operations can be parallelized across shards.

## [Real-World Applications of Sharding Pattern in Java](https://java-design-patterns.com/patterns/sharding/#real-world-applications-of-sharding-pattern-in-java)

- Distributed databases such as Apache Cassandra, MongoDB, and Amazon DynamoDB.
- Large-scale web applications like social networks, e-commerce platforms, and SaaS products.

## [Benefits and Trade-offs of Sharding Pattern](https://java-design-patterns.com/patterns/sharding/#benefits-and-trade-offs-of-sharding-pattern)

Benefits:

- Enhances performance by distributing load.
- Improves scalability by allowing horizontal scaling.
- Increases availability and fault tolerance by isolating failures to individual shards.

Trade-offs:

- Complexity in managing and maintaining multiple shards.
- Potential challenges in rebalancing shards as data grows.
- Increased latency for cross-shard queries.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/sharding/#related-java-design-patterns)

- [Caching](https://java-design-patterns.com/patterns/caching/): Can be used in conjunction with sharding to further improve performance.
- [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Helps in abstracting and encapsulating the details of database interactions, which can be complex in a sharded environment.
- [Repository](https://java-design-patterns.com/patterns/repository/): Provides a way to manage data access logic centrally, which is useful when dealing with multiple shards.
- [Service Locator](https://java-design-patterns.com/patterns/service-locator/): Can be used to find and interact with different shards in a distributed system.

## [References and Credits](https://java-design-patterns.com/patterns/sharding/#references-and-credits)

- [Building Scalable Web Sites: Building, Scaling, and Optimizing the Next Generation of Web Applications](https://amzn.to/4bqpejJ)
- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z)
- [NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence](https://amzn.to/3UWvdpw)
- [Sharding pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/sharding)

---

## [data-access/single-table-inheritance] Single Table Inheritance
> 官方文档: https://java-design-patterns.com/patterns/single-table-inheritance/

Data accessData accessEncapsulationPersistencePolymorphismAbout 6 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/single-table-inheritance/#also-known-as)

- Class Table Inheritance
- STI

## [Intent of Single Table Inheritance Design Pattern](https://java-design-patterns.com/patterns/single-table-inheritance/#intent-of-single-table-inheritance-design-pattern)

Single Table Inheritance pattern simplifies database schema in Java applications.

Streamline the storage of an inheritance hierarchy in a single database table, where rows represent objects of different classes and columns represent the union of all attributes.

## [Detailed Explanation of Single Table Inheritance Pattern with Real-World Examples](https://java-design-patterns.com/patterns/single-table-inheritance/#detailed-explanation-of-single-table-inheritance-pattern-with-real-world-examples)

Real-world example

> Imagine a library system where books, magazines, and DVDs are all stored in a single inventory table. This table includes columns for attributes common to all items, such as `Title`, `Author`, `PublicationDate`, and `ItemType`, as well as columns specific to certain types, like `ISBN` for books, `IssueNumber` for magazines, and `Duration` for DVDs. Each row represents an item in the library, with some columns left null depending on the item type. This setup simplifies the database schema by keeping all inventory items in one table, akin to Single Table Inheritance in a database context.

In plain words

> Single Table Inheritance stores an entire class hierarchy in a single database table, using a type discriminator column to distinguish between different subclasses.

Wikipedia says

> Single table inheritance is a way to emulate object-oriented inheritance in a relational database. When mapping from a database table to an object in an object-oriented language, a field in the database identifies what class in the hierarchy the object belongs to. All fields of all the classes are stored in the same table, hence the name "Single Table Inheritance".

Flowchart

![Single Table Inheritance flowchart](https://java-design-patterns.com/assets/img/single-table-inheritance-flowchart.bbe09265.png)

## [Programmatic Example of Single Table Inheritance Pattern in Java](https://java-design-patterns.com/patterns/single-table-inheritance/#programmatic-example-of-single-table-inheritance-pattern-in-java)

Single Table Inheritance is a design pattern that maps an inheritance hierarchy of classes to a single database table. Each row in the table represents an instance of a class in the hierarchy. A special discriminator column is used to identify the class to which each row belongs.

This pattern is useful when classes in an inheritance hierarchy are not significantly different in terms of fields and behavior. It simplifies the database schema and can improve performance by avoiding joins.

Let's see how this pattern is implemented in the provided code.

The base class in our hierarchy is `Vehicle`. This class has common properties that all vehicles share, such as `manufacturer` and `model`.

```java
public abstract class Vehicle {
  private String manufacturer;
  private String model;
  // other common properties...
}
```

We have two subclasses, `PassengerVehicle` and `TransportVehicle`, which extend `Vehicle` and add additional properties.

```java
public abstract class PassengerVehicle extends Vehicle {
  private int noOfPassengers;
  // other properties specific to passenger vehicles...
}

public abstract class TransportVehicle extends Vehicle {
  private int loadCapacity;
  // other properties specific to transport vehicles...
}
```

Finally, we have concrete classes like `Car` and `Truck` that extend `PassengerVehicle` and `TransportVehicle` respectively.

```java
public class Car extends PassengerVehicle {
  private int trunkCapacity;
  // other properties specific to cars...
}

public class Truck extends TransportVehicle {
  private int towingCapacity;
  // other properties specific to trucks...
}
```

In this example, we're using Hibernate as our ORM. We map our class hierarchy to a single table using the `@Entity` and `@Inheritance` annotations.

```java
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Vehicle {
  // properties...
}
```

The `@DiscriminatorColumn` annotation is used to specify the discriminator column in the table. This column will hold the class name for each row.

```java
@DiscriminatorColumn(name = "vehicle_type")
public abstract class Vehicle {
  // properties...
}
```

Each subclass specifies its discriminator value using the `@DiscriminatorValue` annotation.

```java
@DiscriminatorValue("CAR")
public class Car extends PassengerVehicle {
  // properties...
}

@DiscriminatorValue("TRUCK")
public class Truck extends TransportVehicle {
  // properties...
}
```

The `VehicleService` class provides methods for saving and retrieving vehicles. When we save a `Car` or `Truck` object, Hibernate will automatically set the discriminator column to the appropriate value. When we retrieve a vehicle, Hibernate will use the discriminator column to instantiate the correct class.

```java
public class VehicleService {
  public Vehicle saveVehicle(Vehicle vehicle) {
    // save vehicle to database...
  }

  public Vehicle getVehicle(Long id) {
    // retrieve vehicle from database...
  }

  public List<Vehicle> getAllVehicles() {
    // retrieve all vehicles from database...
  }
}
```

Finally, here is the Spring Boot application that runs our example.

```java
@SpringBootApplication
@AllArgsConstructor
public class SingleTableInheritance implements CommandLineRunner {

  //Autowiring the VehicleService class to execute the business logic methods
  private final VehicleService vehicleService;

  public static void main(String[] args) {
    SpringApplication.run(SingleTableInheritance.class, args);
  }

  @Override
  public void run(String... args) {

    Logger log = LoggerFactory.getLogger(SingleTableInheritance.class);

    log.info("Saving Vehicles :- ");

    // Saving Car to DB as a Vehicle
    Vehicle vehicle1 = new Car("Tesla", "Model S", 4, 825);
    Vehicle car1 = vehicleService.saveVehicle(vehicle1);
    log.info("Vehicle 1 saved : {}", car1);

    // Saving Truck to DB as a Vehicle
    Vehicle vehicle2 = new Truck("Ford", "F-150", 3325, 14000);
    Vehicle truck1 = vehicleService.saveVehicle(vehicle2);
    log.info("Vehicle 2 saved : {}\n", truck1);

    log.info("Fetching Vehicles :- ");

    // Fetching the Car from DB
    Car savedCar1 = (Car) vehicleService.getVehicle(vehicle1.getVehicleId());
    log.info("Fetching Car1 from DB : {}", savedCar1);

    // Fetching the Truck from DB
    Truck savedTruck1 = (Truck) vehicleService.getVehicle(vehicle2.getVehicleId());
    log.info("Fetching Truck1 from DB : {}\n", savedTruck1);

    log.info("Fetching All Vehicles :- ");

    // Fetching the Vehicles present in the DB
    List<Vehicle> allVehiclesFromDb = vehicleService.getAllVehicles();
    allVehiclesFromDb.forEach(s -> log.info(s.toString()));
  }
}
```

Console output:

```
2024-05-27T12:29:49.949+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Starting SingleTableInheritance using Java 17.0.4.1 with PID 56372 (/Users/ilkka.seppala/git/java-design-patterns/single-table-inheritance/target/classes started by ilkka.seppala in /Users/ilkka.seppala/git/java-design-patterns)
2024-05-27T12:29:49.951+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : No active profile set, falling back to 1 default profile: "default"
2024-05-27T12:29:50.154+03:00  INFO 56372 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2024-05-27T12:29:50.176+03:00  INFO 56372 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 19 ms. Found 1 JPA repository interface.
2024-05-27T12:29:50.315+03:00  INFO 56372 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2024-05-27T12:29:50.345+03:00  INFO 56372 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.4.4.Final
2024-05-27T12:29:50.360+03:00  INFO 56372 --- [           main] o.h.c.internal.RegionFactoryInitiator    : HHH000026: Second-level cache disabled
2024-05-27T12:29:50.457+03:00  INFO 56372 --- [           main] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer
2024-05-27T12:29:50.468+03:00  INFO 56372 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2024-05-27T12:29:50.541+03:00  INFO 56372 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:sti user=SA
2024-05-27T12:29:50.542+03:00  INFO 56372 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2024-05-27T12:29:50.930+03:00  INFO 56372 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)
2024-05-27T12:29:50.953+03:00  INFO 56372 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2024-05-27T12:29:51.094+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Started SingleTableInheritance in 1.435 seconds (process running for 1.678)
2024-05-27T12:29:51.095+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Saving Vehicles :-
2024-05-27T12:29:51.114+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Vehicle 1 saved : Car{PassengerVehicle(noOfPassengers=4)}
2024-05-27T12:29:51.115+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Vehicle 2 saved : Truck{ TransportVehicle(loadCapacity=3325), towingCapacity=14000}

2024-05-27T12:29:51.115+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Fetching Vehicles :-
2024-05-27T12:29:51.129+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Fetching Car1 from DB : Car{PassengerVehicle(noOfPassengers=0)}
2024-05-27T12:29:51.130+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Fetching Truck1 from DB : Truck{ TransportVehicle(loadCapacity=0), towingCapacity=14000}

2024-05-27T12:29:51.130+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Fetching All Vehicles :-
2024-05-27T12:29:51.169+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Car{PassengerVehicle(noOfPassengers=0)}
2024-05-27T12:29:51.169+03:00  INFO 56372 --- [           main] com.iluwatar.SingleTableInheritance      : Truck{ TransportVehicle(loadCapacity=0), towingCapacity=14000}
2024-05-27T12:29:51.172+03:00  INFO 56372 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2024-05-27T12:29:51.173+03:00  INFO 56372 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2024-05-27T12:29:51.174+03:00  INFO 56372 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
```

The Single Table Inheritance pattern is a simple and efficient way to map an inheritance hierarchy to a relational database. However, it can lead to sparse tables if subclasses have many unique fields. In such cases, other patterns like Class Table Inheritance or Concrete Table Inheritance might be more appropriate.

## [When to Use the Single Table Inheritance Pattern in Java](https://java-design-patterns.com/patterns/single-table-inheritance/#when-to-use-the-single-table-inheritance-pattern-in-java)

- Use when you have a class hierarchy with subclasses that share a common base class and you want to store all instances of the hierarchy in a single table.
- Ideal for small to medium-sized applications where the simplicity of a single table outweighs the performance cost of null fields for some subclasses.

## [Single Table Inheritance Pattern Tutorials](https://java-design-patterns.com/patterns/single-table-inheritance/#single-table-inheritance-pattern-tutorials)

- [Hibernate Tutorial 18 - Implementing Inheritance - Single Table Strategy (Java Brains)](https://www.youtube.com/watch?v=M5YrLtAHtOo)

## [Real-World Applications of Single Table Inheritance Pattern in Java](https://java-design-patterns.com/patterns/single-table-inheritance/#real-world-applications-of-single-table-inheritance-pattern-in-java)

- Hibernate and JPA implementations in Java applications often use Single Table Inheritance for ORM mapping.
- Rails ActiveRecord supports Single Table Inheritance out of the box.

## [Benefits and Trade-offs of Single Table Inheritance Pattern](https://java-design-patterns.com/patterns/single-table-inheritance/#benefits-and-trade-offs-of-single-table-inheritance-pattern)

Benefits:

Using the Single Table Inheritance pattern in Java ORM

- Simplifies database schema by reducing the number of tables.
- Easier to manage relationships and queries since all data is in one table.

Trade-offs:

- Can lead to sparsely populated tables with many null values.
- May cause performance issues for large hierarchies due to table size and the need to filter by type.
- Changes in the inheritance hierarchy require schema changes.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/single-table-inheritance/#related-java-design-patterns)

- Class Table Inheritance: Uses separate tables for each class in the hierarchy, reducing null values but increasing complexity in joins.
- Concrete Table Inheritance: Each class in the hierarchy has its own table, reducing redundancy but increasing the number of tables.

## [References and Credits](https://java-design-patterns.com/patterns/single-table-inheritance/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Single Table Inheritance (Martin Fowler)](https://www.martinfowler.com/eaaCatalog/singleTableInheritance.html)

---

## [data-access/table-inheritance] Table Inheritance
> 官方文档: https://java-design-patterns.com/patterns/table-inheritance/

Data accessData accessDatabaseInheritancePersistencePolymorphismAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/table-inheritance/#also-known-as)

- Class Table Inheritance
- Joined Table Inheritance

## [Intent of Table Inheritance Pattern](https://java-design-patterns.com/patterns/table-inheritance/#intent-of-table-inheritance-pattern)

Represent inheritance hierarchies in relational databases by mapping each class in a hierarchy to a database table.

## [Detailed Explanation of Table Inheritance Pattern with Real-World Examples](https://java-design-patterns.com/patterns/table-inheritance/#detailed-explanation-of-table-inheritance-pattern-with-real-world-examples)

Real-world example

> A classic real-world analogy for the Table Inheritance (Joined Table) pattern is managing employee records in an organization:
>
> Imagine a company's database storing information about employees. All employees have common attributes (name, employee ID, hire date), stored in a general "Employee" table. However, the company also has different types of employees: Full-time Employees (with a salary and benefits) and Contractors (hourly rate, contract duration). Each employee type has distinct data stored in separate specialized tables ("FullTimeEmployee" and "Contractor"), which reference the main "Employee" table.
>
> This structure mirrors the Table Inheritance pattern—shared fields in a common table and unique fields split into subclass-specific tables.

In plain words

> The Table Inheritance pattern maps each class within an inheritance hierarchy to its own database table, storing common attributes in a base table and subclass-specific attributes in separate joined tables.

Martin Fowler says

> Relational databases don't support inheritance, which creates a mismatch when mapping objects. To fix this, Table Inheritance uses a separate table for each class in the hierarchy while maintaining relationships through foreign keys, making it easier to link the classes together in the database.

Mind map

![Table Inheritance Pattern Mind Map](https://java-design-patterns.com/assets/img/table-inheritance-mind-map.43e55367.png)

## [Programmatic Example of Table Inheritance Pattern in Java](https://java-design-patterns.com/patterns/table-inheritance/#programmatic-example-of-table-inheritance-pattern-in-java)

The `Vehicle` class will be the superclass, and we will have subclasses `Car` and `Truck` that extend `Vehicle`. The superclass `Vehicle` stores common attributes, while subclasses store their own specific attributes.

### [Key Aspects of the Pattern:](https://java-design-patterns.com/patterns/table-inheritance/#key-aspects-of-the-pattern)

**Superclass (`Vehicle`):**

The superclass stores shared attributes:

- `make`: Manufacturer of the vehicle.
- `model`: Model of the vehicle.
- `year`: Year of manufacture.
- `id`: Unique identifier for the vehicle.

These common attributes will reside in a dedicated database table (`Vehicle` table).

**Subclasses (`Car` and `Truck`):**

Each subclass adds attributes specific to its type:

- `Car`: `numberOfDoors`, indicating how many doors the car has.
- `Truck`: `payloadCapacity`, representing how much payload the truck can carry.

Each subclass stores these specific attributes in their respective tables (`Car` and `Truck` tables).

**Foreign Key Relationship:**

Each subclass table references the superclass table via a foreign key. The subclass's `id` links to the primary key of the superclass, thus connecting common and subclass-specific data.

### [Java Implementation Using JPA Annotations:](https://java-design-patterns.com/patterns/table-inheritance/#java-implementation-using-jpa-annotations)

```java
@Setter
@Getter
public class Vehicle {

   private String make;
   private String model;
   private int year;
   private int id;

   public Vehicle(int year, String make, String model, int id) {
      this.make = make;
      this.model = model;
      this.year = year;
      this.id = id;
   }

   @Override
   public String toString() {
      return "Vehicle{"
              + "id="
              + id
              + ", make='"
              + make
              + '\''
              + ", model='"
              + model
              + '\''
              + ", year="
              + year
              + '}';
   }
}

@Getter
public class Car extends Vehicle {
   private int numDoors;

   public Car(int year, String make, String model, int numDoors, int id) {
      super(year, make, model, id);
      if (numDoors <= 0) {
         throw new IllegalArgumentException("Number of doors must be positive.");
      }
      this.numDoors = numDoors;
   }

   public void setNumDoors(int doors) {
      if (doors <= 0) {
         throw new IllegalArgumentException("Number of doors must be positive.");
      }
      this.numDoors = doors;
   }

   @Override
   public String toString() {
      return "Car{"
              + "id="
              + getId()
              + ", make='"
              + getMake()
              + '\''
              + ", model='"
              + getModel()
              + '\''
              + ", year="
              + getYear()
              + ", numberOfDoors="
              + getNumDoors()
              + '}';
   }
}

@Getter
public class Truck extends Vehicle {
   private double loadCapacity;

   public Truck(int year, String make, String model, double loadCapacity, int id) {
      super(year, make, model, id);
      if (loadCapacity <= 0) {
         throw new IllegalArgumentException("Load capacity must be positive.");
      }
      this.loadCapacity = loadCapacity;
   }

   public void setLoadCapacity(double capacity) {
      if (capacity <= 0) {
         throw new IllegalArgumentException("Load capacity must be positive.");
      }
      this.loadCapacity = capacity;
   }

   @Override
   public String toString() {
      return "Truck{"
              + "id="
              + getId()
              + ", make='"
              + getMake()
              + '\''
              + ", model='"
              + getModel()
              + '\''
              + ", year="
              + getYear()
              + ", payloadCapacity="
              + getLoadCapacity()
              + '}';
   }
}
```

### [Explanation of the JPA annotations used above:](https://java-design-patterns.com/patterns/table-inheritance/#explanation-of-the-jpa-annotations-used-above)

- `@Entity`: Indicates that the class is a JPA entity mapped to a database table.
- `@Inheritance(strategy = InheritanceType.JOINED)`: Configures joined table inheritance, meaning each class (superclass and subclasses) maps to its own table.
- `@Table(name = "XYZ")`: Explicitly specifies the database table name for clarity.
- `@Id`: Marks the primary key of the entity.
- `@GeneratedValue(strategy = GenerationType.IDENTITY)`: Specifies auto-generation of primary key values by the database.

### [Database Structure Result:](https://java-design-patterns.com/patterns/table-inheritance/#database-structure-result)

Applying this code will result in three database tables structured as follows:

**Vehicle table**

- id
- make
- model
- year

**Car table**

- id (FK to Vehicle)
- numberOfDoors

**Truck table**

- id (FK to Vehicle)
- payloadCapacity

This approach clearly represents the Table Inheritance (Joined Table) pattern, with common attributes centrally managed in the superclass table and subclass-specific attributes cleanly separated in their own tables.

## [When to Use the Table Inheritance Pattern in Java](https://java-design-patterns.com/patterns/table-inheritance/#when-to-use-the-table-inheritance-pattern-in-java)

- When persisting an inheritance hierarchy of Java classes in a relational database.
- Suitable when classes share common attributes but also have distinct fields.
- Beneficial when polymorphic queries across subclasses are frequent.

## [Table Inheritance Pattern Java Tutorials](https://java-design-patterns.com/patterns/table-inheritance/#table-inheritance-pattern-java-tutorials)

- [Software Patterns Lexicon: Class Table Inheritance](https://softwarepatternslexicon.com/patterns-sql/4/4/2/)
- [Martin Fowler: Class Table Inheritance](http://thierryroussel.free.fr/java/books/martinfowler/www.martinfowler.com/isa/classTableInheritance.html)

## [Real-World Applications of Table Inheritance Pattern in Java](https://java-design-patterns.com/patterns/table-inheritance/#real-world-applications-of-table-inheritance-pattern-in-java)

- Hibernate ORM (`@Inheritance(strategy = InheritanceType.JOINED)` in Java)
- EclipseLink (Joined Inheritance strategy in JPA)
- Spring Data JPA applications modeling complex domain hierarchies.

## [Benefits and Trade-offs of Table Inheritance Pattern](https://java-design-patterns.com/patterns/table-inheritance/#benefits-and-trade-offs-of-table-inheritance-pattern)

Benefits:

- Normalized database schema reduces redundancy.
- Clearly models class hierarchies at the database level.
- Easier to implement polymorphic queries due to clear class distinctions.

Trade-offs:

- Increased complexity in database queries involving multiple joins.
- Reduced performance for deep inheritance hierarchies due to costly joins.
- Maintenance overhead increases with the complexity of inheritance structures.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/table-inheritance/#related-java-design-patterns)

- [Single Table Inheritance](https://java-design-patterns.com/patterns/single-table-inheritance/): Alternative strategy mapping an entire class hierarchy into a single database table, useful when fewer joins are preferred at the cost of nullable columns.
- Concrete Table Inheritance – Each subclass has its own standalone table; related in providing an alternate approach to storing inheritance hierarchies.

## [References and Credits](https://java-design-patterns.com/patterns/table-inheritance/#references-and-credits)

- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Object-Relational Mapping (Wikipedia)](https://en.wikipedia.org/wiki/Object-relational_mapping)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Pro JPA 2: Mastering the Java Persistence API](https://amzn.to/4b7UoMC)

---

## [data-access/table-module] Table Module
> 官方文档: https://java-design-patterns.com/patterns/table-module/

Data accessData accessEncapsulationPersistenceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/table-module/#also-known-as)

- Record Set

## [Intent of Table Module Design Pattern](https://java-design-patterns.com/patterns/table-module/#intent-of-table-module-design-pattern)

The Table Module pattern expertly encapsulates database table data access logic in a single, efficient module, ideal for Java applications.

## [Detailed Explanation of Table Module Pattern with Real-World Examples](https://java-design-patterns.com/patterns/table-module/#detailed-explanation-of-table-module-pattern-with-real-world-examples)

Real-world example

> Imagine a library where all books are stored in a large database. The Table Module design pattern can be compared to a librarian who manages a specific section of the library, such as the fiction section. This librarian is responsible for all tasks related to that section: adding new books, updating book information, removing old books, and providing information about the books when requested. Just like the Table Module pattern encapsulates all the database access logic for a particular table, the librarian handles all operations related to the fiction section without exposing the complexities of how books are cataloged, stored, and managed to the library users. This makes it easier for the library users to interact with the fiction section, as they can rely on the librarian to efficiently manage and retrieve books without needing to understand the underlying details.

In plain words

> The Table Module pattern centralizes and encapsulates database access logic for a specific table, simplifying data retrieval and manipulation while hiding database complexities.

Flowchart

![Table Module flowchart](https://java-design-patterns.com/assets/img/table-module-flowchart.4686c10b.png)

## [Programmatic Example of Table Module Pattern in Java](https://java-design-patterns.com/patterns/table-module/#programmatic-example-of-table-module-pattern-in-java)

In the user system example, the domain logic for user login and registration needs to be managed. By using the Table Module pattern, we can create an instance of the `UserTableModule` class to encapsulate and handle all business logic associated with the rows in the user table.

Here is the basic `User` entity.

```java
@Setter
@Getter
@ToString
@EqualsAndHashCode
@AllArgsConstructor
public class User {
  private int id;
  private String username;
  private String password;
}
```

Here is the `UserTableModule` class.

```java
public class UserTableModule {
  private final DataSource dataSource;
  private Connection connection = null;
  private ResultSet resultSet = null;
  private PreparedStatement preparedStatement = null;

  public UserTableModule(final DataSource userDataSource) {
    this.dataSource = userDataSource;
  }

  public int login(final String username, final String password) throws SQLException {
  		// Method implementation
  }

  public int registerUser(final User user) throws SQLException {
  		// Method implementation
  }
}
```

In the class `App`, we use an instance of the `UserTableModule` to handle user login and registration.

```java
@Slf4j
public final class App {

    private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";

    private App() {}

    public static void main(final String[] args) throws SQLException {
        // Create data source and create the user table.
        final var dataSource = createDataSource();
        createSchema(dataSource);
        var userTableModule = new UserTableModule(dataSource);

        // Initialize two users.
        var user1 = new User(1, "123456", "123456");
        var user2 = new User(2, "test", "password");

        // Login and register using the instance of userTableModule.
        userTableModule.registerUser(user1);
        userTableModule.login(user1.getUsername(), user1.getPassword());
        userTableModule.login(user2.getUsername(), user2.getPassword());
        userTableModule.registerUser(user2);
        userTableModule.login(user2.getUsername(), user2.getPassword());

        deleteSchema(dataSource);
    }

    private static void deleteSchema(final DataSource dataSource)
            throws SQLException {
        try (var connection = dataSource.getConnection();
             var statement = connection.createStatement()) {
            statement.execute(UserTableModule.DELETE_SCHEMA_SQL);
        }
    }

    private static void createSchema(final DataSource dataSource)
            throws SQLException {
        try (var connection = dataSource.getConnection();
             var statement = connection.createStatement()) {
            statement.execute(UserTableModule.CREATE_SCHEMA_SQL);
        }
    }

    private static DataSource createDataSource() {
        var dataSource = new JdbcDataSource();
        dataSource.setURL(DB_URL);
        return dataSource;
    }
}
```

In this example, the `UserTableModule` class is responsible for encapsulating all interactions with the users table in the database. This includes the logic for logging in and registering users. The User class represents the user entity with attributes such as `id`, `username`, and `password`.

1. **Initialization**: The `UserTableModule` is initialized with a `DataSource` object which is used to establish a connection to the database.
2. **User Registration**: The `registerUser` method in `UserTableModule` handles the logic for registering a new user into the database.
3. **User Login**: The `login` method manages the logic for authenticating a user based on their username and password.
4. **Application Flow**: The `App` class demonstrates how to use the `UserTableModule` to register and log in users. The data source is created, the schema is set up, and users are registered and logged in with appropriate feedback.

The program output:

```
13:59:36.417 [main] INFO com.iluwatar.tablemodule.UserTableModule -- Register successfully!
13:59:36.426 [main] INFO com.iluwatar.tablemodule.UserTableModule -- Login successfully!
13:59:36.426 [main] INFO com.iluwatar.tablemodule.UserTableModule -- Fail to login!
13:59:36.426 [main] INFO com.iluwatar.tablemodule.UserTableModule -- Register successfully!
13:59:36.427 [main] INFO com.iluwatar.tablemodule.UserTableModule -- Login successfully!
```

This example shows how the Table Module pattern centralizes database operations for the `users` table, making the application more modular and easier to maintain.

## [When to Use the Table Module Pattern in Java](https://java-design-patterns.com/patterns/table-module/#when-to-use-the-table-module-pattern-in-java)

- Use when you need to manage data access logic for a database table in a centralized module.
- Ideal for applications that interact heavily with database tables and require encapsulation of database queries.
- Particularly suitable for dynamic systems, the Table Module pattern ensures scalable database management as your Java application's schema evolves.

## [Table Module Pattern Java Tutorials](https://java-design-patterns.com/patterns/table-module/#table-module-pattern-java-tutorials)

- [Architecture patterns: Domain model and friends (Inviqa)](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends)

## [Real-World Applications of Table Module Pattern in Java](https://java-design-patterns.com/patterns/table-module/#real-world-applications-of-table-module-pattern-in-java)

- In enterprise applications where multiple modules need to interact with the same database tables.
- Web applications that require CRUD operations on database tables.
- Java-based ORM frameworks such as Hibernate or JPA utilize similar concepts for managing data access.

## [Benefits and Trade-offs of Table Module Pattern](https://java-design-patterns.com/patterns/table-module/#benefits-and-trade-offs-of-table-module-pattern)

Benefits:

- Centralizes and encapsulates data access logic, leading to easier maintenance.
- Reduces code duplication by providing a single point of interaction for database tables.
- Enhances code readability and reduces the risk of SQL injection attacks by encapsulating query logic.

Trade-offs:

- May lead to a large module if the table has many operations, potentially reducing readability.
- Can become a bottleneck if not properly optimized, especially in high-load scenarios.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/table-module/#related-java-design-patterns)

- Active Record: Unlike Table Module, Active Record combines data access and domain logic in the same class.
- [Data Access Object (DAO)](https://java-design-patterns.com/patterns/dao/): Provides an abstract interface to some type of database or other persistence mechanism, often used alongside Table Module to separate low-level data access operations from high-level business logic.
- [Data Mapper](https://java-design-patterns.com/patterns/data-mapper/): Separates the in-memory objects from the database, unlike Table Module which directly maps database tables.
- [Domain Model](https://java-design-patterns.com/patterns/domain-model/): Represents the domain logic and behavior, often used in conjunction with Table Module to handle complex business rules and data interactions.
- [Repository](https://java-design-patterns.com/patterns/repository/): Abstracts the data layer, allowing more complex queries, whereas Table Module is usually simpler and table-centric.
- [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/): Organizes business logic by procedures where each procedure handles a single request from the presentation layer, contrasting with the Table Module's data-centric approach.

## [References and Credits](https://java-design-patterns.com/patterns/table-module/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [data-access/transaction-script] Transaction Script
> 官方文档: https://java-design-patterns.com/patterns/transaction-script/

Data accessBusinessData accessDomainPersistenceTransactionsAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/transaction-script/#also-known-as)

- Scripted Transactions

## [Intent of Transaction Script Design Pattern](https://java-design-patterns.com/patterns/transaction-script/#intent-of-transaction-script-design-pattern)

The Transaction Script pattern in Java organizes business logic by procedures where each procedure handles a single request from the presentation.

## [Detailed Explanation of Transaction Script Pattern with Real-World Examples](https://java-design-patterns.com/patterns/transaction-script/#detailed-explanation-of-transaction-script-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Transaction Script design pattern can be seen in a bank teller's daily operations. Imagine a bank where each transaction, such as depositing money, withdrawing cash, or transferring funds between accounts, is handled by a specific script-like procedure. Each procedure takes in the necessary details (e.g., account numbers, amounts) and performs the transaction in a straightforward, step-by-step manner. This ensures that each transaction is processed correctly and independently, without the need for a complex system of rules and interactions. This simple, organized approach allows bank tellers to efficiently manage a variety of transactions throughout the day.

In plain words

> Transaction Script organizes business logic into transactions that the system needs to carry out.

Wikipedia says

> The Transaction Script design pattern is a straightforward way to organize business logic in applications, particularly suitable for scenarios where each request from the presentation layer can be handled by a single procedure. This pattern is often used in simple applications or in systems where rapid development and ease of understanding are crucial. Each transaction script is responsible for a particular task, such as processing an order or calculating a result, and typically interacts directly with the database.

Flowchart

![Transaction Script Pattern Flowchart](https://java-design-patterns.com/assets/img/transaction-script-flowchart.4399260b.png)

## [Programmatic Example of Transaction Script Pattern in Java](https://java-design-patterns.com/patterns/transaction-script/#programmatic-example-of-transaction-script-pattern-in-java)

Our Transaction Script pattern in Java example is about booking hotel rooms.

The `Hotel` class takes care of booking and cancelling room reservations.

```java
@Slf4j
public class Hotel {

  private final HotelDaoImpl hotelDao;

  public Hotel(HotelDaoImpl hotelDao) {
    this.hotelDao = hotelDao;
  }

  public void bookRoom(int roomNumber) throws Exception {

    Optional<Room> room = hotelDao.getById(roomNumber);

    if (room.isEmpty()) {
      throw new Exception("Room number: " + roomNumber + " does not exist");
    } else {
      if (room.get().isBooked()) {
        throw new Exception("Room already booked!");
      } else {
        Room updateRoomBooking = room.get();
        updateRoomBooking.setBooked(true);
        hotelDao.update(updateRoomBooking);
      }
    }
  }

  public void cancelRoomBooking(int roomNumber) throws Exception {

    Optional<Room> room = hotelDao.getById(roomNumber);

    if (room.isEmpty()) {
      throw new Exception("Room number: " + roomNumber + " does not exist");
    } else {
      if (room.get().isBooked()) {
        Room updateRoomBooking = room.get();
        updateRoomBooking.setBooked(false);
        int refundAmount = updateRoomBooking.getPrice();
        hotelDao.update(updateRoomBooking);

        LOGGER.info("Booking cancelled for room number: " + roomNumber);
        LOGGER.info(refundAmount + " is refunded");
      } else {
        throw new Exception("No booking for the room exists");
      }
    }
  }
}
```

The `Hotel` class has two methods, one for booking and cancelling a room respectively. Each one of them handles a single transaction in the system, making `Hotel` implement the Transaction Script pattern.

The `bookRoom` method consolidates all the needed steps like checking if the room is already booked or not, if not booked then books the room and updates the database by using the DAO.

The `cancelRoom` method consolidates steps like checking if the room is booked or not, if booked then calculates the refund amount and updates the database using the DAO.

Here is the `App` class with `main` method for running the example.

```java
public class App {

  private static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
  private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

  public static void main(String[] args) throws Exception {

    final var dataSource = createDataSource();
    deleteSchema(dataSource);
    createSchema(dataSource);
    final var dao = new HotelDaoImpl(dataSource);

    // Add rooms
    addRooms(dao);

    // Print room booking status
    getRoomStatus(dao);

    var hotel = new Hotel(dao);

    // Book rooms
    hotel.bookRoom(1);
    hotel.bookRoom(2);
    hotel.bookRoom(3);
    hotel.bookRoom(4);
    hotel.bookRoom(5);
    hotel.bookRoom(6);

    // Cancel booking for a few rooms
    hotel.cancelRoomBooking(1);
    hotel.cancelRoomBooking(3);
    hotel.cancelRoomBooking(5);

    getRoomStatus(dao);

    deleteSchema(dataSource);
  }

  private static void getRoomStatus(HotelDaoImpl dao) throws Exception {
    try (var customerStream = dao.getAll()) {
      customerStream.forEach((customer) -> LOGGER.info(customer.toString()));
    }
  }

  private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException {
    try (var connection = dataSource.getConnection();
         var statement = connection.createStatement()) {
      statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL);
    }
  }

  private static void createSchema(DataSource dataSource) throws Exception {
    try (var connection = dataSource.getConnection();
         var statement = connection.createStatement()) {
      statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL);
    } catch (Exception e) {
      throw new Exception(e.getMessage(), e);
    }
  }

  private static DataSource createDataSource() {
    var dataSource = new JdbcDataSource();
    dataSource.setUrl(H2_DB_URL);
    return dataSource;
  }

  private static void addRooms(HotelDaoImpl hotelDao) throws Exception {
    for (var room : generateSampleRooms()) {
      hotelDao.add(room);
    }
  }

  private static List<Room> generateSampleRooms() {
    final var room1 = new Room(1, "Single", 50, false);
    final var room2 = new Room(2, "Double", 80, false);
    final var room3 = new Room(3, "Queen", 120, false);
    final var room4 = new Room(4, "King", 150, false);
    final var room5 = new Room(5, "Single", 50, false);
    final var room6 = new Room(6, "Double", 80, false);
    return List.of(room1, room2, room3, room4, room5, room6);
  }
}
```

The `App.java` file has the `main` entry point of the application. It demonstrates the use of the Transaction Script pattern in a hotel management context. Here's a step-by-step breakdown of what happens:

01. A new H2 database data source is created using the `createDataSource()` method. This data source is used to interact with the in-memory H2 database.

02. The existing schema (if any) in the database is deleted using the `deleteSchema(dataSource)` method. This is done to ensure a clean state before the application starts.

03. A new schema is created in the database using the `createSchema(dataSource)` method. The schema includes the necessary tables and relationships for the application.

04. An instance of `HotelDaoImpl` is created, which serves as the Data Access Object (DAO). This object is responsible for handling the database operations related to the hotel rooms.

05. Sample rooms are added to the hotel using the `addRooms(dao)` method. This method generates a list of sample rooms and adds them to the hotel via the DAO.

06. The booking status of all rooms is printed using the `getRoomStatus(dao)` method.

07. An instance of `Hotel` is created with the DAO as a parameter. This object represents the hotel and provides methods to book and cancel room bookings.

08. Several rooms are booked using the `hotel.bookRoom(roomNumber)` method.

09. Some of the bookings are then cancelled using the `hotel.cancelRoomBooking(roomNumber)` method.

10. The booking status of all rooms is printed again to reflect the changes.

11. Finally, the schema in the database is deleted again using the `deleteSchema(dataSource)` method, cleaning up the state of the database.


Console output:

```
14:22:20.050 [main] INFO com.iluwatar.transactionscript.App -- Room(id=1, roomType=Single, price=50, booked=false)
14:22:20.051 [main] INFO com.iluwatar.transactionscript.App -- Room(id=2, roomType=Double, price=80, booked=false)
14:22:20.051 [main] INFO com.iluwatar.transactionscript.App -- Room(id=3, roomType=Queen, price=120, booked=false)
14:22:20.051 [main] INFO com.iluwatar.transactionscript.App -- Room(id=4, roomType=King, price=150, booked=false)
14:22:20.051 [main] INFO com.iluwatar.transactionscript.App -- Room(id=5, roomType=Single, price=50, booked=false)
14:22:20.051 [main] INFO com.iluwatar.transactionscript.App -- Room(id=6, roomType=Double, price=80, booked=false)
14:22:20.058 [main] INFO com.iluwatar.transactionscript.Hotel -- Booking cancelled for room number: 1
14:22:20.058 [main] INFO com.iluwatar.transactionscript.Hotel -- 50 is refunded
14:22:20.059 [main] INFO com.iluwatar.transactionscript.Hotel -- Booking cancelled for room number: 3
14:22:20.059 [main] INFO com.iluwatar.transactionscript.Hotel -- 120 is refunded
14:22:20.059 [main] INFO com.iluwatar.transactionscript.Hotel -- Booking cancelled for room number: 5
14:22:20.059 [main] INFO com.iluwatar.transactionscript.Hotel -- 50 is refunded
14:22:20.060 [main] INFO com.iluwatar.transactionscript.App -- Room(id=1, roomType=Single, price=50, booked=false)
14:22:20.060 [main] INFO com.iluwatar.transactionscript.App -- Room(id=2, roomType=Double, price=80, booked=true)
14:22:20.060 [main] INFO com.iluwatar.transactionscript.App -- Room(id=3, roomType=Queen, price=120, booked=false)
14:22:20.060 [main] INFO com.iluwatar.transactionscript.App -- Room(id=4, roomType=King, price=150, booked=true)
14:22:20.060 [main] INFO com.iluwatar.transactionscript.App -- Room(id=5, roomType=Single, price=50, booked=false)
14:22:20.060 [main] INFO com.iluwatar.transactionscript.App -- Room(id=6, roomType=Double, price=80, booked=true)
```

This pattern is suitable for simple business logic and can be easily understood and maintained.

## [When to Use the Transaction Script Pattern in Java](https://java-design-patterns.com/patterns/transaction-script/#when-to-use-the-transaction-script-pattern-in-java)

- Use when business logic is simple and can be easily organized into individual procedures.
- Suitable for applications with simple transaction requirements or where the logic doesn't justify complex architectures like Domain Model.

## [Transaction Script Pattern Java Tutorials](https://java-design-patterns.com/patterns/transaction-script/#transaction-script-pattern-java-tutorials)

- [Transaction Script Pattern (DZone)](https://dzone.com/articles/transaction-script-pattern#:~:text=Transaction%20Script%20(TS)%20is%20the,need%20big%20architecture%20behind%20them.)
- [Transaction Script (InformIT)](https://www.informit.com/articles/article.aspx?p=1398617)

## [Real-World Applications of Transaction Script Pattern in Java](https://java-design-patterns.com/patterns/transaction-script/#real-world-applications-of-transaction-script-pattern-in-java)

- Early-stage startups and small-scale applications where rapid development is crucial.
- Enterprise applications with well-defined procedures like banking transactions or e-commerce order processing.
- Legacy systems where business logic is already written as scripts.

## [Benefits and Trade-offs of Transaction Script Pattern](https://java-design-patterns.com/patterns/transaction-script/#benefits-and-trade-offs-of-transaction-script-pattern)

Benefits:

- Leveraging the Transaction Script pattern enhances code simplicity and accelerates development cycles, especially in startup environments.
- Simple and straightforward to implement.
- Easy to understand and maintain for straightforward business logic.
- Fast development cycle for small applications.

Trade-offs:

- Can lead to duplicated code if not carefully managed.
- Not suitable for complex business logic; can become unmanageable as the application grows.
- Harder to test in isolation compared to more structured approaches like Domain Model.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/transaction-script/#related-java-design-patterns)

- [Domain Model](https://java-design-patterns.com/patterns/domain-model/): Unlike Transaction Script, Domain Model organizes business logic around the data model and is better suited for complex business rules.
- [Service Layer](https://java-design-patterns.com/patterns/service-layer/): Often used together with Transaction Script to define an application's boundary and encapsulate the business logic.
- [Table Module](https://java-design-patterns.com/patterns/table-module/): Similar to Transaction Script but organizes logic using a single class per table rather than a procedure per request.

## [References and Credits](https://java-design-patterns.com/patterns/transaction-script/#references-and-credits)

- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [data-access/unit-of-work] Unit of Work
> 官方文档: https://java-design-patterns.com/patterns/unit-of-work/

Data accessData accessDecouplingPersistenceTransactionsAbout 4 min

* * *

## [Intent of Unit Of Work Design Pattern](https://java-design-patterns.com/patterns/unit-of-work/#intent-of-unit-of-work-design-pattern)

Learn how the Java Unit of Work pattern expertly manages and maintains a list of objects impacted by business transactions, coordinating database changes and solving concurrency issues effectively.

## [Detailed Explanation of Unit Of Work Pattern with Real-World Examples](https://java-design-patterns.com/patterns/unit-of-work/#detailed-explanation-of-unit-of-work-pattern-with-real-world-examples)

Real-world example

> Consider a library scenario where a librarian meticulously tracks all books borrowed and returned, utilizing the Unit of Work design pattern to update the inventory system efficiently. Instead of updating the library's inventory system every time a single transaction occurs, the librarian keeps a list of all the changes and updates the system once at the end of the day. This approach ensures that all changes are processed together, maintaining the integrity of the inventory and reducing the number of individual updates needed. This is analogous to the Unit of Work pattern in software, where all changes to a set of objects are tracked and committed as a single transaction to maintain consistency and efficiency.

In plain words

> The Unit of Work pattern tracks changes to objects during a transaction and commits all changes as a single unit to ensure consistency and efficiency.

[MartinFowler.com](https://martinfowler.com/eaaCatalog/unitOfWork.html) says

> Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

Flowchart

![Unit of Work Pattern Flowchart](https://java-design-patterns.com/assets/img/unit-of-work-flowchart.1b177982.png)

## [Programmatic Example of Unit of Work Pattern in Java](https://java-design-patterns.com/patterns/unit-of-work/#programmatic-example-of-unit-of-work-pattern-in-java)

Arms dealer has a database containing weapon information. Merchants all over the town are constantly updating this information causing a high load on the database server. To make the load more manageable we apply to Unit of Work pattern to send many small updates in batches.

Here's the `Weapon` entity that is being persisted in the database.

```java
@Getter
@RequiredArgsConstructor
public class Weapon {
    private final Integer id;
    private final String name;
}
```

The essence of the implementation is the `ArmsDealer` implementing the Unit of Work pattern. It maintains a map of database operations (`context`) that need to be done and when `commit` is called it applies them in a single batch.

```java
public interface IUnitOfWork<T> {

  String INSERT = "INSERT";
  String DELETE = "DELETE";
  String MODIFY = "MODIFY";

  void registerNew(T entity);

  void registerModified(T entity);

  void registerDeleted(T entity);

  void commit();
}
```

```java
@Slf4j
@RequiredArgsConstructor
public class ArmsDealer implements IUnitOfWork<Weapon> {

    private final Map<String, List<Weapon>> context;
    private final WeaponDatabase weaponDatabase;

    @Override
    public void registerNew(Weapon weapon) {
        LOGGER.info("Registering {} for insert in context.", weapon.getName());
        register(weapon, UnitActions.INSERT.getActionValue());
    }

    @Override
    public void registerModified(Weapon weapon) {
        LOGGER.info("Registering {} for modify in context.", weapon.getName());
        register(weapon, UnitActions.MODIFY.getActionValue());

    }

    @Override
    public void registerDeleted(Weapon weapon) {
        LOGGER.info("Registering {} for delete in context.", weapon.getName());
        register(weapon, UnitActions.DELETE.getActionValue());
    }

    private void register(Weapon weapon, String operation) {
        var weaponsToOperate = context.get(operation);
        if (weaponsToOperate == null) {
            weaponsToOperate = new ArrayList<>();
        }
        weaponsToOperate.add(weapon);
        context.put(operation, weaponsToOperate);
    }

    @Override
    public void commit() {
        if (context == null || context.isEmpty()) {
            return;
        }
        LOGGER.info("Commit started");
        if (context.containsKey(UnitActions.INSERT.getActionValue())) {
            commitInsert();
        }

        if (context.containsKey(UnitActions.MODIFY.getActionValue())) {
            commitModify();
        }
        if (context.containsKey(UnitActions.DELETE.getActionValue())) {
            commitDelete();
        }
        LOGGER.info("Commit finished.");
    }

    private void commitInsert() {
        var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue());
        for (var weapon : weaponsToBeInserted) {
            LOGGER.info("Inserting a new weapon {} to sales rack.", weapon.getName());
            weaponDatabase.insert(weapon);
        }
    }

    private void commitModify() {
        var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue());
        for (var weapon : modifiedWeapons) {
            LOGGER.info("Scheduling {} for modification work.", weapon.getName());
            weaponDatabase.modify(weapon);
        }
    }

    private void commitDelete() {
        var deletedWeapons = context.get(UnitActions.DELETE.getActionValue());
        for (var weapon : deletedWeapons) {
            LOGGER.info("Scrapping {}.", weapon.getName());
            weaponDatabase.delete(weapon);
        }
    }
}
```

Here is how the whole app is put together.

```java
public static void main(String[] args) {
    // create some weapons
    var enchantedHammer = new Weapon(1, "enchanted hammer");
    var brokenGreatSword = new Weapon(2, "broken great sword");
    var silverTrident = new Weapon(3, "silver trident");

    // create repository
    var weaponRepository = new ArmsDealer(new HashMap<>(),
            new WeaponDatabase());

    // perform operations on the weapons
    weaponRepository.registerNew(enchantedHammer);
    weaponRepository.registerModified(silverTrident);
    weaponRepository.registerDeleted(brokenGreatSword);
    weaponRepository.commit();
}
```

Here is the console output.

```
21:39:21.984 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering enchanted hammer for insert in context.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering silver trident for modify in context.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Registering broken great sword for delete in context.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit started
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Inserting a new weapon enchanted hammer to sales rack.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scheduling silver trident for modification work.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Scrapping broken great sword.
21:39:21.989 [main] INFO com.iluwatar.unitofwork.ArmsDealer - Commit finished.
```

## [When to Use the Unit Of Work Pattern in Java](https://java-design-patterns.com/patterns/unit-of-work/#when-to-use-the-unit-of-work-pattern-in-java)

- The Unit of Work pattern is ideal for managing multiple database operations in Java that must be executed as a single transaction, ensuring data consistency and integrity.
- Ideal in scenarios where changes to the business objects must be tracked and saved in a coordinated manner.
- Useful when working with object-relational mapping (ORM) frameworks in Java such as Hibernate.

## [Unit Of Work Pattern Java Tutorials](https://java-design-patterns.com/patterns/unit-of-work/#unit-of-work-pattern-java-tutorials)

- [Repository and Unit of Work Pattern (Wolfgang Ofner)](https://www.programmingwithwolfgang.com/repository-and-unit-of-work-pattern/)
- [Unit Of Work Design Pattern (Code Project)](https://www.codeproject.com/Articles/581487/Unit-of-Work-Design-Pattern)
- [Unit of Work - a Design Pattern (Mono)](https://mono.software/2017/01/13/unit-of-work-a-design-pattern/)

## [Real-World Applications of Unit of Work Pattern in Java](https://java-design-patterns.com/patterns/unit-of-work/#real-world-applications-of-unit-of-work-pattern-in-java)

- Implementations in Java-based ORM frameworks like Hibernate.
- Enterprise applications where multiple database operations need to be atomic.
- Complex transactional systems where multiple objects are modified and persisted together.

## [Benefits and Trade-offs of Unit Of Work Pattern](https://java-design-patterns.com/patterns/unit-of-work/#benefits-and-trade-offs-of-unit-of-work-pattern)

Benefits:

- Ensures data integrity by managing transactions effectively.
- Reduces the number of database calls by batching them together.
- Simplifies the persistence logic by decoupling transaction management from the business logic.

Trade-offs:

- Can introduce complexity in managing the life cycle of objects within the unit of work.
- Potential performance overhead if not managed properly, especially with large datasets.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/unit-of-work/#related-java-design-patterns)

- [Identity Map](https://java-design-patterns.com/patterns/identity-map/): Helps to ensure that each object is only loaded once per transaction, reducing redundancy and improving performance.
- [Repository](https://java-design-patterns.com/patterns/repository/): Often used in conjunction with Unit of Work to abstract the persistence logic and provide a cleaner way to access data.
- [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/): While different in its procedural approach, it can complement Unit of Work by managing transactional logic at a higher level.

## [References and Credits](https://java-design-patterns.com/patterns/unit-of-work/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3wlDrze)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Unit Of Work (Martin Fowler)](https://martinfowler.com/eaaCatalog/unitOfWork.html)

---

## [data-access/version-number] Version Number
> 官方文档: https://java-design-patterns.com/patterns/version-number/

Data accessCompatibilityData accessPersistenceState trackingVersioningAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/version-number/#also-known-as)

- Entity Versioning
- Versioning

## [Intent of Version Number Design Pattern](https://java-design-patterns.com/patterns/version-number/#intent-of-version-number-design-pattern)

Ensure data consistency and integrity in Java applications by tracking changes with version numbers—a crucial component of concurrent data management.

## [Detailed Explanation of Version Number Pattern with Real-World Examples](https://java-design-patterns.com/patterns/version-number/#detailed-explanation-of-version-number-pattern-with-real-world-examples)

Real-world example

> Consider a library system where multiple librarians can update the details of books simultaneously. Each book entry in the library's database has a version number. When a librarian wants to update a book's details, the system checks the version number of the entry. If the version number matches the current version in the database, the update proceeds, and the version number is incremented. If the version number has changed, it means another librarian has already updated the book details, prompting the system to notify the librarian of the conflict and suggesting a review of the latest changes. This ensures that updates do not overwrite each other unintentionally, maintaining data integrity and consistency.

In plain words

> The Version Number pattern in Java provides robust protection against concurrent updates, ensuring reliable data versioning in distributed systems.

Wikipedia says

> The Version Number pattern is a technique used to manage concurrent access to data in databases and other data stores. It involves associating a version number with each record, which is incremented every time the record is updated. This pattern helps ensure that when multiple users or processes attempt to update the same data simultaneously, conflicts can be detected and resolved.

Flowchart

![Version Number Pattern Flowchart](https://java-design-patterns.com/assets/img/version-number-flowchart.a252b9c4.png)

## [Programmatic Example of Version Number Pattern in Java](https://java-design-patterns.com/patterns/version-number/#programmatic-example-of-version-number-pattern-in-java)

Alice and Bob are working on the book, which stored in the database. Our heroes are making changes simultaneously, and we need some mechanism to prevent them from overwriting each other.

We have a `Book` entity, which is versioned, and has a copy-constructor:

```java
@Getter
@Setter
public class Book {

    private long id;
    private String title = "";
    private String author = "";
    private long version = 0; // version number

    public Book(Book book) {
        this.id = book.id;
        this.title = book.title;
        this.author = book.author;
        this.version = book.version;
    }
}
```

We also have `BookRepository`, which implements concurrency control:

```java
public class BookRepository {

  private final Map<Long, Book> collection = new HashMap<>();

  public void update(Book book) throws BookNotFoundException, VersionMismatchException {
    if (!collection.containsKey(book.getId())) {
      throw new BookNotFoundException("Not found book with id: " + book.getId());
    }

    var latestBook = collection.get(book.getId());
    if (book.getVersion() != latestBook.getVersion()) {
      throw new VersionMismatchException(
        "Tried to update stale version " + book.getVersion()
          + " while actual version is " + latestBook.getVersion()
      );
    }

    // update version, including client representation - modify by reference here
    book.setVersion(book.getVersion() + 1);

    // save book copy to repository
    collection.put(book.getId(), new Book(book));
  }

  public Book get(long bookId) throws BookNotFoundException {
    if (!collection.containsKey(bookId)) {
      throw new BookNotFoundException("Not found book with id: " + bookId);
    }

    // return copy of the book
    return new Book(collection.get(bookId));
  }
}
```

Here's the version number pattern in action:

```java
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) throws
            BookDuplicateException,
            BookNotFoundException,
            VersionMismatchException {
        var bookId = 1;

        var bookRepository = new BookRepository();
        var book = new Book();
        book.setId(bookId);
        bookRepository.add(book); // adding a book with empty title and author
        LOGGER.info("An empty book with version {} was added to repository", book.getVersion());

        // Alice and Bob took the book concurrently
        final var aliceBook = bookRepository.get(bookId);
        final var bobBook = bookRepository.get(bookId);

        aliceBook.setTitle("Kama Sutra"); // Alice has updated book title
        bookRepository.update(aliceBook); // and successfully saved book in database
        LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion());

        // now Bob has the stale version of the book with empty title and version = 0
        // while actual book in database has filled title and version = 1
        bobBook.setAuthor("Vatsyayana Mallanaga"); // Bob updates the author
        try {
            LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion());
            bookRepository.update(bobBook); // Bob tries to save his book to database
        } catch (VersionMismatchException e) {
            // Bob update fails, and book in repository remained untouchable
            LOGGER.info("Exception: {}", e.getMessage());
            // Now Bob should reread actual book from repository, do his changes again and save again
        }
    }
}
```

Program output:

```
14:51:04.119 [main] INFO com.iluwatar.versionnumber.App -- An empty book with version 0 was added to repository
14:51:04.122 [main] INFO com.iluwatar.versionnumber.App -- Alice updates the book with new version 1
14:51:04.122 [main] INFO com.iluwatar.versionnumber.App -- Bob tries to update the book with his version 0
14:51:04.123 [main] INFO com.iluwatar.versionnumber.App -- Exception: Tried to update stale version 0 while actual version is 1
```

## [When to Use the Version Number Pattern in Java](https://java-design-patterns.com/patterns/version-number/#when-to-use-the-version-number-pattern-in-java)

- Use when you need to handle concurrent data modifications in a distributed system.
- Suitable for systems where data consistency and integrity are crucial.
- Ideal for applications using databases that support versioning or row versioning features.

## [Version Number Pattern Java Tutorials](https://java-design-patterns.com/patterns/version-number/#version-number-pattern-java-tutorials)

- [JPA entity versioning (byteslounge.com)](https://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking)
- [Optimistic Locking in JPA (Baeldung)](https://www.baeldung.com/jpa-optimistic-locking)
- [Versioning Entity (java2s.com)](http://www.java2s.com/Tutorial/Java/0355__JPA/VersioningEntity.htm)

## [Real-World Applications of Version Number Pattern in Java](https://java-design-patterns.com/patterns/version-number/#real-world-applications-of-version-number-pattern-in-java)

- Hibernate (Java Persistence API) uses version numbers to implement optimistic locking.
- Microsoft SQL Server and Oracle databases support version-based concurrency control.
- Apache CouchDB and other NoSQL databases implement versioning for conflict resolution.
- [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning)
- [Apache Solr](https://lucene.apache.org/solr/guide/6_6/updating-parts-of-documents.html)

## [Benefits and Trade-offs of Version Number Pattern](https://java-design-patterns.com/patterns/version-number/#benefits-and-trade-offs-of-version-number-pattern)

Benefits:

- Improves data consistency and integrity.
- Reduces the likelihood of lost updates in concurrent environments.
- Provides a mechanism for conflict detection and resolution.

Trade-offs:

- Requires additional logic for version checking and handling conflicts.
- Can lead to increased complexity in database schema and application logic.
- Potential performance overhead due to version checks and conflict resolution.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/version-number/#related-java-design-patterns)

- [Optimistic Offline Lock](https://java-design-patterns.com/patterns/optimistic-offline-lock/): Uses version numbers to detect conflicts rather than preventing them from occurring.
- Pessimistic Offline Lock: An alternative approach to concurrency control where data is locked for updates to prevent conflicts.

## [References and Credits](https://java-design-patterns.com/patterns/version-number/#references-and-credits)

- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z)
- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Java Persistence with Hibernate](https://amzn.to/44tP1ox)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

<!-- ============================================ -->
<!-- Functional 函数式模式 (8 个) -->
<!-- ============================================ -->

## [functional/callback] Callback
> 官方文档: https://java-design-patterns.com/patterns/callback/

FunctionalAsynchronousDecouplingIdiomReactiveAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/callback/#also-known-as)

- Call-After
- Event-Subscription
- Listener

## [Intent of Callback Design Pattern](https://java-design-patterns.com/patterns/callback/#intent-of-callback-design-pattern)

The Java Callback Design Pattern is a piece of executable code passed as an argument to other code, which is expected to call back (execute) the argument at a convenient time.

## [Detailed Explanation of Callback Pattern with Real-World Examples](https://java-design-patterns.com/patterns/callback/#detailed-explanation-of-callback-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Callback design pattern can be found in the restaurant industry. Imagine a situation where you place an order at a busy restaurant. Instead of waiting at the counter for your food to be ready, you provide the cashier with your phone number. Once your order is prepared, the kitchen staff calls or sends a text message to notify you that your meal is ready for pickup.
>
> In this analogy, placing your order is analogous to initiating an asynchronous task. Providing your phone number is akin to passing a callback function. The kitchen preparing your order represents the asynchronous processing, and the notification you receive is the callback being executed, allowing you to retrieve your meal without having to wait idly. This separation of task initiation and task completion is the essence of the Callback design pattern.

In plain words

> Callback is a method passed to an executor which will be called at a defined moment.

Wikipedia says

> In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time.

Sequence diagram

![Callback sequence diagram](https://java-design-patterns.com/assets/img/callback-sequence-diagram.de49447e.png)

## [Programmatic Example of Callback Pattern in Java](https://java-design-patterns.com/patterns/callback/#programmatic-example-of-callback-pattern-in-java)

We need to be notified after the executing task has finished. We pass a callback method for the executor and wait for it to call back on us.

`Callback` is a simple interface with single method.

```java
public interface Callback {

    void call();
}
```

Next we define `Task` that will execute the callback after the task execution has finished.

```java
public abstract class Task {

    final void executeWith(Callback callback) {
        execute();
        Optional.ofNullable(callback).ifPresent(Callback::call);
    }

    public abstract void execute();
}

@Slf4j
public final class SimpleTask extends Task {

    @Override
    public void execute() {
        LOGGER.info("Perform some important activity and after call the callback method.");
    }
}
```

Finally, here's how we execute a task and receive a callback when it's finished.

```java
public static void main(final String[] args) {
    var task = new SimpleTask();
    task.executeWith(() -> LOGGER.info("I'm done now."));
}
```

Program output:

```
17:12:11.680 [main] INFO com.iluwatar.callback.SimpleTask -- Perform some important activity and after call the callback method.
17:12:11.682 [main] INFO com.iluwatar.callback.App -- I'm done now.
```

## [When to Use the Callback Pattern in Java](https://java-design-patterns.com/patterns/callback/#when-to-use-the-callback-pattern-in-java)

Use the Callback pattern when

- Asynchronous event handling in GUI applications or event-driven systems
- Implementing notification mechanisms where certain events need to trigger actions in other components.
- Decoupling modules or components that need to interact without having a direct dependency on each other

## [Real-World Applications of Callback Pattern in Java](https://java-design-patterns.com/patterns/callback/#real-world-applications-of-callback-pattern-in-java)

- GUI frameworks often use callbacks for event handling, such as user interactions (clicks, key presses)
- Node.js heavily relies on callbacks for non-blocking I/O operations
- Frameworks that deal with asynchronous operations, like Promises in JavaScript, use callbacks to handle the resolution or rejection of asynchronous tasks
- [CyclicBarrier](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html#CyclicBarrier%28int,%20java.lang.Runnable%29) constructor can accept a callback that will be triggered every time a barrier is tripped.

## [Benefits and Trade-offs of Callback Pattern](https://java-design-patterns.com/patterns/callback/#benefits-and-trade-offs-of-callback-pattern)

Benefits:

- Decouples the execution logic of an operation from the signaling or notification logic, enhancing modularity and reusability
- Facilitates asynchronous processing, improving the responsiveness and scalability of applications
- Enables a reactive programming model where components can react to events as they occur

Trade-offs:

- Callback hell or pyramid of doom: Deeply nested callbacks can lead to code that is hard to read and maintain
- Inversion of control can lead to harder-to-follow code flow, making debugging more challenging
- Potential issues with error handling, especially in languages or environments where exceptions are used, as errors might need to be propagated through callbacks

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/callback/#related-java-design-patterns)

- [Command](https://java-design-patterns.com/patterns/command/): Callbacks can be implemented as Command objects in scenarios where more flexibility or statefulness is required in the callback operation
- [Observer](https://java-design-patterns.com/patterns/observer/): Callbacks can be seen as a more dynamic and lightweight form of the Observer pattern, with the ability to subscribe and unsubscribe callback functions dynamically
- [Promise](https://java-design-patterns.com/patterns/promise/): In some languages or frameworks, Promises or Futures can be used to handle asynchronous operations more cleanly, often using callbacks for success or failure cases

## [References and Credits](https://java-design-patterns.com/patterns/callback/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Effective Java](https://amzn.to/4cGk2Jz)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)

---

## [functional/collection-pipeline] Collection Pipeline
> 官方文档: https://java-design-patterns.com/patterns/collection-pipeline/

FunctionalFunctional decompositionData processingData transformationReactiveAbout 3 min

* * *

## [Intent of Collection Pipeline Design Pattern](https://java-design-patterns.com/patterns/collection-pipeline/#intent-of-collection-pipeline-design-pattern)

The Collection Pipeline design pattern in Java processes collections of data by chaining operations in a sequence. Utilizing the Java Stream API, it transforms data declaratively, focusing on what should be done rather than how.

## [Detailed Explanation of Collection Pipeline Pattern with Real-World Examples](https://java-design-patterns.com/patterns/collection-pipeline/#detailed-explanation-of-collection-pipeline-pattern-with-real-world-examples)

Real-world example

> Imagine a real-world example of a factory assembly line for manufacturing cars. In this assembly line, each station performs a specific task on the car chassis, such as installing the engine, painting the body, attaching the wheels, and inspecting the final product. Each station takes the output from the previous station and adds its own processing step. This sequence of operations is analogous to the Collection Pipeline design pattern, where each step in the pipeline transforms the data and passes it on to the next step, ensuring an efficient and organized workflow.

In plain words

> The Collection Pipeline pattern in Java involves processing data through a series of operations using the Stream API. Each operation transforms the data in sequence, akin to an assembly line in a factory, promoting functional programming principles.

Wikipedia says

> In software engineering, a pipeline consists of a chain of processing elements (processes, threads, coroutines, functions, etc.), arranged so that the output of each element is the input of the next; the name is by analogy to a physical pipeline. Usually some amount of buffering is provided between consecutive elements. The information that flows in these pipelines is often a stream of records, bytes, or bits, and the elements of a pipeline may be called filters; this is also called the pipe(s) and filters design pattern. Connecting elements into a pipeline is analogous to function composition.

Flowchart

![Collection Pipeline flowchart](https://java-design-patterns.com/assets/img/collection-pipeline-flowchart.8c45285b.png)

## [Programmatic Example of Collection Pipeline Pattern in Java](https://java-design-patterns.com/patterns/collection-pipeline/#programmatic-example-of-collection-pipeline-pattern-in-java)

The Collection Pipeline is a programming pattern where you organize some computation as a sequence of operations which compose by taking a collection as output of one operation and feeding it into the next.

Here's a programmatic example of the Collection Pipeline design pattern:

**Step 1: Filtering**

We start with a list of `Car` objects and we want to filter out those that were manufactured after the year 2000. This is done using the `stream()` method to create a stream from the list, the `filter()` method to filter out the cars we want, and the `collect()` method to collect the results into a new list.

```java
public static List<String> getModelsAfter2000(List<Car> cars){
    return cars.stream()
        .filter(car -> car.getYear() > 2000) // Filter cars manufactured after 2000
        .sorted(comparing(Car::getYear)) // Sort the cars by year
        .map(Car::getModel) // Get the model of each car
        .collect(toList()); // Collect the results into a new list
}
```

**Step 2: Grouping**

Next, we want to group the cars by their category. This is done using the `groupingBy` collector.

```java
public static Map<Category, List<Car>> getGroupingOfCarsByCategory(List<Car> cars){
    return cars.stream()
        .collect(groupingBy(Car::getCategory)); // Group cars by category
}
```

**Step 3: Filtering, Sorting and Transforming**

Finally, we want to filter the cars owned by a person to only include sedans, sort them by date, and then transform the sorted cars into a list of `Car` objects.

```java
public static List<Car> getSedanCarsOwnedSortedByDate(List<Person> persons){
    return persons.stream()
        .flatMap(person -> person.getCars().stream()) // Flatten the list of cars owned by each person
        .filter(car -> Category.SEDAN.equals(car.getCategory())) // Filter to only include sedans
        .sorted(comparing(Car::getDate)) // Sort the cars by date
        .collect(toList()); // Collect the results into a new list
}
```

In each of these methods, the Collection Pipeline pattern is used to perform a series of operations on the collection of cars in a declarative manner, which improves readability and maintainability.

## [When to Use the Collection Pipeline Pattern in Java](https://java-design-patterns.com/patterns/collection-pipeline/#when-to-use-the-collection-pipeline-pattern-in-java)

The Collection Pipeline pattern is ideal for Java developers handling bulk data operations, including filtering, mapping, sorting, and reducing collections, particularly with Java 8+ Stream API.

Use the Collection Pipeline pattern:

- When you need to perform a series of transformations on a collection of data.
- When you want to improve readability and maintainability of complex data processing code.
- When working with large datasets where intermediate results should not be stored in memory.

## [Real-World Applications of Collection Pipeline Pattern in Java](https://java-design-patterns.com/patterns/collection-pipeline/#real-world-applications-of-collection-pipeline-pattern-in-java)

- LINQ in .NET
- Stream API in Java 8+
- Collections in modern functional languages (e.g., Haskell, Scala)
- Database query builders and ORM frameworks

## [Benefits and Trade-offs of Collection Pipeline Pattern](https://java-design-patterns.com/patterns/collection-pipeline/#benefits-and-trade-offs-of-collection-pipeline-pattern)

Benefits:

- Readability: The code is more readable and declarative, making it easier to understand the sequence of operations.
- Maintainability: Easier to modify or extend the pipeline with additional operations.
- Reusability: Common operations can be abstracted into reusable functions.
- Lazy Evaluation: Some implementations allow for operations to be lazily evaluated, improving performance.

Trade-offs:

- Performance Overhead: Chaining multiple operations can introduce overhead compared to traditional loops, especially for short pipelines or very large collections.
- Debugging Difficulty: Debugging a chain of operations might be more challenging due to the lack of intermediate variables.
- Limited to Collections: Primarily focused on collections, and its utility might be limited outside of collection processing.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/collection-pipeline/#related-java-design-patterns)

- [Builder](https://java-design-patterns.com/patterns/builder/): Similar fluent interface style but used for object construction.
- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Conceptually similar in chaining handlers, but applied to object requests rather than data collection processing.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used within a pipeline stage to encapsulate different algorithms that can be selected at runtime.

## [References and Credits](https://java-design-patterns.com/patterns/collection-pipeline/#references-and-credits)

- [Functional Programming in Scala](https://amzn.to/4cEo6K2)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3THp4wy)
- [Refactoring: Improving the Design of Existing Code](https://amzn.to/3VDMWDO)
- [Collection Pipeline (Martin Fowler)](https://martinfowler.com/articles/collection-pipeline/)

---

## [functional/combinator] Combinator
> 官方文档: https://java-design-patterns.com/patterns/combinator/

FunctionalAbstractionCode simplificationFunctional decompositionIdiomReactiveAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/combinator/#also-known-as)

- Function Composition
- Functional Combinator

## [Intent of Combinator Design Pattern](https://java-design-patterns.com/patterns/combinator/#intent-of-combinator-design-pattern)

The Combinator pattern, a functional programming technique widely used in Java, is essential for combining functions to build complex behaviors. This pattern allows developers to combine multiple smaller functions or operations into a single, more complex operation, promoting flexible and reusable code. By leveraging higher-order functions, the Combinator pattern enhances code reuse and maintainability in Java applications, making it a valuable tool in software design. This approach fosters the creation of modular, scalable solutions in Java development.

## [Detailed Explanation of Combinator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/combinator/#detailed-explanation-of-combinator-pattern-with-real-world-examples)

Real-world example

> In the real world, the combinator design pattern can be likened to a meal preparation process in a kitchen. Imagine a chef who has a set of simple operations: chopping vegetables, boiling water, cooking rice, grilling chicken, and mixing ingredients. Each of these operations is a standalone function. The chef can combine these operations in various sequences to create different dishes. For example, to prepare a chicken rice bowl, the chef can combine the operations of cooking rice, grilling chicken, and mixing them with vegetables. By reusing these basic operations and combining them in different ways, the chef can efficiently prepare a wide variety of meals. Similarly, in software, the combinator pattern allows developers to combine simple, reusable functions to create more complex behaviors.

In plain words

> The combinator design pattern combines simple, reusable functions to create more complex and flexible operations.

Wikipedia says

> A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments.

Flowchart

![Combinator flowchart](https://java-design-patterns.com/assets/img/combinator-flowchart.5290cfd5.png)

## [Programmatic Example of Combinator Pattern in Java](https://java-design-patterns.com/patterns/combinator/#programmatic-example-of-combinator-pattern-in-java)

In software design, combinatory logic is pivotal for creating reusable and modular code components. By leveraging higher-order functions, the Combinator pattern promotes code reuse and maintainability in Java applications.

In this Java example, we demonstrate the implementation of combinators such as `contains`, `not`, `or`, and `and` to create complex finders.

```java
// Functional interface to find lines in text.
public interface Finder {

    // The function to find lines in text.
    List<String> find(String text);

    // Simple implementation of function {@link #find(String)}.
    static Finder contains(String word) {
        return txt -> Stream.of(txt.split("\n"))
                .filter(line -> line.toLowerCase().contains(word.toLowerCase()))
                .collect(Collectors.toList());
    }

    // combinator not.
    default Finder not(Finder notFinder) {
        return txt -> {
            List<String> res = this.find(txt);
            res.removeAll(notFinder.find(txt));
            return res;
        };
    }

    // combinator or.
    default Finder or(Finder orFinder) {
        return txt -> {
            List<String> res = this.find(txt);
            res.addAll(orFinder.find(txt));
            return res;
        };
    }

    // combinator and.
    default Finder and(Finder andFinder) {
        return
                txt -> this
                        .find(txt)
                        .stream()
                        .flatMap(line -> andFinder.find(line).stream())
                        .collect(Collectors.toList());
    }
    // Other properties and methods...
}
```

Then we have also another combinator for some complex finders `advancedFinder`, `filteredFinder`, `specializedFinder` and `expandedFinder`.

```java
// Complex finders consisting of simple finder.
public class Finders {

    private Finders() {
    }

    // Finder to find a complex query.
    public static Finder advancedFinder(String query, String orQuery, String notQuery) {
        return
                Finder.contains(query)
                        .or(Finder.contains(orQuery))
                        .not(Finder.contains(notQuery));
    }

    // Filtered finder looking a query with excluded queries as well.
    public static Finder filteredFinder(String query, String... excludeQueries) {
        var finder = Finder.contains(query);

        for (String q : excludeQueries) {
            finder = finder.not(Finder.contains(q));
        }
        return finder;
    }

    // Specialized query. Every next query is looked in previous result.
    public static Finder specializedFinder(String... queries) {
        var finder = identMult();

        for (String query : queries) {
            finder = finder.and(Finder.contains(query));
        }
        return finder;
    }

    // Expanded query. Looking for alternatives.
    public static Finder expandedFinder(String... queries) {
        var finder = identSum();

        for (String query : queries) {
            finder = finder.or(Finder.contains(query));
        }
        return finder;
    }
    // Other properties and methods...
}
```

Now that we have created the interface and methods for combinators, let's see how an application works with them.

```java
public class CombinatorApp {

    private static final String TEXT = """
            It was many and many a year ago,
            In a kingdom by the sea,
            That a maiden there lived whom you may know
            By the name of ANNABEL LEE;
            And this maiden she lived with no other thought
            Than to love and be loved by me.
            I was a child and she was a child,
            In this kingdom by the sea;
            But we loved with a love that was more than love-
            I and my Annabel Lee;
            With a love that the winged seraphs of heaven
            Coveted her and me.""";

    public static void main(String[] args) {
        var queriesOr = new String[]{"many", "Annabel"};
        var finder = Finders.expandedFinder(queriesOr);
        var res = finder.find(text());
        LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res);

        var queriesAnd = new String[]{"Annabel", "my"};
        finder = Finders.specializedFinder(queriesAnd);
        res = finder.find(text());
        LOGGER.info("the result of specialized(and) query[{}] is {}", queriesAnd, res);

        finder = Finders.advancedFinder("it was", "kingdom", "sea");
        res = finder.find(text());
        LOGGER.info("the result of advanced query is {}", res);

        res = Finders.filteredFinder(" was ", "many", "child").find(text());
        LOGGER.info("the result of filtered query is {}", res);
    }

    private static String text() {
        return TEXT;
    }
}
```

Program output:

```
20:03:52.746 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of expanded(or) query[[many, Annabel]] is [It was many and many a year ago,, By the name of ANNABEL LEE;, I and my Annabel Lee;]
20:03:52.749 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of specialized(and) query[[Annabel, my]] is [I and my Annabel Lee;]
20:03:52.750 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of advanced query is [It was many and many a year ago,]
20:03:52.750 [main] INFO com.iluwatar.combinator.CombinatorApp -- the result of filtered query is [But we loved with a love that was more than love-]
```

Now we can design our app to with the queries finding feature `expandedFinder`, `specializedFinder`, `advancedFinder`, `filteredFinder` which are all derived from `contains`, `or`, `not`, `and`.

## [When to Use the Combinator Pattern in Java](https://java-design-patterns.com/patterns/combinator/#when-to-use-the-combinator-pattern-in-java)

The Combinator pattern is particularly useful in functional programming where complex values are built from simpler, reusable components.

The applicable scenarios include:

- The solution to a problem can be constructed from simple, reusable components.
- There is a need for high modularity and reusability of functions.
- The programming environment supports first-class functions and higher-order functions.

## [Real-World Applications of Combinator Pattern in Java](https://java-design-patterns.com/patterns/combinator/#real-world-applications-of-combinator-pattern-in-java)

- Functional programming languages like Haskell and Scala extensively use combinators for tasks ranging from parsing to UI construction.
- In domain-specific languages, particularly those involved in parsing, such as parsing expression grammars.
- In libraries for functional programming in languages like JavaScript, Python, and Ruby.
- java.util.function.Function#compose
- java.util.function.Function#andThen

## [Benefits and Trade-offs of Combinator Pattern](https://java-design-patterns.com/patterns/combinator/#benefits-and-trade-offs-of-combinator-pattern)

Benefits:

- Enhances developer productivity by using domain-specific terms and facilitates parallel execution in Java applications.
- Enhances modularity and reusability by breaking down complex tasks into simpler, composable functions.
- Promotes readability and maintainability by using a declarative style of programming.
- Facilitates lazy evaluation and potentially more efficient execution through function composition.

Trade-offs:

- Can lead to a steep learning curve for those unfamiliar with functional programming principles.
- May result in performance overhead due to the creation of intermediate functions.
- Debugging can be challenging due to the abstract nature of function compositions.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/combinator/#related-java-design-patterns)

- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/): Relies on chaining objects, whereas Combinator chains functions.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Similar to Combinator in enhancing functionality, but Decorator focuses on object augmentation.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Both involve selecting an algorithm at runtime, but Combinator uses composition of functions.

## [References and Credits](https://java-design-patterns.com/patterns/combinator/#references-and-credits)

- [Functional Programming in Scala](https://amzn.to/4cEo6K2)
- [Haskell: The Craft of Functional Programming](https://amzn.to/4axxtcF)
- [Structure and Interpretation of Computer Programs](https://amzn.to/3PJwVsf)
- [Combinator Pattern with Java 8 (Gregor Trefs)](https://gtrefs.github.io/code/combinator-pattern/)

---

## [functional/currying] Currying
> 官方文档: https://java-design-patterns.com/patterns/currying/

FunctionalCode simplificationFunctional decompositionGenericImmutableAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/currying/#also-known-as)

- Partial Function Application

## [Intent of Currying Design Pattern](https://java-design-patterns.com/patterns/currying/#intent-of-currying-design-pattern)

Currying decomposes a function that takes multiple arguments into a sequence of functions that each take a single argument. This technique is integral in functional programming, enabling the creation of higher-order functions through partial application of its arguments. Using currying in Java can lead to more modular, reusable, and maintainable code.

## [Detailed Explanation of Currying Pattern with Real-World Examples](https://java-design-patterns.com/patterns/currying/#detailed-explanation-of-currying-pattern-with-real-world-examples)

Real-world example

> Currying in programming can be compared to an assembly line in a factory. Imagine a car manufacturing process where each station on the assembly line performs a specific task, such as installing the engine, painting the car, and adding the wheels. Each station takes a partially completed car and performs a single operation before passing it to the next station. Similarly, in currying, a function that requires multiple arguments is broken down into a series of functions, each taking a single argument and returning another function until all arguments are provided. This step-by-step processing simplifies complex tasks by dividing them into manageable, sequential operations, which is especially useful in Java functional programming.

In plain words

> Decompose a function that take multiple arguments into multiple functions that take a single argument.

Wikipedia says

> In mathematics and computer science, currying is the technique of translating a function that takes multiple arguments into a sequence of families of functions, each taking a single argument.

Sequence diagram

![Currying sequence diagram](https://java-design-patterns.com/assets/img/currying-sequence-diagram.6c23bcb3.png)

## [Programmatic example of Currying Pattern in Java](https://java-design-patterns.com/patterns/currying/#programmatic-example-of-currying-pattern-in-java)

Consider a librarian who wants to populate their library with books. The librarian wants functions which can create books corresponding to specific genres and authors. Currying makes this possible by writing a curried book builder function and utilising partial application.

We have a `Book` class and `Genre` enum.

```java
public class Book {
    private final Genre genre;
    private final String author;
    private final String title;
    private final LocalDate publicationDate;

    Book(Genre genre, String author, String title, LocalDate publicationDate) {
        this.genre = genre;
        this.author = author;
        this.title = title;
        this.publicationDate = publicationDate;
    }
}
```

```java
public enum Genre {
    FANTASY,
    HORROR,
    SCI_FI
}
```

We could easily create a `Book` object with the following method:

```java
Book createBook(Genre genre, String author, String title, LocalDate publicationDate) {
    return new Book(genre, author, title, publicationDate);
}
```

However, what if we only wanted to create books from the `FANTASY` genre? Passing the `FANTASY` parameter with each method call would be repetitive. Alternatively, we could define a new method specifically for creating `FANTASY` books, but it would be impractical to create a separate method for each genre. The solution is to use a curried function.

```java
static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator
        = bookGenre
        -> bookAuthor
        -> bookTitle
        -> bookPublicationDate
        -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate);
```

Note that the order of the parameters is important. `genre` must come before `author`, `author` must come before `title` and so on. We must be considerate of this when writing curried functions to take full advantage of partial application. Using the above function, we can define a new function `fantasyBookFunc`, to generate `FANTASY` books as follows:

```java
Function<String, Function<String, Function<LocalDate, Book>>> fantasyBookFunc = Book.book_creator.apply(Genre.FANTASY);
```

Unfortunately, the type signature of `BOOK_CREATOR` and `fantasyBookFunc` are difficult to read and understand. We can improve this by using the [builder pattern](https://java-design-patterns.com/patterns/builder/) and functional interfaces.

```java
public static AddGenre builder() {
    return genre
            -> author
            -> title
            -> publicationDate
            -> new Book(genre, author, title, publicationDate);
}

public interface AddGenre {
    Book.AddAuthor withGenre(Genre genre);
}

public interface AddAuthor {
    Book.AddTitle withAuthor(String author);
}

public interface AddTitle {
    Book.AddPublicationDate withTitle(String title);
}

public interface AddPublicationDate {
    Book withPublicationDate(LocalDate publicationDate);
}
```

The semantics of the `builder` function can easily be understood. The `builder` function returns a function `AddGenre`, which adds the genre to the book. Similarity, the `AddGenre` function returns another function `AddTitle`, which adds the title to the book and so on, until the `AddPublicationDate` function returns a `Book`. For example, we could create a `Book` as follows:

```java
Book book = Book.builder().withGenre(Genre.FANTASY)
    .withAuthor("Author")
    .withTitle("Title")
    .withPublicationDate(LocalDate.of(2000, 7, 2));
```

The below example demonstrates how partial application can be used with the `builder` function to create specialised book builder functions.

```java
public static void main(String[] args) {
    LOGGER.info("Librarian begins their work.");

    // Defining genre book functions
    Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY);
    Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR);
    Book.AddAuthor scifiBookFunc = Book.builder().withGenre(Genre.SCIFI);

    // Defining author book functions
    Book.AddTitle kingFantasyBooksFunc = fantasyBookFunc.withAuthor("Stephen King");
    Book.AddTitle kingHorrorBooksFunc = horrorBookFunc.withAuthor("Stephen King");
    Book.AddTitle rowlingFantasyBooksFunc = fantasyBookFunc.withAuthor("J.K. Rowling");

    // Creates books by Stephen King (horror and fantasy genres)
    Book shining = kingHorrorBooksFunc.withTitle("The Shining")
            .withPublicationDate(LocalDate.of(1977, 1, 28));
    Book darkTower = kingFantasyBooksFunc.withTitle("The Dark Tower: Gunslinger")
            .withPublicationDate(LocalDate.of(1982, 6, 10));

    // Creates fantasy books by J.K. Rowling
    Book chamberOfSecrets = rowlingFantasyBooksFunc.withTitle("Harry Potter and the Chamber of Secrets")
            .withPublicationDate(LocalDate.of(1998, 7, 2));

    // Create sci-fi books
    Book dune = scifiBookFunc.withAuthor("Frank Herbert")
            .withTitle("Dune")
            .withPublicationDate(LocalDate.of(1965, 8, 1));
    Book foundation = scifiBookFunc.withAuthor("Isaac Asimov")
            .withTitle("Foundation")
            .withPublicationDate(LocalDate.of(1942, 5, 1));

    LOGGER.info("Stephen King Books:");
    LOGGER.info(shining.toString());
    LOGGER.info(darkTower.toString());

    LOGGER.info("J.K. Rowling Books:");
    LOGGER.info(chamberOfSecrets.toString());

    LOGGER.info("Sci-fi Books:");
    LOGGER.info(dune.toString());
    LOGGER.info(foundation.toString());
}
```

Program output:

```
09:04:52.499 [main] INFO com.iluwatar.currying.App -- Librarian begins their work.
09:04:52.502 [main] INFO com.iluwatar.currying.App -- Stephen King Books:
09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=HORROR, author='Stephen King', title='The Shining', publicationDate=1977-01-28}
09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=FANTASY, author='Stephen King', title='The Dark Tower: Gunslinger', publicationDate=1982-06-10}
09:04:52.506 [main] INFO com.iluwatar.currying.App -- J.K. Rowling Books:
09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=FANTASY, author='J.K. Rowling', title='Harry Potter and the Chamber of Secrets', publicationDate=1998-07-02}
09:04:52.506 [main] INFO com.iluwatar.currying.App -- Sci-fi Books:
09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=SCIFI, author='Frank Herbert', title='Dune', publicationDate=1965-08-01}
09:04:52.506 [main] INFO com.iluwatar.currying.App -- Book{genre=SCIFI, author='Isaac Asimov', title='Foundation', publicationDate=1942-05-01}
```

## [When to Use the Currying Pattern in Java](https://java-design-patterns.com/patterns/currying/#when-to-use-the-currying-pattern-in-java)

- When functions need to be called with some arguments preset in Java.
- In functional programming languages or paradigms to simplify functions that take multiple arguments.
- To improve code reusability and composability by breaking down functions into simpler, unary functions, enhancing the modularity of Java applications.

## [Currying Pattern Java Tutorials](https://java-design-patterns.com/patterns/currying/#currying-pattern-java-tutorials)

- [Currying in Java (Baeldung)](https://www.baeldung.com/java-currying)
- [What Is Currying in Programming (Towards Data Science)](https://towardsdatascience.com/what-is-currying-in-programming-56fd57103431#:~:text=Currying%20is%20helpful%20when%20you,concise%2C%20and%20more%20readable%20solution.)
- [Why the fudge should I use currying? (DailyJS)](https://medium.com/dailyjs/why-the-fudge-should-i-use-currying-84e4000c8743)

## [Real-World Applications of Currying Pattern in Java](https://java-design-patterns.com/patterns/currying/#real-world-applications-of-currying-pattern-in-java)

- Functional programming languages like Haskell, Scala, and JavaScript.
- Java programming, especially with lambda expressions and streams introduced in Java 8.
- Event handling in UIs where a function with specific parameters needs to be triggered upon an event.
- APIs that require configuration with multiple parameters.

## [Benefits and Trade-offs of Currying Pattern](https://java-design-patterns.com/patterns/currying/#benefits-and-trade-offs-of-currying-pattern)

Benefits:

- Increases function reusability by allowing the creation of specialized functions from more generic ones.
- Enhances code readability and maintainability by breaking complex functions into simpler, single-argument functions.
- Facilitates function composition, leading to more declarative and concise code.

Trade-offs:

- Can lead to performance overhead due to the creation of additional closures.
- May make debugging more challenging, as it introduces additional layers of function calls.
- Can be less intuitive for developers unfamiliar with functional programming concepts.
- As shown in the programmatic example above, curried functions with several parameters have a cumbersome type signature in Java.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/currying/#related-java-design-patterns)

- Function Composition: Currying is often used in conjunction with function composition to enable more readable and concise code.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): While not the same, currying shares the decorator pattern's concept of wrapping functionality.
- [Factory](https://java-design-patterns.com/patterns/factory/): Currying can be used to create factory functions that produce variations of a function with certain arguments preset.

## [References and Credits](https://java-design-patterns.com/patterns/currying/#references-and-credits)

- [Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions](https://amzn.to/3TKeZPD)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3J6vEaW)
- [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://amzn.to/3J6vJLM)

---

## [functional/function-composition] Function Composition
> 官方文档: https://java-design-patterns.com/patterns/function-composition/

FunctionalCode simplificationCompositionFunctional decompositionReusabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/function-composition/#also-known-as)

- Function Chaining
- Higher-Order Function Wrapping

## [Intent of Function Composition Design Pattern](https://java-design-patterns.com/patterns/function-composition/#intent-of-function-composition-design-pattern)

Combine multiple small functions into a single operation that executes them in a sequence, producing a new function as the result.

## [Detailed Explanation of Function Composition Pattern with Real-World Examples](https://java-design-patterns.com/patterns/function-composition/#detailed-explanation-of-function-composition-pattern-with-real-world-examples)

Real-world example

> Imagine a fast-food restaurant where the process of making a burger is broken down into several steps: grilling the patty, toasting the bun, adding condiments, and assembling the burger. Each of these steps can be seen as a function.
>
> In the Functional Composition design pattern, these individual steps (functions) can be composed into a complete burger-making process. Each step remains simple and reusable. For instance, the grilling function could be reused for making sandwiches or other dishes that require a grilled patty. This modular approach allows the restaurant to efficiently create various menu items by reusing and combining simple, predefined steps.

In plain words

> The Function Composition pattern allows building complex functions by combining simpler ones, making it easier to manage, test, and reuse individual pieces of functionality.

Wikipedia says

> Function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole.

Sequence diagram

![Function Composition sequence diagram](https://java-design-patterns.com/assets/img/function-composition-sequence-diagram.fec997f2.png)

## [Programmatic Example of Function Composition Pattern in Java](https://java-design-patterns.com/patterns/function-composition/#programmatic-example-of-function-composition-pattern-in-java)

In the functional programming paradigm, function composition is a powerful technique. For instance, in Java, you can use higher-order functions to combine operations like multiplying and squaring numbers.

Using Java's functional interfaces, we can define simple functions and compose them. Here's how function composition works in Java.

Let's start with defining two simple functions. In this case, we have a function `timesTwo` that multiplies its input by 2, and a function `square` that squares its input:

```java
Function<Integer, Integer> timesTwo = x -> x * 2;
Function<Integer, Integer> square = x -> x * x;
```

Next, we use the `FunctionComposer` class to compose these two functions into a new function. The `composeFunctions` method takes two functions as arguments and returns a new function that is the composition of the input functions:

```java
Function<Integer, Integer> composedFunction = FunctionComposer.composeFunctions(timesTwo, square);
```

Finally, we apply the composed function to an input value. In this case, we apply it to the number 3. The result is the square of the number 3 multiplied by 2, which is 36:

```java
public static void main(String[] args) {
    final var logger = LoggerFactory.getLogger(App.class);
    Function<Integer, Integer> timesTwo = x -> x * 2;
    Function<Integer, Integer> square = x -> x * x;

    Function<Integer, Integer> composedFunction = FunctionComposer.composeFunctions(timesTwo, square);

    int result = composedFunction.apply(3);
    logger.info("Result of composing 'timesTwo' and 'square' functions applied to 3 is: " + result);
}
```

This will output:

```
Result of composing 'timesTwo' and 'square' functions applied to 3 is: 36
```

This example demonstrates how the Function Composition pattern can be used to create complex functions by composing simpler ones, enhancing modularity and reusability of function-based logic.

## [When to Use the Function Composition Pattern in Java](https://java-design-patterns.com/patterns/function-composition/#when-to-use-the-function-composition-pattern-in-java)

Use the Function Composition pattern when:

- When you want to build complex transformations by chaining smaller, reusable functions in Java.
- When the logic is best expressed through a series of operations that naturally feed one into another.
- When you want to reduce code duplication and improve readability by isolating each operation in its own function.

## [Function Composition Pattern Java Tutorials](https://java-design-patterns.com/patterns/function-composition/#function-composition-pattern-java-tutorials)

- [Function Composition in Java (Medium)](https://functionalprogramming.medium.com/function-composition-in-java-beaf39426f52)
- [Functional Programming in Java (Baeldung)](https://www.baeldung.com/java-functional-programming)

## [Real-World Applications of Function Composition Pattern in Java](https://java-design-patterns.com/patterns/function-composition/#real-world-applications-of-function-composition-pattern-in-java)

- Java’s Stream API, where map and filter are composed for data transformations.
- Google Guava’s Function utilities.
- Apache Commons libraries that provide utilities for chaining functions.

## [Benefits and Trade-offs of Function Composition Pattern](https://java-design-patterns.com/patterns/function-composition/#benefits-and-trade-offs-of-function-composition-pattern)

Benefits:

- Encourages highly modular and reusable code.
- Simplifies complex logic by breaking it down into smaller, testable units.
- Makes the code more expressive and easier to maintain.

Trade-offs:

- Excessive chaining can reduce readability if taken too far.
- May introduce performance overhead due to multiple function calls.
- Errors can be harder to trace in a deeply composed function pipeline.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/function-composition/#related-java-design-patterns)

- [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/) \- Both patterns allow processing to be broken down into a series of steps, but Functional Composition focuses on function composition rather than responsibility delegation.
- [Composite](https://java-design-patterns.com/patterns/composite/): Also deals with combining smaller components, though it is typically about object structure rather than function operations.

## [References and Credits](https://java-design-patterns.com/patterns/function-composition/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Functional Programming in Java](https://amzn.to/3JUIc5Q)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs)

---

## [functional/map-reduce] MapReduce
> 官方文档: https://java-design-patterns.com/patterns/map-reduce/

FunctionalConcurrencyData processingData transformationFunctional decompositionImmutableMultithreadingScalabilityAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/map-reduce/#also-known-as)

- Map-Reduce
- Divide and Conquer for Data Processing

## [Intent of Map Reduce Design Pattern](https://java-design-patterns.com/patterns/map-reduce/#intent-of-map-reduce-design-pattern)

To efficiently process large-scale datasets by dividing computation into two phases: map and reduce, which can be executed in parallel and distributed across multiple nodes.

## [Detailed Explanation of Map Reduce Pattern with Real-World Examples](https://java-design-patterns.com/patterns/map-reduce/#detailed-explanation-of-map-reduce-pattern-with-real-world-examples)

Real-world example

> Imagine a large e-commerce company that wants to analyze its sales data across multiple regions. They have terabytes of transaction data stored across hundreds of servers. Using MapReduce, they can efficiently process this data to calculate total sales by product category. The Map function would process individual sales records, emitting key-value pairs of (category, sale amount). The Reduce function would then sum up all sale amounts for each category, producing the final result.

In plain words

> MapReduce splits a large problem into smaller parts, processes them in parallel, and then combines the results.

Wikipedia says

> MapReduce is a programming model and associated implementation for processing and generating big data sets with a parallel, distributed algorithm on a cluster. MapReduce consists of two main steps:
>
> The Map step: The master node takes the input, divides it into smaller sub-problems, and distributes them to worker nodes. A worker node may do this again in turn, leading to a multi-level tree structure. The worker node processes the smaller problem, and passes the answer back to its master node. The Reduce step: The master node then collects the answers to all the sub-problems and combines them in some way to form the output – the answer to the problem it was originally trying to solve. This approach allows for efficient processing of vast amounts of data across multiple machines, making it a fundamental technique in big data analytics and distributed computing.

Flowchart

![MapReduce flowchart](https://java-design-patterns.com/assets/img/mapreduce-flowchart.37cbbec1.png)

## [Programmatic Example of Map Reduce in Java](https://java-design-patterns.com/patterns/map-reduce/#programmatic-example-of-map-reduce-in-java)

### [1\. Map Phase (Splitting & Processing Data)](https://java-design-patterns.com/patterns/map-reduce/#_1-map-phase-splitting-processing-data)

- Each input string is split into words, normalized, and counted.
- Output: A map `{word → count}` for each input string.

#### [`Mapper.java`](https://java-design-patterns.com/patterns/map-reduce/#mapper-java)

```java
public class Mapper {
    public static Map<String, Integer> map(String input) {
        Map<String, Integer> wordCount = new HashMap<>();
        String[] words = input.split("\\s+");
        for (String word : words) {
            word = word.toLowerCase().replaceAll("[^a-z]", "");
            if (!word.isEmpty()) {
                wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
            }
        }
        return wordCount;
    }
}
```

Example Input: `"Hello world hello"`

Output: `{hello=2, world=1}`

### [2\. Shuffle Phase – Grouping Words Across Inputs](https://java-design-patterns.com/patterns/map-reduce/#_2-shuffle-phase-%E2%80%93-grouping-words-across-inputs)

- Takes results from all mappers and groups values by word.
- Output: A map `{word → list of counts}`.

#### [`Shuffler.java`](https://java-design-patterns.com/patterns/map-reduce/#shuffler-java)

```java
public class Shuffler {
    public static Map<String, List<Integer>> shuffleAndSort(List<Map<String, Integer>> mapped) {
        Map<String, List<Integer>> grouped = new HashMap<>();
        for (Map<String, Integer> map : mapped) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                grouped.putIfAbsent(entry.getKey(), new ArrayList<>());
                grouped.get(entry.getKey()).add(entry.getValue());
            }
        }
        return grouped;
    }
}
```

Example Input:

```
[\
    {"hello": 2, "world": 1},\
    {"hello": 1, "java": 1}\
]
```

Output:

```
{
    "hello": [2, 1],
    "world": [1],
    "java": [1]
}
```

### [3\. Reduce Phase – Aggregating Counts](https://java-design-patterns.com/patterns/map-reduce/#_3-reduce-phase-%E2%80%93-aggregating-counts)

- Sums the list of counts for each word.
- Output: A sorted list of word counts in descending order.

#### [`Reducer.java`](https://java-design-patterns.com/patterns/map-reduce/#reducer-java)

```java
public class Reducer {
    public static List<Map.Entry<String, Integer>> reduce(Map<String, List<Integer>> grouped) {
        Map<String, Integer> reduced = new HashMap<>();
        for (Map.Entry<String, List<Integer>> entry : grouped.entrySet()) {
            reduced.put(entry.getKey(), entry.getValue().stream().mapToInt(Integer::intValue).sum());
        }

        List<Map.Entry<String, Integer>> result = new ArrayList<>(reduced.entrySet());
        result.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
        return result;
    }
}
```

Example Input:

```
{
    "hello": [2, 1],
    "world": [1],
    "java": [1]
}
```

Output:

```
[\
    {"hello": 3},\
    {"world": 1},\
    {"java": 1}\
]
```

### [4\. MapReduce Coordinator – Running the Whole Pipeline](https://java-design-patterns.com/patterns/map-reduce/#_4-mapreduce-coordinator-%E2%80%93-running-the-whole-pipeline)

- Coordinates map, shuffle, and reduce phases.

#### [`MapReduce.java`](https://java-design-patterns.com/patterns/map-reduce/#mapreduce-java)

```java
public class MapReduce {
    public static List<Map.Entry<String, Integer>> mapReduce(List<String> inputs) {
        List<Map<String, Integer>> mapped = new ArrayList<>();
        for (String input : inputs) {
            mapped.add(Mapper.map(input));
        }

        Map<String, List<Integer>> grouped = Shuffler.shuffleAndSort(mapped);

        return Reducer.reduce(grouped);
    }
}
```

### [5\. Main Execution – Example Usage](https://java-design-patterns.com/patterns/map-reduce/#_5-main-execution-%E2%80%93-example-usage)

- Runs the MapReduce process and prints results.

#### [`Main.java`](https://java-design-patterns.com/patterns/map-reduce/#main-java)

```java
  public static void main(String[] args) {
    List<String> inputs = Arrays.asList(
            "Hello world hello",
            "MapReduce is fun",
            "Hello from the other side",
            "Hello world"
    );
    List<Map.Entry<String, Integer>> result = MapReduce.mapReduce(inputs);
    for (Map.Entry<String, Integer> entry : result) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}
```

Output:

```
hello: 4
world: 2
the: 1
other: 1
side: 1
mapreduce: 1
is: 1
from: 1
fun: 1
```

## [When to Use the Map Reduce Pattern in Java](https://java-design-patterns.com/patterns/map-reduce/#when-to-use-the-map-reduce-pattern-in-java)

Use MapReduce when:

- When processing large datasets that can be broken into independent chunks.
- When data operations can be naturally divided into map (transformation) and reduce (aggregation) phases.
- When horizontal scalability and parallelization are essential, especially in distributed or big data environments.
- When leveraging Java-based distributed computing platforms like Hadoop or Spark.

## [Map Reduce Pattern Java Tutorials](https://java-design-patterns.com/patterns/map-reduce/#map-reduce-pattern-java-tutorials)

- [MapReduce Tutorial(Apache Hadoop)](https://hadoop.apache.org/docs/stable/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html)
- [MapReduce Example(Simplilearn)](https://www.youtube.com/watch?v=l2clwKnrtO8)

## [Benefits and Trade-offs of Map Reduce Pattern](https://java-design-patterns.com/patterns/map-reduce/#benefits-and-trade-offs-of-map-reduce-pattern)

Benefits:

- Enables massive scalability by distributing processing across nodes.
- Encourages a functional style, promoting immutability and stateless operations.
- Simplifies complex data workflows by separating transformation (map) from aggregation (reduce).
- Fault-tolerant due to isolated, recoverable processing tasks.

Trade-offs:

- Requires a suitable problem structure — not all tasks fit the map/reduce paradigm.
- Data shuffling between map and reduce phases can be performance-intensive.
- Higher complexity in debugging and optimizing distributed jobs.
- Intermediate I/O can become a bottleneck in large-scale operations.

## [Real-World Applications of Map Reduce Pattern in Java](https://java-design-patterns.com/patterns/map-reduce/#real-world-applications-of-map-reduce-pattern-in-java)

- Hadoop MapReduce: Java-based framework for distributed data processing using MapReduce.
- Apache Spark: Utilizes similar map and reduce transformations in its RDD and Dataset APIs.
- Elasticsearch: Uses MapReduce-style aggregation pipelines for querying distributed data.
- Google Bigtable: Underlying storage engine influenced by MapReduce principles.
- MongoDB Aggregation Framework: Conceptually applies MapReduce in its data pipelines.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/map-reduce/#related-java-design-patterns)

- [Master-Worker](https://java-design-patterns.com/patterns/master-worker/): Similar distribution of tasks among workers, with a master coordinating job execution.
- [Pipeline](https://java-design-patterns.com/patterns/pipeline/): Can be used to chain multiple MapReduce operations into staged transformations.
- [Iterator](https://java-design-patterns.com/patterns/iterator/): Often used under the hood to process input streams lazily in map and reduce steps.

## [References and Credits](https://java-design-patterns.com/patterns/map-reduce/#references-and-credits)

- [Big Data: Principles and Paradigms](https://amzn.to/3RJIGPZ)
- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3E6VhtD)
- [Hadoop: The Definitive Guide: Storage and Analysis at Internet Scale](https://amzn.to/4ij2y7F)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs)
- [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3HWNf4U)
- [Programming Pig: Dataflow Scripting with Hadoop](https://amzn.to/4cAU36K)
- [What is MapReduce (IBM)](https://www.ibm.com/think/topics/mapreduce)
- [Why MapReduce is not dead (Codemotion)](https://www.codemotion.com/magazine/ai-ml/big-data/mapreduce-not-dead-heres-why-its-still-ruling-in-the-cloud/)

---

## [functional/monad] Monad
> 官方文档: https://java-design-patterns.com/patterns/monad/

FunctionalAbstractionAccumulationDecouplingEncapsulationFunctional decompositionGenericIdiomInstantiationInterfaceLayered architectureObject compositionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/monad/#also-known-as)

- Computation Wrapper
- Monadic Interface

## [Intent of Monad Design Pattern](https://java-design-patterns.com/patterns/monad/#intent-of-monad-design-pattern)

The Monad design pattern in Java provides a mechanism for encapsulating computations or side effects, enabling the chaining of operations while managing context and data flow in a side-effect-free manner.

## [Detailed Explanation of Monad Pattern with Real-World Examples](https://java-design-patterns.com/patterns/monad/#detailed-explanation-of-monad-pattern-with-real-world-examples)

Real-world example

> Consider a real-world example of a monad in Java with a restaurant meal ordering process. This encapsulation and chaining allow for a clean, error-managed progression, similar to how monads handle data and operations in functional programming. In this scenario, each step of selecting a dish, adding sides, and choosing a drink can be thought of as a monadic operation. Each operation encapsulates the current state of the order (e.g., main dish chosen) and allows for the next choice (e.g., selecting a side) without exposing the complexity of the entire order's details to the customer.
>
> Just like in a functional monad, if any step fails (like an unavailable dish), the entire process can be halted or redirected without throwing exceptions, maintaining a smooth flow. This encapsulation and chaining allow for a clean, error-managed progression from choosing the main dish to completing the full meal order, akin to how monads handle data and operations in functional programming. This approach ensures a consistent experience, where every choice builds on the previous one in a controlled manner.

In plain words

> Monad pattern ensures that each operation is executed regardless of the success or failure of previous ones.

Wikipedia says

> In functional programming, a monad is a structure that combines program fragments (functions) and wraps their return values in a type with additional computation. In addition to defining a wrapping monadic type, monads define two operators: one to wrap a value in the monad type, and another to compose together functions that output values of the monad type (these are known as monadic functions). General-purpose languages use monads to reduce boilerplate code needed for common operations (such as dealing with undefined values or fallible functions, or encapsulating bookkeeping code). Functional languages use monads to turn complicated sequences of functions into succinct pipelines that abstract away control flow, and side effects.

Flowchart

![Monad flowchart](https://java-design-patterns.com/assets/img/monad-flowchart.b02d0e48.png)

## [Programmatic Example of Monad Pattern in Java](https://java-design-patterns.com/patterns/monad/#programmatic-example-of-monad-pattern-in-java)

Here’s the Monad implementation in Java. The `Validator` class encapsulates an object and performs validation steps in a monadic fashion, showcasing the benefits of using the Monad pattern for error handling and state management.

```java
public class Validator<T> {
  private final T obj;
  private final List<Throwable> exceptions = new ArrayList<>();

   private Validator(T obj) {
    this.obj = obj;
  }
  public static <T> Validator<T> of(T t) {
    return new Validator<>(Objects.requireNonNull(t));
  }

  public Validator<T> validate(Predicate<? super T> validation, String message) {
    if (!validation.test(obj)) {
      exceptions.add(new IllegalStateException(message));
    }
    return this;
  }

  public <U> Validator<T> validate(
      Function<? super T, ? extends U> projection,
      Predicate<? super U> validation,
      String message
  ) {
    return validate(projection.andThen(validation::test)::apply, message);
  }

  public T get() throws IllegalStateException {
    if (exceptions.isEmpty()) {
      return obj;
    }
    var e = new IllegalStateException();
    exceptions.forEach(e::addSuppressed);
    throw e;
  }
}
```

Next we define an enum `Sex`.

```java
public enum Sex {
  MALE, FEMALE
}
```

Now we can introduce the `User`.

```java
public record User(String name, int age, Sex sex, String email) {
}
```

And finally, a `User` object is validated for its name, email, and age using the `Validator` monad.

```java
public static void main(String[] args) {
    var user = new User("user", 24, Sex.FEMALE, "foobar.com");
    LOGGER.info(Validator.of(user).validate(User::name, Objects::nonNull, "name is null")
        .validate(User::name, name -> !name.isEmpty(), "name is empty")
        .validate(User::email, email -> !email.contains("@"), "email doesn't contains '@'")
        .validate(User::age, age -> age > 20 && age < 30, "age isn't between...").get()
        .toString());
}
```

Console output:

```
15:06:17.679 [main] INFO com.iluwatar.monad.App -- User[name=user, age=24, sex=FEMALE, email=foobar.com]
```

## [When to Use the Monad Pattern in Java](https://java-design-patterns.com/patterns/monad/#when-to-use-the-monad-pattern-in-java)

The Monad design pattern is applicable when

- Consistent and unified error handling is required without relying on exceptions, particularly in functional programming paradigms.
- Asynchronous computations need clear and maintainable chaining.
- State needs to be managed and encapsulated within functional flows.
- Dependencies and lazy evaluations are to be handled cleanly and efficiently.

## [Monad Pattern Java Tutorials](https://java-design-patterns.com/patterns/monad/#monad-pattern-java-tutorials)

- [Design Pattern Reloaded (Remi Forax)](https://youtu.be/-k2X7guaArU)

## [Real-World Applications of Monad Pattern in Java](https://java-design-patterns.com/patterns/monad/#real-world-applications-of-monad-pattern-in-java)

- Optional in Java's standard library for handling potential absence of values.
- Stream for constructing functional pipelines to operate on collections.
- Frameworks like Vavr enhance functional programming in Java by providing monadic constructs for better code maintainability.

## [Benefits and Trade-offs of Monad Pattern](https://java-design-patterns.com/patterns/monad/#benefits-and-trade-offs-of-monad-pattern)

Benefits:

- Increases code readability and reduces boilerplate.
- Encourages a declarative programming style.
- Promotes immutability and thread safety.
- Simplifies complex error handling and state management.

Trade-offs:

- Can be challenging for developers new to functional programming.
- May introduce performance overhead due to additional abstraction layers.
- Debugging can be difficult due to less transparent operational flow.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/monad/#related-java-design-patterns)

Related design patterns to monads in Java include

- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Similar in that it helps instantiate monads, encapsulating object creation logic.
- [Command](https://java-design-patterns.com/patterns/command/): Also encapsulates operations, but monads add context management to the mix.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Dynamically enhances functionalities, whereas monads use static typing for consistent composability.

## [References and Credits](https://java-design-patterns.com/patterns/monad/#references-and-credits)

- [Functional Programming in Java](https://amzn.to/3JUIc5Q)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs)
- [Real-World Software Development: A Project-Driven Guide to Fundamentals in Java](https://amzn.to/4btoN7U)
- [Monad (functional programming) (Wikipedia)](https://en.wikipedia.org/wiki/Monad_(functional_programming))

---

## [functional/trampoline] Trampoline
> 官方文档: https://java-design-patterns.com/patterns/trampoline/

FunctionalCode simplificationFunctional decompositionPerformanceRecursionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/trampoline/#also-known-as)

- Bounce
- Tail-Call Optimization

## [Intent of Trampoline Design Pattern](https://java-design-patterns.com/patterns/trampoline/#intent-of-trampoline-design-pattern)

The Trampoline Pattern in Java optimizes recursive function calls by converting them into iterative loops, avoiding stack overflow errors.

## [Detailed Explanation of Trampoline Pattern with Real-World Examples](https://java-design-patterns.com/patterns/trampoline/#detailed-explanation-of-trampoline-pattern-with-real-world-examples)

Real-world example

> Imagine you are organizing a relay race. Each runner passes the baton to the next runner until the race is complete. However, if each runner had to physically run back to the starting line to pass the baton to the next runner, the race would be inefficient and error-prone. Instead, runners pass the baton directly to the next runner in line, who continues the race seamlessly.
>
> The Trampoline pattern in programming works similarly by ensuring that each recursive step is handed off efficiently without having to return to the start, preventing a stack overflow (similar to our runners never having to backtrack).

In plain words

> The Trampoline pattern in Java allows efficient recursion without running out of stack memory, optimizing deep recursive calls for better performance and stack safety.

Wikipedia says

> In Java, trampoline refers to using reflection to avoid using inner classes, for example in event listeners. The time overhead of a reflection call is traded for the space overhead of an inner class. Trampolines in Java usually involve the creation of a GenericListener to pass events to an outer class.

Flowchart

![Trampoline Pattern Flowchart](https://java-design-patterns.com/assets/img/trampoline-flowchart.dd567bc7.png)

## [Programmatic Example of Trampoline Pattern in Java](https://java-design-patterns.com/patterns/trampoline/#programmatic-example-of-trampoline-pattern-in-java)

Here's the `Trampoline` implementation in Java.

When `get` is called on the returned Trampoline, internally it will iterate calling `jump` on the returned `Trampoline` as long as the concrete instance returned is `Trampoline`, stopping once the returned instance is `done`.

```java
public interface Trampoline<T> {

  T get();

  default Trampoline<T> jump() {
    return this;
  }

  default T result() {
    return get();
  }

  default boolean complete() {
    return true;
  }

  static <T> Trampoline<T> done(final T result) {
    return () -> result;
  }

  static <T> Trampoline<T> more(final Trampoline<Trampoline<T>> trampoline) {
    return new Trampoline<T>() {
      @Override
      public boolean complete() {
        return false;
      }

      @Override
      public Trampoline<T> jump() {
        return trampoline.result();
      }

      @Override
      public T get() {
        return trampoline(this);
      }

      T trampoline(final Trampoline<T> trampoline) {
        return Stream.iterate(trampoline, Trampoline::jump)
            .filter(Trampoline::complete)
            .findFirst()
            .map(Trampoline::result)
            .orElseThrow();
      }
    };
  }
}
```

Using the `Trampoline` to get Fibonacci values.

```java
@Slf4j
public class TrampolineApp {

    public static void main(String[] args) {
        LOGGER.info("Start calculating war casualties");
        var result = loop(10, 1).result();
        LOGGER.info("The number of orcs perished in the war: {}", result);

    }

    public static Trampoline<Integer> loop(int times, int prod) {
        if (times == 0) {
            return Trampoline.done(prod);
        } else {
            return Trampoline.more(() -> loop(times - 1, prod * times));
        }
    }
}
```

Program output:

```
19:22:24.462 [main] INFO com.iluwatar.trampoline.TrampolineApp - Start calculating war casualties
19:22:24.472 [main] INFO com.iluwatar.trampoline.TrampolineApp - The number of orcs perished in the war: 3628800
```

## [When to Use the Trampoline Pattern in Java](https://java-design-patterns.com/patterns/trampoline/#when-to-use-the-trampoline-pattern-in-java)

Use the Trampoline pattern when

- When dealing with algorithms that use recursion heavily and risk running into stack overflow errors.
- When tail-call optimization is not supported by the Java language natively.

## [Trampoline Pattern Java Tutorials](https://java-design-patterns.com/patterns/trampoline/#trampoline-pattern-java-tutorials)

- [Laziness, trampolines, monoids and other functional amenities: This is not your father's Java(Mario Fusco)](https://www.slideshare.net/mariofusco/lazine)
- [Trampoline.java (totallylazy)](https://github.com/bodar/totallylazy/blob/master/src/com/googlecode/totallylazy/Trampoline.java)
- [Trampoline: Java Glossary (mindprod.com)](http://mindprod.com/jgloss/trampoline.html)
- [Trampolining: A practical guide for awesome Java Developers (John McClean)](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076)
- [What is a trampoline function? (Stack Overflow)](https://stackoverflow.com/questions/189725/what-is-a-trampoline-function)

## [Real-World Applications of Trampoline Pattern in Java](https://java-design-patterns.com/patterns/trampoline/#real-world-applications-of-trampoline-pattern-in-java)

- Implementing algorithms that require deep recursion, such as certain tree traversals, combinatorial algorithms, and mathematical computations.
- Functional programming libraries and frameworks where tail-call optimization is necessary for performance and stack safety.
- [cyclops-react](https://github.com/aol/cyclops-react)

## [Benefits and Trade-offs of Trampoline Pattern](https://java-design-patterns.com/patterns/trampoline/#benefits-and-trade-offs-of-trampoline-pattern)

Benefits:

- Prevents stack overflow by converting deep recursion into iteration.
- Enhances performance by avoiding the overhead of deep recursive calls.
- Simplifies the code by making recursive calls look like a sequence of steps.

Trade-offs:

- May introduce additional complexity in terms of understanding and implementing the trampoline mechanism.
- Requires converting naturally recursive algorithms into a continuation-passing style.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/trampoline/#related-java-design-patterns)

- [Iterator](https://java-design-patterns.com/patterns/iterator/): Both patterns aim to transform potentially recursive operations into iterative processes, though the iterator pattern is more general-purpose.
- [State](https://java-design-patterns.com/patterns/state/): Like the Trampoline, the State pattern can also handle complex state transitions, which can sometimes involve recursive-like state changes.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): This pattern can be related in terms of defining a family of algorithms (or continuations in the case of the Trampoline) and making them interchangeable.

## [References and Credits](https://java-design-patterns.com/patterns/trampoline/#references-and-credits)

- [Functional Programming in Java](https://amzn.to/3JUIc5Q)
- [Functional Programming for Java Developers: Tools for Better Concurrency, Abstraction, and Agility](https://amzn.to/4dRu4rJ)
- [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs)
- [Modern Java in Action: Lambdas, streams, functional and reactive programming](https://amzn.to/3yxdu0g)

---

<!-- ============================================ -->
<!-- Integration 集成模式 (5 个) -->
<!-- ============================================ -->

## [integration/ambassador] Ambassador
> 官方文档: https://java-design-patterns.com/patterns/ambassador/

IntegrationAPI designDecouplingFault toleranceProxyResilienceScalabilityAbout 5 min

* * *

## [Intent of Ambassador Design Pattern](https://java-design-patterns.com/patterns/ambassador/#intent-of-ambassador-design-pattern)

The Ambassador Pattern in Java helps offload common functionalities such as monitoring, logging, and routing from a shared resource to a helper service instance, enhancing performance and maintainability in distributed systems.

## [Detailed Explanation of Ambassador Pattern with Real-World Examples](https://java-design-patterns.com/patterns/ambassador/#detailed-explanation-of-ambassador-pattern-with-real-world-examples)

Real-world example

> Imagine a busy hotel where guests frequently request restaurant reservations, event tickets, or transportation arrangements. Instead of each guest individually contacting these services, the hotel provides a concierge. The concierge handles these tasks on behalf of the guests, ensuring that reservations are made smoothly, tickets are booked on time, and transportation is scheduled efficiently.
>
> In this analogy, the guests are the client services, the external providers (restaurants, ticket vendors, transportation) are the remote services, and the concierge represents the ambassador service. This setup allows the guests to focus on enjoying their stay while the concierge manages the complexities of external interactions, providing a seamless and enhanced experience.

In plain words

> With the Ambassador pattern, we can implement less-frequent polling from clients along with latency checks and logging.

Microsoft documentation states

> An ambassador service can be thought of as an out-of-process proxy which is co-located with the client. This pattern can be useful for offloading common client connectivity tasks such as monitoring, logging, routing, security (such as TLS), and resiliency patterns in a language agnostic way. It is often used with legacy applications, or other applications that are difficult to modify, in order to extend their networking capabilities. It can also enable a specialized team to implement those features.

Sequence diagram

![Ambassador sequence diagram](https://java-design-patterns.com/assets/img/ambassador-sequence-diagram.b533e3e1.png)

## [Programmatic Example of Ambassador Pattern in Java](https://java-design-patterns.com/patterns/ambassador/#programmatic-example-of-ambassador-pattern-in-java)

In this example of the Ambassador Pattern in Java, we demonstrate how to implement latency checks, logging, and retry mechanisms to improve system reliability.

A remote service has many clients accessing a function it provides. The service is a legacy application and is impossible to update. Large numbers of requests from users are causing connectivity issues. New rules for request frequency should be implemented along with latency checks and client-side logging.

With the above introduction in mind we will imitate the functionality in this example. We have an interface implemented by the remote service as well as the ambassador service.

```java
interface RemoteServiceInterface {
    long doRemoteFunction(int value) throws Exception;
}
```

A remote services represented as a singleton.

```java

@Slf4j
public class RemoteService implements RemoteServiceInterface {
    private static RemoteService service = null;

    static synchronized RemoteService getRemoteService() {
        if (service == null) {
            service = new RemoteService();
        }
        return service;
    }

    private RemoteService() {
    }

    @Override
    public long doRemoteFunction(int value) {
        long waitTime = (long) Math.floor(Math.random() * 1000);

        try {
            sleep(waitTime);
        } catch (InterruptedException e) {
            LOGGER.error("Thread sleep interrupted", e);
        }

        return waitTime >= 200 ? value * 10 : -1;
    }
}
```

A service ambassador adds additional features such as logging and latency checks.

```java

@Slf4j
public class ServiceAmbassador implements RemoteServiceInterface {
    private static final int RETRIES = 3;
    private static final int DELAY_MS = 3000;

    ServiceAmbassador() {
    }

    @Override
    public long doRemoteFunction(int value) {
        return safeCall(value);
    }

    private long checkLatency(int value) {
        var startTime = System.currentTimeMillis();
        var result = RemoteService.getRemoteService().doRemoteFunction(value);
        var timeTaken = System.currentTimeMillis() - startTime;

        LOGGER.info("Time taken (ms): " + timeTaken);
        return result;
    }

    private long safeCall(int value) {
        var retries = 0;
        var result = (long) FAILURE;

        for (int i = 0; i < RETRIES; i++) {
            if (retries >= RETRIES) {
                return FAILURE;
            }

            if ((result = checkLatency(value)) == FAILURE) {
                LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
                retries++;
                try {
                    sleep(DELAY_MS);
                } catch (InterruptedException e) {
                    LOGGER.error("Thread sleep state interrupted", e);
                }
            } else {
                break;
            }
        }
        return result;
    }
}
```

A client has a local service ambassador used to interact with the remote service.

```java

@Slf4j
public class Client {
    private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();

    long useService(int value) {
        var result = serviceAmbassador.doRemoteFunction(value);
        LOGGER.info("Service result: " + result);
        return result;
    }
}
```

Here are two clients using the service.

```java
public class App {
    public static void main(String[] args) {
        var host1 = new Client();
        var host2 = new Client();
        host1.useService(12);
        host2.useService(73);
    }
}
```

Here's the output for running the example:

```java
Time taken(ms):111
Service result:120
Time taken(ms):931
Failed to reach remote:(1)
Time taken(ms):665
Failed to reach remote:(2)
Time taken(ms):538
Failed to reach remote:(3)
Service result:-1
```

## [When to Use the Ambassador Pattern in Java](https://java-design-patterns.com/patterns/ambassador/#when-to-use-the-ambassador-pattern-in-java)

- The Ambassador Pattern is particularly beneficial for Cloud Native and Microservices Architectures in Java. It helps in monitoring, logging, and securing inter-service communication, making it ideal for distributed systems.
- Legacy System Integration: Facilitates communication with newer services by handling necessary but non-core functionalities.
- Performance Enhancement: Can be used to cache results or compress data to improve communication efficiency.

Typical use cases include:

- Control access to another object
- Implement logging
- Implement circuit breaking
- Offload remote service tasks
- Facilitate network connection

## [Benefits and Trade-offs of Ambassador Pattern](https://java-design-patterns.com/patterns/ambassador/#benefits-and-trade-offs-of-ambassador-pattern)

Benefits:

- Separation of Concerns: Offloads cross-cutting concerns from the service logic, leading to cleaner, more maintainable code.
- Reusable Infrastructure Logic: The ambassador pattern allows the same logic (e.g., logging, monitoring) to be reused across multiple services.
- Improved Security: Centralizes security features like SSL termination or authentication, reducing the risk of misconfiguration.
- Flexibility: Makes it easier to update or replace infrastructure concerns without modifying the service code.

Trade-offs:

- Increased Complexity: Adds another layer to the architecture, which can complicate the system design and debugging.
- Potential Performance Overhead: The additional network hop can introduce latency and overhead, particularly if not optimized.
- Deployment Overhead: Requires additional resources and management for deploying and scaling ambassador services.

## [Real-World Applications of Ambassador Pattern in Java](https://java-design-patterns.com/patterns/ambassador/#real-world-applications-of-ambassador-pattern-in-java)

- Service Mesh Implementations: In a service mesh architecture, like Istio or Linkerd, the Ambassador pattern is often employed as a sidecar proxy that handles inter-service communications. This includes tasks such as service discovery, routing, load balancing, telemetry (metrics and tracing), and security (authentication and authorization).
- API Gateways: API gateways can use the Ambassador pattern to encapsulate common functionalities like rate limiting, caching, request shaping, and authentication. This allows backend services to focus on their core business logic without being burdened by these cross-cutting concerns.
- Logging and Monitoring: An Ambassador can aggregate logs and metrics from various services and forward them to centralized monitoring tools like Prometheus or ELK Stack (Elasticsearch, Logstash, Kibana). This simplifies the logging and monitoring setup for each service and provides a unified view of the system's health.
- Security: Security-related functionalities such as SSL/TLS termination, identity verification, and encryption can be managed by an Ambassador. This ensures consistent security practices across services and reduces the likelihood of security breaches due to misconfigurations.
- Resilience: The Ambassador can implement resilience patterns like circuit breakers, retries, and timeouts. For instance, Netflix's Hystrix library can be used within an Ambassador to prevent cascading failures in a microservices ecosystem.
- Database Proxy: Ambassadors can act as proxies for database connections, providing functionalities like connection pooling, read/write splitting for replicas, and query caching. This offloads significant complexity from the application services.
- Legacy System Integration: In scenarios where modern microservices need to communicate with legacy systems, an Ambassador can serve as an intermediary that translates protocols, handles necessary transformations, and implements modern security practices, easing the integration process.
- Network Optimization: For services deployed across different geographical locations or cloud regions, Ambassadors can optimize communication by compressing data, batching requests, or even implementing smart routing to reduce latency and costs.
- [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador)

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/ambassador/#related-java-design-patterns)

- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Often used in conjunction to manage fault tolerance by stopping calls to an unresponsive service.
- [Decorator](https://java-design-patterns.com/patterns/decorator/): The decorator pattern is used to add functionality to an object dynamically, while the ambassador pattern is used to offload functionality to a separate object.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Shares similarities with the proxy pattern, but the ambassador pattern specifically focuses on offloading ancillary functionalities.
- Sidecar: A similar pattern used in the context of containerized applications, where a sidecar container provides additional functionality to the main application container.

## [References and Credits](https://java-design-patterns.com/patterns/ambassador/#references-and-credits)

- [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43aGpSR)
- [Cloud Native Patterns: Designing Change-tolerant Software](https://amzn.to/3wUAl4O)
- [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://amzn.to/3T9g9Uj)
- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
- [Ambassador pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador)

---

## [integration/anti-corruption-layer] Anti-Corruption Layer
> 官方文档: https://java-design-patterns.com/patterns/anti-corruption-layer/

IntegrationArchitectureDecouplingIntegrationIsolationLayered architectureMigrationModernizationRefactoringWrappingAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/anti-corruption-layer/#also-known-as)

- ACL
- Interface layer
- Translation layer

## [Intent of Anti-Corruption Layer Design Pattern](https://java-design-patterns.com/patterns/anti-corruption-layer/#intent-of-anti-corruption-layer-design-pattern)

The Anti-Corruption Layer (ACL) is a crucial design pattern in Java development, particularly for system integration and maintaining data integrity. Implement a façade or adapter layer between different subsystems that don't share the same semantics. It translates between different data formats and systems, ensuring that the integration between systems does not lead to corruption of business logic or data integrity.

## [Detailed Explanation of Anti-Corruption Layer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/anti-corruption-layer/#detailed-explanation-of-anti-corruption-layer-pattern-with-real-world-examples)

Real-world example

> This example demonstrates how the Anti-Corruption Layer ensures seamless integration between legacy systems and modern platforms, crucial for maintaining business logic integrity during system migration.
>
> Imagine a large retail company transitioning its inventory management system from an old legacy software to a new modern platform. The legacy system has been in use for decades and contains complex business rules and data formats that are incompatible with the new system. Instead of directly connecting the new system to the legacy one, the company implements an Anti-Corruption Layer (ACL).
>
> The ACL acts as a mediator, translating and adapting data between the two systems. When the new system requests inventory data, the ACL translates the request into a format the legacy system understands, retrieves the data, and then translates it back into a format suitable for the new system. This approach ensures that the new system remains unaffected by the intricacies of the legacy system, preventing corruption of data and business logic while facilitating a smooth transition.

In plain words

> The Anti-Corruption Layer design pattern protects a system from the complexities and changes of external systems by providing an intermediary translation layer.

[Microsoft's documentation](https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer) says

> Implement a façade or adapter layer between different subsystems that don't share the same semantics. This layer translates requests that one subsystem makes to the other subsystem. Use this pattern to ensure that an application's design is not limited by dependencies on outside subsystems. This pattern was first described by Eric Evans in Domain-Driven Design.

Sequence diagram

![Anti-Corruption Layer sequence diagram](https://java-design-patterns.com/assets/img/anti-corruption-layer-sequence-diagram.79bfaa6e.png)

## [Programmatic Example of Anti-Corruption Layer Pattern in Java](https://java-design-patterns.com/patterns/anti-corruption-layer/#programmatic-example-of-anti-corruption-layer-pattern-in-java)

The ACL design pattern in Java provides an intermediary layer that translates data formats, ensuring that integration between different systems does not lead to data corruption.

Here are 2 shop-ordering systems: `Legacy` and `Modern`.

The aforementioned systems have different domain models and have to operate simultaneously. Since they work independently the orders can come either from the `Legacy` or `Modern` system. Therefore, the system that receives the legacyOrder needs to check if the legacyOrder is valid and not present in the other system. Then it can place the legacyOrder in its own system.

But for that, the system needs to know the domain model of the other system and to avoid that, the anti-corruption layer(ACL) is introduced. The ACL is a layer that translates the domain model of the `Legacy` system to the domain model of the `Modern` system and vice versa. Also, it hides all other operations with the other system, uncoupling the systems.

Domain model of the `Legacy` system:

```java
public class LegacyOrder {
    private String id;
    private String customer;
    private String item;
    private String qty;
    private String price;
}
```

Domain model of the `Modern` system:

```java
public class ModernOrder {
    private String id;
    private Customer customer;

    private Shipment shipment;

    private String extra;
}

public class Customer {
    private String address;
}

public class Shipment {
    private String item;
    private String qty;
    private String price;
}
```

Anti-corruption layer:

```java
public class AntiCorruptionLayer {

    @Autowired
    private ModernShop modernShop;

    @Autowired
    private LegacyShop legacyShop;

    public Optional<LegacyOrder> findOrderInModernSystem(String id) {
        return modernShop.findOrder(id).map(o -> /* map to legacyOrder*/);
    }

    public Optional<ModernOrder> findOrderInLegacySystem(String id) {
        return legacyShop.findOrder(id).map(o -> /* map to modernOrder*/);
    }

}
```

The connection between the systems. Wherever the `Legacy` or `Modern` system needs to communicate with the counterpart the ACL needs to be used to avoid corrupting the current domain model. The example below shows how the `Legacy` system places an order with a validation from the `Modern` system.

```java
public class LegacyShop {
    @Autowired
    private AntiCorruptionLayer acl;

    public void placeOrder(LegacyOrder legacyOrder) throws ShopException {

        String id = legacyOrder.getId();

        Optional<ModernOrder> orderInModernSystem = acl.findOrderInModernSystem(id);

        if (orderInModernSystem.isPresent()) {
            // order is already in the modern system
        } else {
            // place order in the current system
        }
    }
}
```

## [When to Use the Anti-Corruption Layer Pattern in Java](https://java-design-patterns.com/patterns/anti-corruption-layer/#when-to-use-the-anti-corruption-layer-pattern-in-java)

Use this pattern when:

- A migration is planned to happen over multiple stages, but integration between new and legacy systems needs to be maintained
- Two or more subsystems have different semantics, but still need to communicate
- When integrating with legacy systems or external systems where direct integration might pollute the domain model of the new system
- In scenarios where different subsystems within a larger system use different data formats or structures
- When there is a need to ensure loose coupling between different subsystems or external services to facilitate easier maintenance and scalability

## [Anti-Corruption Layer Pattern Java Tutorials](https://java-design-patterns.com/patterns/anti-corruption-layer/#anti-corruption-layer-pattern-java-tutorials)

- [Anti-Corruption Layer (Microsoft)](https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer)
- [Anti-Corruption Layer Pattern (Amazon)](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/acl.html)

## [Real-World Applications of Anti-Corruption Layer Pattern in Java](https://java-design-patterns.com/patterns/anti-corruption-layer/#real-world-applications-of-anti-corruption-layer-pattern-in-java)

- Microservices architectures where individual services must communicate without being tightly coupled to each other’s data schemas
- Enterprise systems integration, especially when integrating modern systems with legacy systems
- In bounded contexts within Domain-Driven Design (DDD) to maintain the integrity of a domain model when interacting with external systems or subsystems

## [Benefits and Trade-offs of Anti-Corruption Layer Pattern](https://java-design-patterns.com/patterns/anti-corruption-layer/#benefits-and-trade-offs-of-anti-corruption-layer-pattern)

Benefits:

- Protects the integrity of the domain model by providing a clear boundary
- Promotes loose coupling between systems, making the system more resilient to changes in external systems
- Facilitates cleaner and more maintainable code by isolating integration code from business logic

Trade-offs:

- Introduces additional complexity and potential performance overhead due to the translation process
- Requires extra effort in design and implementation to ensure the layer is effective without becoming a bottleneck
- Can lead to duplication of models if not carefully managed

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/anti-corruption-layer/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): The Anti-Corruption Layer can be implemented using the Adapter pattern to translate between different data formats or structures
- [Facade](https://java-design-patterns.com/patterns/facade/): The Anti-Corruption Layer can be seen as a specialized form of the Facade pattern that is used to isolate different subsystems
- [Gateway](https://java-design-patterns.com/patterns/gateway/): The Anti-Corruption Layer can be used as a Gateway to external systems to provide a unified interface

## [References and Credits](https://java-design-patterns.com/patterns/anti-corruption-layer/#references-and-credits)

- [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://amzn.to/3vptcJz)
- [Implementing Domain-Driven Design](https://amzn.to/3ISOSRA)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [integration/gateway] Gateway
> 官方文档: https://java-design-patterns.com/patterns/gateway/

IntegrationAPI designData accessDecouplingEnterprise patternsAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/gateway/#also-known-as)

- Service Gateway

## [Intent of Gateway Design Pattern](https://java-design-patterns.com/patterns/gateway/#intent-of-gateway-design-pattern)

The Gateway design pattern is a crucial concept in Java design patterns for simplifying API integration and interactions with remote services. It provides a unified and simplified interface to external systems, enhancing the maintainability and architecture of applications. By encapsulating these interactions, the Gateway pattern ensures loose coupling and promotes a more modular and scalable software design, making it essential for robust and efficient application development.

## [Detailed Explanation of Gateway Pattern with Real-World Examples](https://java-design-patterns.com/patterns/gateway/#detailed-explanation-of-gateway-pattern-with-real-world-examples)

Real-world example

> In real-world applications, companies often need to interact with multiple external systems. The Gateway design pattern provides a unified interface for such interactions, handling protocol translation and data transformation, thereby ensuring loose coupling between the internal and external components. '
>
> Consider a logistics company that uses multiple third-party services for various operations, such as shipping, inventory management, and customer notifications. Each of these services has its own API with different protocols and data formats. To simplify the interaction, the company implements a Gateway design pattern. This gateway acts as a unified interface for all third-party service interactions, allowing the company's internal systems to communicate with these services seamlessly. The gateway handles the translation of protocols, data transformation, and routing of requests, ensuring that the internal systems remain decoupled from the specifics of each external service. This setup improves maintainability and scalability while providing a single point of control for external communications.

In plain words

> Gateway can provide an interface which lets internal system to utilize external service.

Wikipedia says

> A server that acts as an API front-end, receives API requests, enforces throttling and security policies, passes requests to the back-end service and then passes the response back to the requester.

Sequence diagram

![Gateway sequence diagram](https://java-design-patterns.com/assets/img/gateway-sequence-diagram.c474989d.png)

## [Programmatic Example of Gateway Pattern in Java](https://java-design-patterns.com/patterns/gateway/#programmatic-example-of-gateway-pattern-in-java)

First, we define a `Gateway` interface. This interface represents the contract for our external services. Each service that we want to interact with will implement this interface.

```java
public interface Gateway {
  void execute();
}
```

Next, we create our external services. These are the services that our application needs to interact with. Each service implements the `Gateway` interface and provides its own implementation of the `execute` method.

```java
public class ExternalServiceA implements Gateway {
  @Override
  public void execute() {
    // Implementation for ExternalServiceA
  }
}
```

```java
public class ExternalServiceB implements Gateway {
  @Override
  public void execute() {
    // Implementation for ExternalServiceB
  }
}
```

```java
public class ExternalServiceC implements Gateway {
  @Override
  public void execute() {
    // Implementation for ExternalServiceC
  }
}
```

We then create a `GatewayFactory` class. This class maintains a registry of all available gateways. It provides methods to register a new gateway and to retrieve a gateway by its key.

```java
public class GatewayFactory {
  private Map<String, Gateway> gateways = new HashMap<>();

  public void registerGateway(String key, Gateway gateway) {
    gateways.put(key, gateway);
  }

  public Gateway getGateway(String key) {
    return gateways.get(key);
  }
}
```

Finally, we have our main application. The application uses the `GatewayFactory` to register and retrieve gateways. It then uses these gateways to interact with the external services.

```java
public class App {
  public static void main(String[] args) throws Exception {
    GatewayFactory gatewayFactory = new GatewayFactory();

    // Register different gateways
    gatewayFactory.registerGateway("ServiceA", new ExternalServiceA());
    gatewayFactory.registerGateway("ServiceB", new ExternalServiceB());
    gatewayFactory.registerGateway("ServiceC", new ExternalServiceC());

    // Use an executor service for execution
    Gateway serviceA = gatewayFactory.getGateway("ServiceA");
    Gateway serviceB = gatewayFactory.getGateway("ServiceB");
    Gateway serviceC = gatewayFactory.getGateway("ServiceC");

    // Execute external services
    try {
      serviceA.execute();
      serviceB.execute();
      serviceC.execute();
    } catch (ThreadDeath e) {
      LOGGER.info("Interrupted!" + e);
      throw e;
    }
  }
}
```

Running the example produces the following output.

```
09:24:44.030 [main] INFO com.iluwatar.gateway.ExternalServiceA -- Executing Service A
09:24:45.038 [main] INFO com.iluwatar.gateway.ExternalServiceB -- Executing Service B
09:24:46.043 [main] INFO com.iluwatar.gateway.ExternalServiceC -- Executing Service C
```

This example demonstrates how the Gateway design pattern can be used to simplify the interaction with multiple external services. Each service is encapsulated behind a common interface, and the application interacts with this interface rather than directly with the services. This reduces coupling and makes the application easier to maintain and extend.

## [When to Use the Gateway Pattern in Java](https://java-design-patterns.com/patterns/gateway/#when-to-use-the-gateway-pattern-in-java)

Use the Gateway pattern when integrating with remote services or APIs. It is particularly beneficial in microservices architecture to manage communication through well-defined interfaces.

## [Real-World Applications of Gateway Pattern in Java](https://java-design-patterns.com/patterns/gateway/#real-world-applications-of-gateway-pattern-in-java)

- API Gateways in Microservices: Acts as an intermediary that processes incoming requests from clients, directing them to appropriate services within a microservices architecture.
- Database Gateways: Provides a unified interface to access data from various database systems, hiding the specifics of database querying and data retrieval.

## [Benefits and Trade-offs of Gateway Pattern](https://java-design-patterns.com/patterns/gateway/#benefits-and-trade-offs-of-gateway-pattern)

Benefits:

- The Gateway design pattern reduces complexity by abstracting the details of external APIs and services behind a simpler interface.
- Promotes loose coupling between the application and its dependencies on external systems.
- Makes the system easier to test and maintain.

Trade-offs:

- Introduces an additional layer that could potentially impact performance.
- Requires careful design to avoid creating a monolithic gateway that becomes a bottleneck.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/gateway/#related-java-design-patterns)

- [Facade](https://java-design-patterns.com/patterns/facade/): Similar to Gateway in abstracting complex subsystems, but Gateway specifically targets external or remote interfaces.
- [Adapter](https://java-design-patterns.com/patterns/adapter/): While both patterns provide a different interface to a subsystem, Gateway focuses more on networked data sources and services.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Often used together, as both can control and manage access to another object, but Gateway specifically deals with external services.
- [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): Often considered a specialization of the Gateway pattern, it specifically manages API requests and routes them to the appropriate services within a backend system.

## [References and Credits](https://java-design-patterns.com/patterns/gateway/#references-and-credits)

- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Gateway (Martin Fowler)](https://martinfowler.com/articles/gateway-pattern.html)

---

## [integration/microservices-api-gateway] Microservices API Gateway
> 官方文档: https://java-design-patterns.com/patterns/microservices-api-gateway/

IntegrationAPI designCloud distributedDecouplingEnterprise patternsIntegrationMicroservicesScalabilitySecurityAbout 3 min

* * *

## [Intent of Microservices API Gateway Design Pattern](https://java-design-patterns.com/patterns/microservices-api-gateway/#intent-of-microservices-api-gateway-design-pattern)

The API Gateway design pattern aims to provide a unified interface to a set of microservices within a microservices architecture. It acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results, thereby simplifying the client-side code.

## [Also known as](https://java-design-patterns.com/patterns/microservices-api-gateway/#also-known-as)

- API Facade
- Backend for Frontends (BFF)

## [Detailed Explanation of Microservices API Gateway Pattern with Real-World Examples](https://java-design-patterns.com/patterns/microservices-api-gateway/#detailed-explanation-of-microservices-api-gateway-pattern-with-real-world-examples)

Real-world example

> In a large e-commerce platform, an API Gateway is used as the single entry point for all client requests, simplifying client-side development. When a user visits the site or uses the mobile app, their requests for product information, user authentication, order processing, and payment are all routed through the API Gateway. The API Gateway handles tasks such as user authentication, rate limiting to prevent abuse, and logging for monitoring purposes, enhancing overall security optimization. This setup simplifies the client interface and ensures that all backend microservices can evolve independently without affecting the client directly, thereby enhancing microservices communication. This also enhances security by providing a centralized point to enforce policies and monitor traffic.

In plain words

> For a system implemented using microservices architecture, API Gateway is the single entry point that aggregates the calls to the individual microservices.

Wikipedia says

> API Gateway is a server that acts as an API front-end, receives API requests, enforces throttling and security policies, passes requests to the back-end service and then passes the response back to the requester. A gateway often includes a transformation engine to orchestrate and modify the requests and responses on the fly. A gateway can also provide functionality such as collecting analytics data and providing caching. The gateway can provide functionality to support authentication, authorization, security, audit and regulatory compliance.

Sequence diagram

![Microservices API Gateway sequence diagram](https://java-design-patterns.com/assets/img/microservices-api-gateway-sequence-diagram.51d818d9.png)

## [Programmatic Example of Microservice API Gateway in Java](https://java-design-patterns.com/patterns/microservices-api-gateway/#programmatic-example-of-microservice-api-gateway-in-java)

This implementation shows what the API Gateway pattern could look like for an e-commerce site. The`ApiGateway` makes calls to the Image and Price microservices using the `ImageClientImpl` and `PriceClientImpl` respectively. Customers viewing the site on a desktop device can see both price information and an image of a product, so the `ApiGateway` calls both of the microservices and aggregates the data in the `DesktopProduct` model. However, mobile users only see price information; they do not see a product image. For mobile users, the `ApiGateway` only retrieves price information, which it uses to populate the `MobileProduct`.

Here's the Image microservice implementation.

```java
public interface ImageClient {
    String getImagePath();
}

public class ImageClientImpl implements ImageClient {
    @Override
    public String getImagePath() {
        var httpClient = HttpClient.newHttpClient();
        var httpGet = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("http://localhost:50005/image-path"))
                .build();

        try {
            var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
            return httpResponse.body();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return null;
    }
}
```

Here's the Price microservice implementation.

```java
public interface PriceClient {
    String getPrice();
}

public class PriceClientImpl implements PriceClient {

    @Override
    public String getPrice() {
        var httpClient = HttpClient.newHttpClient();
        var httpGet = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("http://localhost:50006/price"))
                .build();

        try {
            var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
            return httpResponse.body();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return null;
    }
}
```

Here we can see how API Gateway maps the requests to the microservices.

```java
public class ApiGateway {

    @Resource
    private ImageClient imageClient;

    @Resource
    private PriceClient priceClient;

    @RequestMapping(path = "/desktop", method = RequestMethod.GET)
    public DesktopProduct getProductDesktop() {
        var desktopProduct = new DesktopProduct();
        desktopProduct.setImagePath(imageClient.getImagePath());
        desktopProduct.setPrice(priceClient.getPrice());
        return desktopProduct;
    }

    @RequestMapping(path = "/mobile", method = RequestMethod.GET)
    public MobileProduct getProductMobile() {
        var mobileProduct = new MobileProduct();
        mobileProduct.setPrice(priceClient.getPrice());
        return mobileProduct;
    }
}
```

## [When to Use the Microservices API Gateway Pattern in Java](https://java-design-patterns.com/patterns/microservices-api-gateway/#when-to-use-the-microservices-api-gateway-pattern-in-java)

- When building a microservices architecture, and there's a need to abstract the complexity of microservices from the client.
- When multiple microservices need to be consumed in a single request.
- For authentication, authorization, and security enforcement at a single point.
- To optimize communication between clients and services, especially in a cloud environment.

## [Microservices API Gateway Pattern Java Tutorials](https://java-design-patterns.com/patterns/microservices-api-gateway/#microservices-api-gateway-pattern-java-tutorials)

- [Exploring the New Spring Cloud Gateway (Baeldung)](https://www.baeldung.com/spring-cloud-gateway)
- [Spring Cloud - Gateway(tutorialspoint)](https://www.tutorialspoint.com/spring_cloud/spring_cloud_gateway.htm)
- [Getting Started With Spring Cloud Gateway (DZone)](https://dzone.com/articles/getting-started-with-spring-cloud-gateway)

## [Benefits and Trade-offs of Microservices API Gateway Pattern](https://java-design-patterns.com/patterns/microservices-api-gateway/#benefits-and-trade-offs-of-microservices-api-gateway-pattern)

Benefits:

- Decouples client from microservices, allowing services to evolve independently.
- Simplifies client by aggregating requests to multiple services.
- Centralized location for cross-cutting concerns like security, logging, and rate limiting.
- Potential for performance optimizations like caching and request compression.

Trade-offs:

- Introduces a single point of failure, although this can be mitigated with high availability setups.
- Can become a bottleneck if not properly scaled.
- Adds complexity in terms of deployment and management.

## [Real-World Applications of Microservices API Gateway Pattern in Java](https://java-design-patterns.com/patterns/microservices-api-gateway/#real-world-applications-of-microservices-api-gateway-pattern-in-java)

- E-commerce platforms where multiple services (product info, pricing, inventory) are aggregated for a single view.
- Mobile applications that consume various backend services but require a simplified interface for ease of use.
- Cloud-native applications that leverage multiple microservices architectures.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/microservices-api-gateway/#related-java-design-patterns)

- [Aggregator Microservice](https://java-design-patterns.com/patterns/microservices-aggregator/) \- The API Gateway pattern is often used in conjunction with the Aggregator Microservice pattern to provide a unified interface to a set of microservices.
- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/) \- API Gateways can use the Circuit Breaker pattern to prevent cascading failures when calling multiple microservices.
- [Proxy](https://java-design-patterns.com/patterns/proxy/) \- The API Gateway pattern is a specialized form of the Proxy pattern, where the gateway acts as a single entry point for clients, routing requests to the appropriate microservices and aggregating results.

## [References and Credits](https://java-design-patterns.com/patterns/microservices-api-gateway/#references-and-credits)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Cloud Native Patterns: Designing change-tolerant software](https://amzn.to/3uV12WN)
- [Designing Data-Intensive Applications](https://amzn.to/3PfRk7Y)
- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
- [API Gateway (microservices.io)](http://microservices.io/patterns/apigateway.html)
- [Building Microservices: Using an API Gateway (nginx)](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/)

---

## [integration/microservices-log-aggregation] Microservices Log Aggregation
> 官方文档: https://java-design-patterns.com/patterns/microservices-log-aggregation/

IntegrationData processingDecouplingEnterprise patternsFault toleranceMessagingMicroservicesPerformanceScalabilityAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/microservices-log-aggregation/#also-known-as)

- Centralized Logging
- Log Management

## [Intent of Microservices Log Aggregation Design Pattern](https://java-design-patterns.com/patterns/microservices-log-aggregation/#intent-of-microservices-log-aggregation-design-pattern)

Log Aggregation is a crucial microservices design pattern that centralizes the collection, storage, and analysis of logs from multiple sources, facilitating efficient monitoring, debugging, and operational intelligence.

## [Detailed Explanation of Microservices Log Aggregation Pattern with Real-World Examples](https://java-design-patterns.com/patterns/microservices-log-aggregation/#detailed-explanation-of-microservices-log-aggregation-pattern-with-real-world-examples)

Real-world example

> Imagine an e-commerce platform using a microservices architecture, where each service generates logs. A log aggregation system, utilizing tools like the ELK Stack (Elasticsearch, Logstash, Kibana), centralizes these logs. This setup allows administrators to effectively monitor and analyze the entire platform's activity in real-time. By collecting logs from each microservice and centralizing them, the system provides a unified view, enabling quick troubleshooting and comprehensive analysis of user behavior and system performance.

In plain words

> The Log Aggregation design pattern centralizes the collection and analysis of log data from multiple applications or services to simplify monitoring and troubleshooting.

Wikipedia says

> You have applied the Microservice architecture pattern. The application consists of multiple services and service instances that are running on multiple machines. Requests often span multiple service instances. Each service instance generates writes information about what it is doing to a log file in a standardized format. The log file contains errors, warnings, information and debug messages.

Flowchart

![Microservices Log Aggregration flowchart](https://java-design-patterns.com/assets/img/microservices-log-aggregation-flowchart.070a954a.png)

## [Programmatic Example of Microservices Log Aggregation Pattern in Java](https://java-design-patterns.com/patterns/microservices-log-aggregation/#programmatic-example-of-microservices-log-aggregation-pattern-in-java)

Log Aggregation is a pattern that centralizes the collection, storage, and analysis of logs from multiple sources to facilitate monitoring, debugging, and operational intelligence. It is particularly useful in distributed systems where logs from various components need to be centralized for better management and analysis.

In this example, we will demonstrate the Log Aggregation pattern using a simple Java application. The application consists of multiple services that generate logs. These logs are collected by a log aggregator and stored in a central log store.

The `CentralLogStore` is responsible for storing the logs collected from various services. In this example, we are using an in-memory store for simplicity.

```java
public class CentralLogStore {

  private final List<LogEntry> logs = new ArrayList<>();

  public void storeLog(LogEntry logEntry) {
    logs.add(logEntry);
  }

  public void displayLogs() {
    logs.forEach(System.out::println);
  }
}
```

The `LogAggregator` collects logs from various services and stores them in the `CentralLogStore`. It filters logs based on their log level.

```java
public class LogAggregator {

  private final CentralLogStore centralLogStore;
  private final LogLevel minimumLogLevel;

  public LogAggregator(CentralLogStore centralLogStore, LogLevel minimumLogLevel) {
    this.centralLogStore = centralLogStore;
    this.minimumLogLevel = minimumLogLevel;
  }

  public void collectLog(LogEntry logEntry) {
    if (logEntry.getLogLevel().compareTo(minimumLogLevel) >= 0) {
      centralLogStore.storeLog(logEntry);
    }
  }
}
```

The `LogProducer` represents a service that generates logs. It sends the logs to the `LogAggregator`.

```java
public class LogProducer {

  private final String serviceName;
  private final LogAggregator logAggregator;

  public LogProducer(String serviceName, LogAggregator logAggregator) {
    this.serviceName = serviceName;
    this.logAggregator = logAggregator;
  }

  public void generateLog(LogLevel logLevel, String message) {
    LogEntry logEntry = new LogEntry(serviceName, logLevel, message, LocalDateTime.now());
    logAggregator.collectLog(logEntry);
  }
}
```

The `main` application creates services, generates logs, aggregates, and finally displays the logs.

```java
public class App {

  public static void main(String[] args) throws InterruptedException {
    final CentralLogStore centralLogStore = new CentralLogStore();
    final LogAggregator aggregator = new LogAggregator(centralLogStore, LogLevel.INFO);

    final LogProducer serviceA = new LogProducer("ServiceA", aggregator);
    final LogProducer serviceB = new LogProducer("ServiceB", aggregator);

    serviceA.generateLog(LogLevel.INFO, "This is an INFO log from ServiceA");
    serviceB.generateLog(LogLevel.ERROR, "This is an ERROR log from ServiceB");
    serviceA.generateLog(LogLevel.DEBUG, "This is a DEBUG log from ServiceA");

    centralLogStore.displayLogs();
  }
}
```

In this example, the `LogProducer` services generate logs of different levels. The `LogAggregator` collects these logs and stores them in the `CentralLogStore` if they meet the minimum log level requirement. Finally, the logs are displayed by the `CentralLogStore`.

## [When to Use the Microservices Log Aggregation Pattern in Java](https://java-design-patterns.com/patterns/microservices-log-aggregation/#when-to-use-the-microservices-log-aggregation-pattern-in-java)

- Microservices log aggregation is essential in distributed systems for better management and analysis of log data.
- Applicable in environments where compliance and auditing require consolidated log data.
- Beneficial in systems that require high availability and resilience, ensuring that log data is preserved and accessible despite individual component failures.

## [Real-World Applications of Microservices Log Aggregation Pattern in Java](https://java-design-patterns.com/patterns/microservices-log-aggregation/#real-world-applications-of-microservices-log-aggregation-pattern-in-java)

- ava applications using frameworks like Log4j2 or SLF4J with centralized log management tools such as the ELK stack or Splunk benefit from microservices log aggregation.
- Microservices architectures where each service outputs logs that are aggregated into a single system to provide a unified view of the system’s health and behavior.

## [Benefits and Trade-offs of Microservices Log Aggregation Pattern](https://java-design-patterns.com/patterns/microservices-log-aggregation/#benefits-and-trade-offs-of-microservices-log-aggregation-pattern)

Benefits:

- Centralizing logs in a microservices environment improves debuggability and traceability across multiple services.
- Enhances monitoring capabilities by providing a centralized platform for log analysis.
- Facilitates compliance with regulatory requirements for log retention and auditability.

Trade-offs:

- Introduces a potential single point of failure if the log aggregation system is not adequately resilient.
- Can lead to high data volumes requiring significant storage and processing resources.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/microservices-log-aggregation/#related-java-design-patterns)

- Messaging Patterns: Log Aggregation often utilizes messaging systems to transport log data, facilitating decoupling and asynchronous data processing.
- Microservices: Often employed in microservice architectures to handle logs from various services efficiently.
- Publish/Subscribe: Utilizes a pub/sub model for log data collection where components publish logs and the aggregation system subscribes to them.

## [References and Credits](https://java-design-patterns.com/patterns/microservices-log-aggregation/#references-and-credits)

- [Cloud Native Java: Designing Resilient Systems with Spring Boot, Spring Cloud, and Cloud Foundry](https://amzn.to/44vDTat)
- [Logging in Action: With Fluentd, Kubernetes and more](https://amzn.to/3JQLzdT)
- [Release It! Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF)
- [Pattern: Log aggregation (microservices.io)](https://microservices.io/patterns/observability/application-logging.html)

---

<!-- ============================================ -->
<!-- Resilience 弹性模式 (5 个) -->
<!-- ============================================ -->

## [resilience/circuit-breaker] Circuit Breaker
> 官方文档: https://java-design-patterns.com/patterns/circuit-breaker/

ResilienceCloud distributedFault toleranceMicroservicesRetryAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/circuit-breaker/#also-known-as)

- Fault Tolerance Switch

## [Intent of Circuit Breaker Design Pattern](https://java-design-patterns.com/patterns/circuit-breaker/#intent-of-circuit-breaker-design-pattern)

The Circuit Breaker pattern is a critical Java design pattern that helps ensure fault tolerance and resilience in microservices and distributed systems. Using Circuit Breaker, it is possible to prevent a system from repeatedly trying to execute an operation likely to fail, allowing it to recover from faults and prevent cascading failures.

## [Detailed Explanation of Circuit Breaker Pattern with Real-World Examples](https://java-design-patterns.com/patterns/circuit-breaker/#detailed-explanation-of-circuit-breaker-pattern-with-real-world-examples)

Real-world example

> Consider a real-world example of an e-commerce website that depends on multiple external payment gateways to process transactions. If one of the payment gateways becomes unresponsive or slow, the Circuit Breaker pattern can be used to detect the failure and prevent the system from repeatedly attempting to use the problematic gateway. Instead, it can quickly switch to alternative payment gateways or display an error message to the user, ensuring that the rest of the website remains functional and responsive. This avoids resource exhaustion and provides a better user experience by allowing transactions to be processed through other available services. This way, the Circuit Breaker pattern handles external API failures, ensuring the system remains functional.

In plain words

> Circuit Breaker allows graceful handling of failed remote services. It's especially useful when all parts of our application are highly decoupled from each other, and failure of one component doesn't mean the other parts will stop working.

Wikipedia says

> Circuit breaker is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.

Flowchart

![Circuit Breaker flowchart](https://java-design-patterns.com/assets/img/circuit-breaker-flowchart.34a2cf13.png)

## [Programmatic Example of Circuit Breaker Pattern in Java](https://java-design-patterns.com/patterns/circuit-breaker/#programmatic-example-of-circuit-breaker-pattern-in-java)

This Java example demonstrates how the Circuit Breaker pattern can manage remote service failures and maintain system stability.

Imagine a web application that uses both local files/images and remote services to fetch data. Remote services can become slow or unresponsive, which may cause the application to hang due to thread starvation. The Circuit Breaker pattern can help detect such failures and allow the application to degrade gracefully.

1. **Simulating a Delayed Remote Service**

```java
// The DelayedRemoteService simulates a remote service that responds after a certain delay.
var delayedService = new DelayedRemoteService(serverStartTime, 5);
```

2. **Setting Up the Circuit Breaker**

```java
// The DefaultCircuitBreaker wraps the remote service and monitors for failures.
var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2, 2000 * 1000 * 1000);
```

3. **Monitoring Service to Handle Requests**

```java
// The MonitoringService is responsible for calling the remote services.
var monitoringService = new MonitoringService(delayedServiceCircuitBreaker, quickServiceCircuitBreaker);

// Fetch response from local resource
LOGGER.info(monitoringService.localResourceResponse());

// Fetch response from delayed service 2 times to meet the failure threshold
LOGGER.info(monitoringService.delayedServiceResponse());
LOGGER.info(monitoringService.delayedServiceResponse());
```

4. **Handling Circuit Breaker States**

```java
// Fetch current state of delayed service circuit breaker after crossing failure threshold limit
LOGGER.info(delayedServiceCircuitBreaker.getState()); // Should be OPEN

// Meanwhile, the delayed service is down, fetch response from the healthy quick service
LOGGER.info(monitoringService.quickServiceResponse());
LOGGER.info(quickServiceCircuitBreaker.getState());
```

5. **Recovering from Failure**

```java
// Wait for the delayed service to become responsive
try {
  LOGGER.info("Waiting for delayed service to become responsive");
  Thread.sleep(5000);
} catch (InterruptedException e) {
  LOGGER.error("An error occurred: ", e);
}

// Check the state of delayed circuit breaker, should be HALF_OPEN
LOGGER.info(delayedServiceCircuitBreaker.getState());

// Fetch response from delayed service, which should be healthy by now
LOGGER.info(monitoringService.delayedServiceResponse());

// As successful response is fetched, it should be CLOSED again.
LOGGER.info(delayedServiceCircuitBreaker.getState());
```

6. **Full example**

```java
public static void main(String[] args) {

    var serverStartTime = System.nanoTime();

    var delayedService = new DelayedRemoteService(serverStartTime, 5);
    var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2,
        2000 * 1000 * 1000);

    var quickService = new QuickRemoteService();
    var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2,
        2000 * 1000 * 1000);

    //Create an object of monitoring service which makes both local and remote calls
    var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,
        quickServiceCircuitBreaker);

    //Fetch response from local resource
    LOGGER.info(monitoringService.localResourceResponse());

    //Fetch response from delayed service 2 times, to meet the failure threshold
    LOGGER.info(monitoringService.delayedServiceResponse());
    LOGGER.info(monitoringService.delayedServiceResponse());

    //Fetch current state of delayed service circuit breaker after crossing failure threshold limit
    //which is OPEN now
    LOGGER.info(delayedServiceCircuitBreaker.getState());

    //Meanwhile, the delayed service is down, fetch response from the healthy quick service
    LOGGER.info(monitoringService.quickServiceResponse());
    LOGGER.info(quickServiceCircuitBreaker.getState());

    //Wait for the delayed service to become responsive
    try {
      LOGGER.info("Waiting for delayed service to become responsive");
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      LOGGER.error("An error occurred: ", e);
    }
    //Check the state of delayed circuit breaker, should be HALF_OPEN
    LOGGER.info(delayedServiceCircuitBreaker.getState());

    //Fetch response from delayed service, which should be healthy by now
    LOGGER.info(monitoringService.delayedServiceResponse());
    //As successful response is fetched, it should be CLOSED again.
    LOGGER.info(delayedServiceCircuitBreaker.getState());
}
```

Summary of the example

- Initialize the Circuit Breaker with parameters: `timeout`, `failureThreshold`, and `retryTimePeriod`.
- Start in the `closed` state.
- On successful calls, reset the state.
- On failures exceeding the threshold, transition to the `open` state to prevent further calls.
- After the retry timeout, transition to the `half-open` state to test the service.
- On success in `half-open` state, transition back to `closed`. On failure, return to `open`.

Program output:

```
16:59:19.767 [main] INFO com.iluwatar.circuitbreaker.App -- Local Service is working
16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Delayed service is down
16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Delayed service is down
16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- OPEN
16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Quick Service is working
16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- CLOSED
16:59:19.769 [main] INFO com.iluwatar.circuitbreaker.App -- Waiting for delayed service to become responsive
16:59:24.779 [main] INFO com.iluwatar.circuitbreaker.App -- HALF_OPEN
16:59:24.780 [main] INFO com.iluwatar.circuitbreaker.App -- Delayed service is working
16:59:24.780 [main] INFO com.iluwatar.circuitbreaker.App -- CLOSED
```

This example demonstrates how the Circuit Breaker pattern can help maintain application stability and resilience by managing remote service failures.

## [When to Use the Circuit Breaker Pattern in Java](https://java-design-patterns.com/patterns/circuit-breaker/#when-to-use-the-circuit-breaker-pattern-in-java)

The Circuit Breaker pattern is applicable:

- In distributed systems where individual service failures can lead to cascading system-wide failures
- For applications that interact with third-party services or databases that might become unresponsive or slow
- In microservices architectures where the failure of one service can affect the availability of others

## [Real-World Applications of Circuit Breaker Pattern in Java](https://java-design-patterns.com/patterns/circuit-breaker/#real-world-applications-of-circuit-breaker-pattern-in-java)

- Cloud-based services to gracefully handle the failure of external services
- E-commerce platforms to manage high volumes of transactions and dependency on external APIs
- Microservices architectures for maintaining system stability and responsiveness
- [Spring Circuit Breaker module](https://spring.io/guides/gs/cloud-circuit-breaker)
- [Netflix Hystrix API](https://github.com/Netflix/Hystrix)

## [Benefits and Trade-offs of Circuit Breaker Pattern](https://java-design-patterns.com/patterns/circuit-breaker/#benefits-and-trade-offs-of-circuit-breaker-pattern)

Benefits:

- Prevents the system from performing futile operations that are likely to fail, thus saving resources
- Helps in maintaining the system stability and performance of the application during partial system failures
- Facilitates faster system recovery by avoiding the overwhelming of failing services with repeated requests

Trade-Offs:

- The complexity of the system increases as the pattern requires additional logic to detect failures and manage the state of the circuit breaker
- May lead to system degradation if not properly configured, as legitimate requests might be blocked if the circuit is open
- Requires careful tuning of thresholds and timeout periods to balance between responsiveness and protection

## [Related Patterns](https://java-design-patterns.com/patterns/circuit-breaker/#related-patterns)

- Bulkhead: Can be used to isolate different parts of the system to prevent failures from spreading across the system
- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry): Can be used in conjunction with the Circuit Breaker pattern to retry failed operations before opening the circuit

## [References and Credits](https://java-design-patterns.com/patterns/circuit-breaker/#references-and-credits)

- [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/43Dx86g)
- [Microservices Patterns: With examples in Java](https://amzn.to/3xaZwk0)
- [Release It! Design and Deploy Production-Ready Software](https://amzn.to/4aqTNEP)
- [Understand CircuitBreaker Design Pattern with Simple Practical Example (ITNEXT)](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42)
- [Circuit Breaker (Martin Fowler)](https://martinfowler.com/bliki/CircuitBreaker.html)
- [Fault tolerance in a high volume, distributed system (Netflix)](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a)
- [Circuit Breaker pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker)

---

## [resilience/queue-based-load-leveling] Queue-Based Load Leveling
> 官方文档: https://java-design-patterns.com/patterns/queue-based-load-leveling/

ResilienceAsynchronousBufferingDecouplingFault toleranceMessagingScalabilitySynchronizationThread managementAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/queue-based-load-leveling/#also-known-as)

- Load Leveling
- Message Queuing

## [Intent of Queue-Based Load Leveling Design Pattern](https://java-design-patterns.com/patterns/queue-based-load-leveling/#intent-of-queue-based-load-leveling-design-pattern)

The Queue-Based Load Leveling pattern expertly manages system load balancing in Java by utilizing a queue to efficiently distribute the workload among producers and consumers, enhancing system performance and scalability.

## [Detailed Explanation of Queue-Based Load Leveling Pattern with Real-World Examples](https://java-design-patterns.com/patterns/queue-based-load-leveling/#detailed-explanation-of-queue-based-load-leveling-pattern-with-real-world-examples)

Real-world example

> In a practical scenario, akin to a bustling restaurant, Queue-Based Load Leveling serves as a system optimization strategy, where orders are systematically queued to maintain high service quality and efficiency. During peak hours, if all customers were served immediately, the kitchen would be overwhelmed, leading to long wait times and potential mistakes in orders. To manage this, the restaurant implements a queue-based load leveling system using a ticketing machine.
>
> When customers place orders, they receive a ticket number and their order is placed in a queue. The kitchen staff then processes orders one at a time in the order they were received. This ensures that the kitchen can handle the workload at a manageable pace, preventing overload and maintaining service quality. Customers wait comfortably knowing their order is in line and will be handled efficiently, even during the busiest times.

In plain words

> Queue-Based Load Leveling is a design pattern that uses a queue to manage and balance the workload between producers and consumers, preventing system overload and ensuring smooth processing.

Wikipedia says

> Message Queues are essential components for inter-process communication (IPC) and inter-thread communication, using queues to manage the passing of messages. They help in decoupling producers and consumers, allowing asynchronous processing, which is a key aspect of the Queue-Based Load Leveling pattern.

Flowchart

![Queue-Based Load Leveling flowchart](https://java-design-patterns.com/assets/img/queue-based-load-leveling-flowchart.12717979.png)

## [Programmatic Example of Queue-Based Load Leveling Pattern in Java](https://java-design-patterns.com/patterns/queue-based-load-leveling/#programmatic-example-of-queue-based-load-leveling-pattern-in-java)

The Queue-Based Load Leveling pattern helps to manage high-volume, sporadic bursts of tasks that can overwhelm a system. It uses a queue as a buffer to hold tasks, decoupling the task generation from task processing. Tasks are processed at a controlled rate, ensuring optimal load management and fault tolerance, crucial for maintaining robust system architecture.

First, let's look at the `MessageQueue` and `Message` classes. The `MessageQueue` acts as a buffer, storing messages until they are retrieved by the `ServiceExecutor`. The `Message` represents the tasks to be processed.

```java
public class Message {
  // Message details
}
```

```java
public class MessageQueue {
  private Queue<Message> queue;

  public MessageQueue() {
    queue = new LinkedList<>();
  }

  // Method to add a message to the queue
  public void addMessage(Message message) {
    queue.add(message);
  }

  // Method to retrieve a message from the queue
  public Message getMessage() {
    return queue.poll();
  }
}
```

Next, we have the `TaskGenerator` class. This class represents the task producers. It generates tasks and submits them to the `MessageQueue`.

```java
public class TaskGenerator implements Runnable {

  private MessageQueue msgQueue;
  private int taskCount;

  public TaskGenerator(MessageQueue msgQueue, int taskCount) {
    this.msgQueue = msgQueue;
    this.taskCount = taskCount;
  }

  @Override
  public void run() {
    for (int i = 0; i < taskCount; i++) {
      Message message = new Message(); // Create a new message
      msgQueue.addMessage(message); // Add the message to the queue
    }
  }
}
```

The `ServiceExecutor` class represents the task consumer. It retrieves tasks from the `MessageQueue` and processes them.

```java
public class ServiceExecutor implements Runnable {

  private MessageQueue msgQueue;

  public ServiceExecutor(MessageQueue msgQueue) {
    this.msgQueue = msgQueue;
  }

  @Override
  public void run() {
    while (true) {
      Message message = msgQueue.getMessage(); // Retrieve a message from the queue
      if (message != null) {
        // Process the message
      } else {
        // No more messages to process
        break;
      }
    }
  }
}
```

Finally, we have the `App` class which sets up the `TaskGenerator` and `ServiceExecutor` threads and submits them to an `ExecutorService`.

```java
public class App {
  public static void main(String[] args) {
    var msgQueue = new MessageQueue();

    final var taskRunnable1 = new TaskGenerator(msgQueue, 5);
    final var taskRunnable2 = new TaskGenerator(msgQueue, 1);
    final var taskRunnable3 = new TaskGenerator(msgQueue, 2);

    final var srvRunnable = new ServiceExecutor(msgQueue);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.submit(taskRunnable1);
    executor.submit(taskRunnable2);
    executor.submit(taskRunnable3);
    executor.submit(srvRunnable);

    executor.shutdown();
  }
}
```

In this example, the `TaskGenerator` threads generate tasks at a variable rate and submit them to the `MessageQueue`. The `ServiceExecutor` retrieves the tasks from the queue and processes them at its own pace, preventing the system from being overwhelmed by peak loads.

Running the application produces the following console output:

```
[main] INFO App - Submitting TaskGenerators and ServiceExecutor threads.
[main] INFO App - Initiating shutdown. Executor will shutdown only after all the Threads are completed.
[pool-1-thread-2] INFO TaskGenerator - Message-1 submitted by pool-1-thread-2
[pool-1-thread-1] INFO TaskGenerator - Message-5 submitted by pool-1-thread-1
[pool-1-thread-1] INFO TaskGenerator - Message-4 submitted by pool-1-thread-1
[pool-1-thread-2] INFO TaskGenerator - Message-2 submitted by pool-1-thread-2
[pool-1-thread-1] INFO TaskGenerator - Message-3 submitted by pool-1-thread-1
[pool-1-thread-2] INFO TaskGenerator - Message-1 submitted by pool-1-thread-2
[pool-1-thread-1] INFO TaskGenerator - Message-2 submitted by pool-1-thread-1
[pool-1-thread-2] INFO ServiceExecutor - Message-1 submitted by pool-1-thread-2 is served.
[pool-1-thread-1] INFO TaskGenerator - Message-1 submitted by pool-1-thread-1
[pool-1-thread-2] INFO ServiceExecutor - Message-5 submitted by pool-1-thread-1 is served.
[pool-1-thread-2] INFO ServiceExecutor - Message-4 submitted by pool-1-thread-1 is served.
[pool-1-thread-2] INFO ServiceExecutor - Message-2 submitted by pool-1-thread-2 is served.
[pool-1-thread-2] INFO ServiceExecutor - Message-3 submitted by pool-1-thread-1 is served.
[pool-1-thread-2] INFO ServiceExecutor - Message-1 submitted by pool-1-thread-2 is served.
[pool-1-thread-2] INFO ServiceExecutor - Message-2 submitted by pool-1-thread-1 is served.
[pool-1-thread-2] INFO ServiceExecutor - Message-1 submitted by pool-1-thread-1 is served.
[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
[pool-1-thread-2] INFO ServiceExecutor - Service Executor: Waiting for Messages to serve ..
[main] INFO App - Executor was shut down and Exiting.
[pool-1-thread-2] ERROR ServiceExecutor - sleep interrupted
```

## [When to Use the Queue-Based Load Leveling Pattern in Java](https://java-design-patterns.com/patterns/queue-based-load-leveling/#when-to-use-the-queue-based-load-leveling-pattern-in-java)

- When there are variable workloads, and you need to ensure that peak loads do not overwhelm the system
- In distributed systems where tasks are produced at a different rate than they are consumed
- For decoupling producers and consumers in an asynchronous messaging system

## [Real-World Applications of Queue-Based Load Leveling Pattern in Java](https://java-design-patterns.com/patterns/queue-based-load-leveling/#real-world-applications-of-queue-based-load-leveling-pattern-in-java)

- Amazon Web Services (AWS) Simple Queue Service (SQS)
- RabbitMQ
- Java Message Service (JMS) in enterprise Java applications

## [Benefits and Trade-offs of Queue-Based Load Leveling Pattern](https://java-design-patterns.com/patterns/queue-based-load-leveling/#benefits-and-trade-offs-of-queue-based-load-leveling-pattern)

Benefits:

- Decouples the producers and consumers, allowing each to operate at its own pace
- Increases system resilience and fault tolerance by preventing overload conditions
- Enhances scalability by allowing more consumers to be added to handle increased load

Trade-offs:

- Adds complexity to the system architecture
- May introduce latency as messages need to be queued and dequeued
- Requires additional components (queues) to be managed and monitored

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/queue-based-load-leveling/#related-java-design-patterns)

- Asynchronous Messaging: Queue-Based Load Leveling uses asynchronous messaging to decouple producers and consumers
- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Often used in conjunction with Queue-Based Load Leveling to prevent system overloads by temporarily halting message processing
- [Producer-Consumer](https://java-design-patterns.com/patterns/producer-consumer/): Queue-Based Load Leveling is a specific application of the Producer-Consumer pattern where the queue serves as the intermediary
- [Retry](https://java-design-patterns.com/patterns/retry/): Works with Queue-Based Load Leveling to handle transient failures by retrying failed operations

## [References and Credits](https://java-design-patterns.com/patterns/queue-based-load-leveling/#references-and-credits)

- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z)
- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Queue-Based Load Leveling - Microsoft](https://docs.microsoft.com/en-us/azure/architecture/patterns/queue-based-load-leveling)

---

## [resilience/retry] Retry
> 官方文档: https://java-design-patterns.com/patterns/retry/

ResilienceFault tolerancePerformanceRetryResilienceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/retry/#also-known-as)

- Retry Logic
- Retry Mechanism

## [Intent of Retry Design Pattern](https://java-design-patterns.com/patterns/retry/#intent-of-retry-design-pattern)

The Retry pattern in Java transparently retries certain operations that involve communication with external resources, particularly over the network, isolating calling code from the retry implementation details. It is crucial for developing resilient software systems that handle transient failures gracefully.

## [Detailed Explanation of Retry Pattern with Real-World Examples](https://java-design-patterns.com/patterns/retry/#detailed-explanation-of-retry-pattern-with-real-world-examples)

Real-world example

> Imagine you're a delivery driver attempting to deliver a package to a customer's house. You ring the doorbell, but no one answers. Instead of leaving immediately, you wait for a few minutes and try again, repeating this process a few times. This is similar to the Retry pattern in software, where a system retries a failed operation (e.g., making a network request) a certain number of times before finally giving up, in hopes that the issue (e.g., transient network glitch) will be resolved and the operation will succeed.

In plain words

> Retry pattern transparently retries failed operations over network.

[Microsoft documentation](https://docs.microsoft.com/en-us/azure/architecture/patterns/retry) says

> Enable an application to handle transient failures when it tries to connect to a service or network resource, by transparently retrying a failed operation. This can improve the stability of the application.

Flowchart

![Retry flowchart](https://java-design-patterns.com/assets/img/retry-flowchart.7c54b19c.png)

## [Programmatic Example of Retry Pattern in Java](https://java-design-patterns.com/patterns/retry/#programmatic-example-of-retry-pattern-in-java)

The Retry design pattern is a resilience pattern that allows an application to transparently attempt to execute operations multiple times in the expectation that it'll succeed. This pattern is particularly useful when the application is connecting to a network service or a remote resource, where temporary failures are common.

First, we have a `BusinessOperation` interface that represents an operation that can be performed and might throw a `BusinessException`.

```java
public interface BusinessOperation<T> {
  T perform() throws BusinessException;
}
```

Next, we have a `FindCustomer` class that implements this interface. This class simulates a flaky service that intermittently fails by throwing `BusinessException`s before eventually returning a customer's ID.

```java
public final class FindCustomer implements BusinessOperation<String> {
  @Override
  public String perform() throws BusinessException {
    // ...
  }
}
```

The `Retry` class is where the Retry pattern is implemented. It takes a `BusinessOperation` and a number of attempts, and it will keep trying to perform the operation until it either succeeds or the maximum number of attempts is reached.

```java
public final class Retry<T> implements BusinessOperation<T> {

    private final BusinessOperation<T> op;
    private final int maxAttempts;
    private final long delay;
    private final AtomicInteger attempts;
    private final Predicate<Exception> test;
    private final List<Exception> errors;

    @SafeVarargs
    public Retry(
            BusinessOperation<T> op,
            int maxAttempts,
            long delay,
            Predicate<Exception>... ignoreTests
    ) {
        this.op = op;
        this.maxAttempts = maxAttempts;
        this.delay = delay;
        this.attempts = new AtomicInteger();
        this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false);
        this.errors = new ArrayList<>();
    }

    public List<Exception> errors() {
        return Collections.unmodifiableList(this.errors);
    }

    public int attempts() {
        return this.attempts.intValue();
    }

    @Override
    public T perform() throws BusinessException {
        do {
            try {
                return this.op.perform();
            } catch (BusinessException e) {
                this.errors.add(e);

                if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) {
                    throw e;
                }

                try {
                    Thread.sleep(this.delay);
                } catch (InterruptedException f) {
                    //ignore
                }
            }
        } while (true);
    }
}
```

In this class, the `perform` method tries to perform the operation. If the operation throws an exception, it checks if the exception is recoverable and if the maximum number of attempts has not been reached. If both conditions are true, it waits for a specified delay and then tries again. If the exception is not recoverable or the maximum number of attempts has been reached, it rethrows the exception.

Finally, here is the `App` class driving the retry pattern example.

```java
public final class App {

  private static final Logger LOG = LoggerFactory.getLogger(App.class);
  public static final String NOT_FOUND = "not found";
  private static BusinessOperation<String> op;

  public static void main(String[] args) throws Exception {
    noErrors();
    errorNoRetry();
    errorWithRetry();
    errorWithRetryExponentialBackoff();
  }

  private static void noErrors() throws Exception {
    op = new FindCustomer("123");
    op.perform();
    LOG.info("Sometimes the operation executes with no errors.");
  }

  private static void errorNoRetry() throws Exception {
    op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND));
    try {
      op.perform();
    } catch (CustomerNotFoundException e) {
      LOG.info("Yet the operation will throw an error every once in a while.");
    }
  }

  private static void errorWithRetry() throws Exception {
    final var retry = new Retry<>(
        new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
        3,  //3 attempts
        100, //100 ms delay between attempts
        e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
    );
    op = retry;
    final var customerId = op.perform();
    LOG.info(String.format(
        "However, retrying the operation while ignoring a recoverable error will eventually yield "
            + "the result %s after a number of attempts %s", customerId, retry.attempts()
    ));
  }

  private static void errorWithRetryExponentialBackoff() throws Exception {
    final var retry = new RetryExponentialBackoff<>(
        new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)),
        6,  //6 attempts
        30000, //30 s max delay between attempts
        e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass())
    );
    op = retry;
    final var customerId = op.perform();
    LOG.info(String.format(
        "However, retrying the operation while ignoring a recoverable error will eventually yield "
            + "the result %s after a number of attempts %s", customerId, retry.attempts()
    ));
  }
}
```

Running the code produces the following console output.

```
10:12:19.573 [main] INFO com.iluwatar.retry.App -- Sometimes the operation executes with no errors.
10:12:19.575 [main] INFO com.iluwatar.retry.App -- Yet the operation will throw an error every once in a while.
10:12:19.682 [main] INFO com.iluwatar.retry.App -- However, retrying the operation while ignoring a recoverable error will eventually yield the result 123 after a number of attempts 1
10:12:22.297 [main] INFO com.iluwatar.retry.App -- However, retrying the operation while ignoring a recoverable error will eventually yield the result 123 after a number of attempts 1
```

This way, the Retry pattern allows the application to handle temporary failures gracefully, improving its resilience and reliability.

## [When to Use the Retry Pattern in Java](https://java-design-patterns.com/patterns/retry/#when-to-use-the-retry-pattern-in-java)

Applying the Retry pattern is particularly effective

- When operations can fail transiently, such as network calls, database connections, or external service integrations.
- In scenarios where the likelihood of transient failure is high but the cost of retries is low.

## [Real-World Applications of Retry Pattern in Java](https://java-design-patterns.com/patterns/retry/#real-world-applications-of-retry-pattern-in-java)

- In network communication libraries to handle transient failures.
- Database connection libraries to manage temporary outages or timeouts.
- APIs interacting with third-party services that may be temporarily unavailable.

## [Benefits and Trade-offs of Retry Pattern](https://java-design-patterns.com/patterns/retry/#benefits-and-trade-offs-of-retry-pattern)

Benefits:

- Increases the robustness and fault tolerance of applications.
- Can significantly reduce the impact of transient failures.

Trade-offs:

- May introduce latency due to retries.
- Can lead to resource exhaustion if not managed properly.
- Requires careful configuration of retry parameters to avoid exacerbating the problem.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/retry/#related-java-design-patterns)

- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Used to stop the flow of requests to an external service after a failure threshold is reached, preventing system overload.

## [References and Credits](https://java-design-patterns.com/patterns/retry/#references-and-credits)

- [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications](https://amzn.to/4dLvowg)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Java Concurrency in Practice](https://amzn.to/4aRMruW)
- [Release It!: Design and Deploy Production-Ready Software](https://amzn.to/3UPwmPh)
- [Retry pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/retry)

---

## [resilience/saga] Saga
> 官方文档: https://java-design-patterns.com/patterns/saga/

ResilienceAsynchronousDecouplingFault toleranceIntegrationMicroservicesTransactionsAbout 6 min

* * *

## [Intent of Saga Design Pattern](https://java-design-patterns.com/patterns/saga/#intent-of-saga-design-pattern)

To manage and coordinate distributed transactions across multiple services in a fault-tolerant and reliable manner.

## [Detailed Explanation of Saga Pattern with Real-World Examples](https://java-design-patterns.com/patterns/saga/#detailed-explanation-of-saga-pattern-with-real-world-examples)

Real-world example

> Imagine a travel agency coordinating a vacation package for a customer. The package includes booking a flight, reserving a hotel room, and renting a car. Each of these bookings is managed by a different service provider. If the flight booking is successful but the hotel is fully booked, the agency needs to cancel the flight and notify the customer. This ensures that the customer does not end up with only a partial vacation package. In the Saga pattern, this scenario is managed by a series of coordinated transactions, with compensating actions (like canceling the flight) to maintain consistency.

In plain words

> The Saga pattern in Java coordinates distributed transactions across microservices using a sequence of events and compensating actions to ensure data consistency and fault tolerance.

Wikipedia says

> Long-running transactions (also known as the saga interaction pattern) are computer database transactions that avoid locks on non-local resources, use compensation to handle failures, potentially aggregate smaller ACID transactions (also referred to as atomic transactions), and typically use a coordinator to complete or abort the transaction. In contrast to rollback in ACID transactions, compensation restores the original state, or an equivalent, and is business-specific. For example, the compensating action for making a hotel reservation is canceling that reservation.

Flowchart

![Saga flowchart](https://java-design-patterns.com/assets/img/saga-flowchart.2621db68.png)

## [Programmatic Example of Saga Pattern in Java](https://java-design-patterns.com/patterns/saga/#programmatic-example-of-saga-pattern-in-java)

The Saga design pattern is a sequence of local transactions where each transaction updates data within a single service. It's particularly useful in a microservices architecture where each service has its own database. The Saga pattern ensures data consistency and fault tolerance across services. Here are the key components of the Saga pattern:

1. **Saga**: A Saga is a sequence of local transactions, each of which is called a chapter. The Saga manages the sequence of these transactions, ensuring that each transaction is performed in the correct order and that the Saga is rolled back if a transaction fails.

2. **Chapter**: Each chapter in a Saga represents a local transaction. A chapter has a name, a result (which can be `INIT`, `SUCCESS`, or `ROLLBACK`), and an input value. The `Chapter` class provides methods to get and set these properties.

3. **Service**: A service performs a local transaction. It processes the input value of a chapter and returns a `ChapterResult`. If the transaction fails, it sets the status of the chapter to `ROLLBACK`.

4. **Service Discovery**: This component is responsible for discovering available services and executing the Saga. It processes each chapter in the Saga in order. If a chapter fails, the Saga will be rolled back.

5. **Saga Result**: The result of a Saga can be `PROGRESS`, `FINISHED`, or `ROLLBACKED`. This is determined by the `getResult` method of the `Saga` class.


In a real-world application, the `Service` class would contain the logic to perform the local transaction and handle failures. The `Saga` class would manage the sequence of local transactions, ensuring that each transaction is performed in the correct order and that the Saga is rolled back if a transaction fails.

**Snippet 1: Creating a Saga**

The first step in using the Saga pattern is to create a Saga. A Saga is a sequence of chapters, each representing a local transaction. The `Saga` class provides methods to add chapters and to check if a chapter is present.

```java
// Create a new Saga
Saga saga = Saga.create();
```

**Snippet 2: Adding Chapters to the Saga**

Each chapter in a Saga represents a local transaction. We can add chapters to the Saga using the `chapter` method.

```java
// Add chapters to the Saga
saga.chapter("init an order");
saga.chapter("booking a Fly");
saga.chapter("booking a Hotel");
saga.chapter("withdrawing Money");
```

**Snippet 3: Setting Input Values for Chapters**

Each chapter in a Saga can have an input value. We can set the input value for the last added chapter using the `setInValue` method.

```java
// Set input values for the chapters
saga.chapter("init an order").setInValue("good_order");
```

**Snippet 4: Executing the Saga**

We can execute the Saga using a service. The service will process each chapter in the Saga in order. If a chapter fails, the Saga will be rolled back.

```java
// Execute the Saga
var service = sd.findAny();
var goodOrderSaga = service.execute(saga);
```

**Snippet 5: Checking the Result of the Saga**

We can check the result of the Saga using the `getResult` method. This method returns the result of the Saga, which can be `PROGRESS`, `FINISHED`, or `ROLLBACKED`.

```java
// Check the result of the Saga
SagaResult result = goodOrderSaga.getResult();
```

The `SagaApplication` class has a `main` method for running the example.

```java
@Slf4j
public class SagaApplication {

  public static void main(String[] args) {
    var sd = serviceDiscovery();
    var service = sd.findAny();
    var goodOrderSaga = service.execute(newSaga("good_order"));
    var badOrderSaga = service.execute(newSaga("bad_order"));
    LOGGER.info("orders: goodOrder is {}, badOrder is {}",
        goodOrderSaga.getResult(), badOrderSaga.getResult());
  }

  private static Saga newSaga(Object value) {
    return Saga
        .create()
        .chapter("init an order").setInValue(value)
        .chapter("booking a Fly")
        .chapter("booking a Hotel")
        .chapter("withdrawing Money");
  }

  private static ServiceDiscoveryService serviceDiscovery() {
    var sd = new ServiceDiscoveryService();
    return sd
        .discover(new OrderService(sd))
        .discover(new FlyBookingService(sd))
        .discover(new HotelBookingService(sd))
        .discover(new WithdrawMoneyService(sd));
  }
}
```

1. **Saga**: The `SagaApplication` creates a new Saga using the `Saga.create()` method. It then adds chapters to the Saga using the `chapter` method and sets the input value for each chapter using the `setInValue` method.
2. **Service**: The `SagaApplication` uses services to execute the chapters in the Saga. Each service represents a local transaction. The `SagaApplication` uses the `ServiceDiscoveryService` to discover available services and execute the Saga.
3. **Service Discovery**: The `ServiceDiscoveryService` is used to discover available services. The `SagaApplication` uses this to find a service and execute the Saga.
4. **Saga Execution**: The `SagaApplication` executes the Saga using the `execute` method of a service. It creates two Sagas, one for a good order and one for a bad order, and executes them.
5. **Saga Result**: The `SagaApplication` checks the result of the Saga using the `getResult` method. It logs the result of the good order Saga and the bad order Saga.

In summary, the `SagaApplication` creates a Saga, adds chapters to it, sets the input value for each chapter, discovers services, executes the Saga using a service, and checks the result of the Saga.

Running the example produces the following console output:

```
11:32:17.779 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'init an order' has been started. The data good_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'booking a Fly' has been started. The data good_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'booking a Hotel' has been started. The data good_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'withdrawing Money' has been started. The data good_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service --  the saga has been finished with FINISHED status
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'init an order' has been started. The data bad_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'booking a Fly' has been started. The data bad_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'booking a Hotel' has been started. The data bad_order has been stored or calculated successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The chapter 'withdrawing Money' has been started. But the exception has been raised.The rollback is about to start
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The Rollback for a chapter 'booking a Hotel' has been started. The data bad_order has been rollbacked successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The Rollback for a chapter 'booking a Fly' has been started. The data bad_order has been rollbacked successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service -- The Rollback for a chapter 'init an order' has been started. The data bad_order has been rollbacked successfully
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.Service --  the saga has been finished with ROLLBACKED status
11:32:17.782 [main] INFO com.iluwatar.saga.choreography.SagaApplication -- orders: goodOrder is FINISHED, badOrder is ROLLBACKED
```

This is a basic example of how to use the Saga design pattern. In a real-world application, the `Saga` class would manage the sequence of local transactions, ensuring that each transaction is performed in the correct order and that the Saga is rolled back if a transaction fails.

## [When to Use the Saga Pattern in Java](https://java-design-patterns.com/patterns/saga/#when-to-use-the-saga-pattern-in-java)

- When you have a complex transaction that spans multiple microservices.
- When you need to ensure data consistency across services without using a traditional two-phase commit.
- When you need to handle long-running transactions in an asynchronous manner.

## [Real-World Applications of Saga Pattern in Java](https://java-design-patterns.com/patterns/saga/#real-world-applications-of-saga-pattern-in-java)

- E-commerce platforms managing orders, inventory, and payment services.
- Banking systems coordinating between account debits and credits across multiple services.
- Travel booking systems coordinating flights, hotels, and car rentals.

## [Benefits and Trade-offs of Saga Pattern](https://java-design-patterns.com/patterns/saga/#benefits-and-trade-offs-of-saga-pattern)

Benefits:

- Improved fault tolerance and reliability.
- Scalability due to decoupled services.
- Flexibility in handling long-running transactions.

Trade-offs:

- Increased complexity in handling compensating transactions.
- Requires careful design to handle partial failures and rollback scenarios.
- Potential latency due to asynchronous nature.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/saga/#related-java-design-patterns)

- [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Used to capture state changes as a sequence of events, which can complement the Saga pattern by providing a history of state changes.
- [Command Query Responsibility Segregation (CQRS)](https://java-design-patterns.com/patterns/command-query-responsibility-segregation/): Can be used in conjunction with the Saga pattern to separate command and query responsibilities, improving scalability and fault tolerance.

## [References and Credits](https://java-design-patterns.com/patterns/saga/#references-and-credits)

- [Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems](https://amzn.to/3y6yv1z)
- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui)
- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
- [Pattern: Saga (microservices.io)](https://microservices.io/patterns/data/saga.html)
- [Saga distributed transactions pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga)

---

## [resilience/tolerant-reader] Tolerant Reader
> 官方文档: https://java-design-patterns.com/patterns/tolerant-reader/

ResilienceAPI designDecouplingFault toleranceIntegrationAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/tolerant-reader/#also-known-as)

- Lenient Consumer

## [Intent of Tolerant Reader Design Pattern](https://java-design-patterns.com/patterns/tolerant-reader/#intent-of-tolerant-reader-design-pattern)

The Tolerant Reader pattern enhances system resilience to changes in data structures by strategically ignoring unrecognized elements, promoting robust API design.

## [Detailed Explanation of Tolerant Reader Pattern with Real-World Examples](https://java-design-patterns.com/patterns/tolerant-reader/#detailed-explanation-of-tolerant-reader-pattern-with-real-world-examples)

Real-world example

> Imagine a postal system that delivers letters and packages to recipients. In this system, postal workers deliver mail regardless of additional information or stickers that might be present on the envelopes or packages. If a package has extra labels or instructions that the postal system does not recognize, the postal worker ignores these and focuses only on the essential information like the address. This approach ensures that the delivery process remains functional even when senders use different formats or include unnecessary details, similar to how the Tolerant Reader pattern works in software by ignoring unrecognized data elements to maintain functionality and compatibility.

In plain words

> Utilize the Tolerant Reader pattern to establish robust and resilient communication between services, ensuring data compatibility and integration.

[Robustness Principle](https://java-design-patterns.com/principles/#robustness-principle) says

> Be conservative in what you do, be liberal in what you accept from others.

Sequence diagram

![Tolerant Reader sequence diagrams](https://java-design-patterns.com/assets/img/tolerant-reader-sequence-diagram.a0de01ab.png)

## [Programmatic Example of Tolerant Reader Pattern in Java](https://java-design-patterns.com/patterns/tolerant-reader/#programmatic-example-of-tolerant-reader-pattern-in-java)

We are persisting `RainbowFish` objects to file. Later on they need to be restored. What makes it problematic is that `RainbowFish` data structure is versioned and evolves over time. New version of `RainbowFish` needs to be able to restore old versions as well.

Here's the versioned `RainbowFish`. Notice how the second version introduces additional properties.

```java
@Getter
@RequiredArgsConstructor
public class RainbowFish implements Serializable {

    private static final long serialVersionUID = 1L;

    private final String name;
    private final int age;
    private final int lengthMeters;
    private final int weightTons;
}
```

```java
@Getter
public class RainbowFishV2 extends RainbowFish {

    @Serial
    private static final long serialVersionUID = 1L;

    private boolean sleeping;
    private boolean hungry;
    private boolean angry;

    public RainbowFishV2(String name, int age, int lengthMeters, int weightTons) {
        super(name, age, lengthMeters, weightTons);
    }

    public RainbowFishV2(String name, int age, int lengthMeters, int weightTons, boolean sleeping,
                         boolean hungry, boolean angry) {
        this(name, age, lengthMeters, weightTons);
        this.sleeping = sleeping;
        this.hungry = hungry;
        this.angry = angry;
    }
}
```

Next we introduce the `RainbowFishSerializer`. This is the class that implements the Tolerant Reader pattern.

```java
@NoArgsConstructor
public final class RainbowFishSerializer {

    public static void writeV1(RainbowFish rainbowFish, String filename) throws IOException {
        var map = Map.of(
                "name", rainbowFish.getName(),
                "age", String.format("%d", rainbowFish.getAge()),
                "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
                "weightTons", String.format("%d", rainbowFish.getWeightTons())
        );

        try (var fileOut = new FileOutputStream(filename);
             var objOut = new ObjectOutputStream(fileOut)) {
            objOut.writeObject(map);
        }
    }

    public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException {
        var map = Map.of(
                "name", rainbowFish.getName(),
                "age", String.format("%d", rainbowFish.getAge()),
                "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()),
                "weightTons", String.format("%d", rainbowFish.getWeightTons()),
                "angry", Boolean.toString(rainbowFish.getAngry()),
                "hungry", Boolean.toString(rainbowFish.getHungry()),
                "sleeping", Boolean.toString(rainbowFish.getSleeping())
        );

        try (var fileOut = new FileOutputStream(filename);
             var objOut = new ObjectOutputStream(fileOut)) {
            objOut.writeObject(map);
        }
    }

    public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {
        Map<String, String> map;

        try (var fileIn = new FileInputStream(filename);
             var objIn = new ObjectInputStream(fileIn)) {
            map = (Map<String, String>) objIn.readObject();
        }

        return new RainbowFish(
                map.get("name"),
                Integer.parseInt(map.get("age")),
                Integer.parseInt(map.get("lengthMeters")),
                Integer.parseInt(map.get("weightTons"))
        );
    }
}
```

And finally, here's the full example in action.

```java
public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Write V1
    var fishV1 = new RainbowFish("Zed", 10, 11, 12);
    LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(),
            fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons());
    RainbowFishSerializer.writeV1(fishV1, "fish1.out");
    // Read V1
    var deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out");
    LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}",
            deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(),
            deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons());
    // Write V2
    var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true);
    LOGGER.info(
            "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}",
            fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(),
            fishV2.isHungry(), fishV2.isAngry(), fishV2.isSleeping());
    RainbowFishSerializer.writeV2(fishV2, "fish2.out");
    // Read V2 with V1 method
    var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out");
    LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}",
            deserializedFishV2.getName(), deserializedFishV2.getAge(),
            deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons());
}
```

Program output:

```
15:38:00.602 [main] INFO com.iluwatar.tolerantreader.App -- fishV1 name=Zed age=10 length=11 weight=12
15:38:00.618 [main] INFO com.iluwatar.tolerantreader.App -- deserializedFishV1 name=Zed age=10 length=11 weight=12
15:38:00.618 [main] INFO com.iluwatar.tolerantreader.App -- fishV2 name=Scar age=5 length=12 weight=15 sleeping=true hungry=true angry=true
15:38:00.619 [main] INFO com.iluwatar.tolerantreader.App -- deserializedFishV2 name=Scar age=5 length=12 weight=15
```

## [When to Use the Tolerant Reader Pattern in Java](https://java-design-patterns.com/patterns/tolerant-reader/#when-to-use-the-tolerant-reader-pattern-in-java)

- Apply the Tolerant Reader pattern when your system consumes data from evolving external sources, maintaining efficiency and data integrity.
- Applicable when backward compatibility is required in API design.
- Suitable for integration scenarios where different systems exchange data and evolve independently.

## [Real-World Applications of Tolerant Reader Pattern in Java](https://java-design-patterns.com/patterns/tolerant-reader/#real-world-applications-of-tolerant-reader-pattern-in-java)

- JSON or XML parsers that skip unknown elements.
- API clients in microservices architectures that interact with multiple versions of a service.

## [Benefits and Trade-offs of Tolerant Reader Pattern](https://java-design-patterns.com/patterns/tolerant-reader/#benefits-and-trade-offs-of-tolerant-reader-pattern)

Benefits:

- Increases the robustness and flexibility of the system.
- Allows independent evolution of producers and consumers in a distributed system.
- Simplifies versioning by enabling backward compatibility.

Trade-offs:

- May result in silent failures if important data is ignored.
- Can complicate debugging and tracing of issues due to missing or unrecognized data.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/tolerant-reader/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Both patterns deal with data transformation and integration, but the Adapter Pattern focuses on converting interfaces, while Tolerant Reader focuses on ignoring unrecognized data.
- [Facade](https://java-design-patterns.com/patterns/facade/): Simplifies interactions with complex systems, similar to how Tolerant Reader simplifies data consumption by ignoring irrelevant data.
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Can be used in conjunction with Tolerant Reader to dynamically switch between different data handling strategies.

## [References and Credits](https://java-design-patterns.com/patterns/tolerant-reader/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
- [Service Design Patterns: Fundamental Design Solutions for SOAP/WSDL and RESTful Web Services](https://amzn.to/4dNIfOx)
- [Tolerant Reader (Martin Fowler)](http://martinfowler.com/bliki/TolerantReader.html)

---

<!-- ============================================ -->
<!-- Testing 测试模式 (4 个) -->
<!-- ============================================ -->

## [testing/arrange-act-assert] Arrange/Act/Assert
> 官方文档: https://java-design-patterns.com/patterns/arrange-act-assert/

TestingCode simplificationIsolationTestingAbout 2 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/arrange-act-assert/#also-known-as)

- Given/When/Then

## [Intent of Arrange/Act/Assert Design Pattern](https://java-design-patterns.com/patterns/arrange-act-assert/#intent-of-arrange-act-assert-design-pattern)

The Arrange/Act/Assert pattern is essential in unit testing in Java. This testing method structures unit tests clearly by dividing them into three distinct sections: setup (Arrange), execution (Act), and verification (Assert).

## [Detailed Explanation of Arrange/Act/Assert Pattern with Real-World Examples](https://java-design-patterns.com/patterns/arrange-act-assert/#detailed-explanation-of-arrange-act-assert-pattern-with-real-world-examples)

Real-world example

> Imagine you are organizing a small event. To ensure everything runs smoothly, you follow a pattern similar to Arrange/Act/Assert:
>
> 1. **Arrange**: You set up the venue, prepare the guest list, arrange seating, and organize the catering.
> 2. **Act**: You conduct the event according to the plan, welcoming guests, serving food, and following the schedule.
> 3. **Assert**: After the event, you evaluate its success by checking guest feedback, ensuring all tasks were completed, and reviewing if everything went as planned.
>
> This clear separation of preparation, execution, and evaluation helps ensure the event is well-organized and successful, mirroring the structured approach of the Arrange/Act/Assert pattern in software testing.

In plain words

> Arrange/Act/Assert is a testing pattern that organizes tests into three clear steps for easy maintenance.

WikiWikiWeb says

> Arrange/Act/Assert is a pattern for arranging and formatting code in UnitTest methods.

Flowchart

![Arrange/Act/Assert flowchart](https://java-design-patterns.com/assets/img/arrange-act-assert-flowchart.367e6a0f.png)

## [Programmatic Example of Arrange/Act/Assert Pattern in Java](https://java-design-patterns.com/patterns/arrange-act-assert/#programmatic-example-of-arrange-act-assert-pattern-in-java)

We need to write comprehensive and clear unit test suite for a class. Using the Arrange/Act/Assert pattern in Java testing ensures clarity.

Let's first introduce our `Cash` class to be unit tested.

```java
public class Cash {

    private int amount;

    Cash(int amount) {
        this.amount = amount;
    }

    void plus(int addend) {
        amount += addend;
    }

    boolean minus(int subtrahend) {
        if (amount >= subtrahend) {
            amount -= subtrahend;
            return true;
        } else {
            return false;
        }
    }

    int count() {
        return amount;
    }
}
```

Then we write our unit tests according to Arrange/Act/Assert pattern. Notice the clearly separated steps for each unit test.

```java
class CashAAATest {

    @Test
    void testPlus() {
        //Arrange
        var cash = new Cash(3);
        //Act
        cash.plus(4);
        //Assert
        assertEquals(7, cash.count());
    }

    @Test
    void testMinus() {
        //Arrange
        var cash = new Cash(8);
        //Act
        var result = cash.minus(5);
        //Assert
        assertTrue(result);
        assertEquals(3, cash.count());
    }

    @Test
    void testInsufficientMinus() {
        //Arrange
        var cash = new Cash(1);
        //Act
        var result = cash.minus(6);
        //Assert
        assertFalse(result);
        assertEquals(1, cash.count());
    }

    @Test
    void testUpdate() {
        //Arrange
        var cash = new Cash(5);
        //Act
        cash.plus(6);
        var result = cash.minus(3);
        //Assert
        assertTrue(result);
        assertEquals(8, cash.count());
    }
}
```

## [When to Use the Arrange/Act/Assert Pattern in Java](https://java-design-patterns.com/patterns/arrange-act-assert/#when-to-use-the-arrange-act-assert-pattern-in-java)

Use Arrange/Act/Assert pattern when

- Unit testing, especially within the context of TDD and BDD
- Anywhere clarity and structure are needed in test cases

## [Real-World Applications of Arrange/Act/Assert Pattern in Java](https://java-design-patterns.com/patterns/arrange-act-assert/#real-world-applications-of-arrange-act-assert-pattern-in-java)

- This pattern is particularly useful when practicing TDD and/or BDD methodologies in Java.
- Utilized in various programming languages and testing frameworks, such as JUnit (Java), NUnit (.NET), and xUnit frameworks.

## [Benefits and Trade-offs of Arrange/Act/Assert Pattern](https://java-design-patterns.com/patterns/arrange-act-assert/#benefits-and-trade-offs-of-arrange-act-assert-pattern)

Benefits:

- Improved readability of tests by clearly separating the setup, action, and verification steps.
- Easier maintenance and understanding of tests, as each test is structured in a predictable way.
- Facilitates debugging by isolating test failures to specific phases within the test.

Trade-offs:

- May introduce redundancy in tests, as similar arrangements may be repeated across tests.
- Some complex tests might not fit neatly into this structure, requiring additional context or setup outside these three phases.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/arrange-act-assert/#related-java-design-patterns)

- [Page Object](https://java-design-patterns.com/patterns/page-object/): A pattern for organizing UI tests that can be used in conjunction with Arrange/Act/Assert.

## [References and Credits](https://java-design-patterns.com/patterns/arrange-act-assert/#references-and-credits)

- [The Art of Unit Testing: with examples in C#](https://amzn.to/49IbdwO)
- [Test Driven Development: By Example](https://amzn.to/3wEwKbF)
- [Unit Testing Principles, Practices, and Patterns: Effective testing styles, patterns, and reliable automation for unit testing, mocking, and integration testing with examples in C#](https://amzn.to/4ayjpiM)
- [xUnit Test Patterns: Refactoring Test Code](https://amzn.to/4dHGDpm)
- [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx)
- [Bill Wake: 3A – Arrange, Act, Assert (NCrunch)](https://xp123.com/articles/3a-arrange-act-assert/)
- [GivenWhenThen (Martin Fowler)](https://martinfowler.com/bliki/GivenWhenThen.html)

---

## [testing/object-mother] Object Mother
> 官方文档: https://java-design-patterns.com/patterns/object-mother/

TestingCode simplificationInstantiationIsolationTestingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/object-mother/#also-known-as)

- Object Builder
- Test Data Builder

## [Intent of Object Mother Design Pattern](https://java-design-patterns.com/patterns/object-mother/#intent-of-object-mother-design-pattern)

The Object Mother pattern simplifies the creation of objects for testing purposes in Java, ensuring that test cases are clear and maintainable by centralizing the logic needed to instantiate objects in a consistent state.

## [Detailed Explanation of Object Mother Pattern with Real-World Examples](https://java-design-patterns.com/patterns/object-mother/#detailed-explanation-of-object-mother-pattern-with-real-world-examples)

Real-world example

> Imagine you're developing a Java application for a travel agency. In your system, there are different types of travelers, such as tourists, business travelers, and travel agents, each with specific attributes and behaviors. To perform thorough testing, you need to create and manipulate these traveler objects in various contexts. The Object Mother Pattern can help you generate consistent and predefined traveler objects for testing purposes, ensuring that your tests are based on known, reliable data.

In plain words

> The Object Mother Pattern is a design pattern used in Java to simplify the creation of objects with specific configurations, especially for testing. Instead of manually constructing objects with varying properties for each test case, you create a dedicated "Object Mother" class or method that produces these objects with predefined settings. This ensures that you have consistent and predictable test data, making your tests more reliable and easier to manage.

[wiki.c2.com](http://wiki.c2.com/) says

> Object Mother starts with the factory pattern, by delivering prefabricated test-ready objects via a simple method call. It moves beyond the realm of the factory by
>
> 1. facilitating the customization of created objects,
> 2. providing methods to update the objects during the tests, and
> 3. if necessary, deleting the object from the database at the completion of the test.

Mind map

![Object Mother mind map](https://java-design-patterns.com/assets/img/object-mother-mind-map.144efc9e.png)

Flowchart

![Object Mother flowchart](https://java-design-patterns.com/assets/img/object-mother-flowchart.acddbfe4.png)

## [Programmatic Example of Object Mother Pattern in Java](https://java-design-patterns.com/patterns/object-mother/#programmatic-example-of-object-mother-pattern-in-java)

The Object Mother is a design pattern that aims to provide an easy way to create objects for testing purposes. It encapsulates the logic for building instances of complex objects in one place, making it easier to maintain and reuse across multiple tests.

First, we have the `King` class. This class represents a king with certain behaviors and states. The king can be drunk or sober, happy or unhappy. The king can also flirt with a queen, which may affect his happiness.

```java
public class King implements Royalty {
  boolean isDrunk = false;
  boolean isHappy = false;

  @Override
  public void makeDrunk() {
    isDrunk = true;
  }

  @Override
  public void makeSober() {
    isDrunk = false;
  }

  @Override
  public void makeHappy() {
    isHappy = true;
  }

  @Override
  public void makeUnhappy() {
    isHappy = false;
  }

  public boolean isHappy() {
    return isHappy;
  }

  public void flirt(Queen queen) {
    var flirtStatus = queen.getFlirted(this);
    if (!flirtStatus) {
      this.makeUnhappy();
    } else {
      this.makeHappy();
    }
  }
}
```

The `RoyaltyObjectMother` class is where the Object Mother pattern is implemented. This class provides static methods to create different types of `King` and `Queen` objects. These methods encapsulate the logic for creating these objects, making it easier to create them in a consistent way across multiple tests.

```java
class RoyaltyObjectMother {

  static King createDrunkKing() {
    var king = new King();
    king.makeDrunk();
    return king;
  }

  static King createHappyKing() {
    var king = new King();
    king.makeHappy();
    return king;
  }

  // Other methods to create different types of King and Queen objects...
}
```

In the `RoyaltyObjectMotherTest` class, we can see how the Object Mother pattern is used to create objects for testing. The `RoyaltyObjectMother` class is used to create `King` and `Queen` objects in different states, which are then used in the tests.

```java
class RoyaltyObjectMotherTest {

  @Test
  void unsuccessfulKingFlirt() {
    var soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing();
    var flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
    soberUnhappyKing.flirt(flirtyQueen);
    assertFalse(soberUnhappyKing.isHappy());
  }

  // Other tests...
}
```

In this way, the Object Mother pattern simplifies the creation of objects for testing, making the tests easier to read and maintain.

## [When to Use the Object Mother Pattern in Java](https://java-design-patterns.com/patterns/object-mother/#when-to-use-the-object-mother-pattern-in-java)

Use the Object Mother pattern when

- Creating complex objects with numerous fields for unit tests.
- You need to reuse a standard set of objects across multiple tests.
- Test setup is becoming cumbersome and repetitive.

## [Object Mother Pattern Java Tutorials](https://java-design-patterns.com/patterns/object-mother/#object-mother-pattern-java-tutorials)

- [What is an ObjectMother? (Stack Overflow)](http://stackoverflow.com/questions/923319/what-is-an-objectmother)
- [Object Mother (c2wiki)](http://c2.com/cgi/wiki?ObjectMother)
- [Test Data Builders: an alternative to the Object Mother pattern (Nat Pryce)](http://www.natpryce.com/articles/000714.html)

## [Real-World Applications of Object Mother Pattern in Java](https://java-design-patterns.com/patterns/object-mother/#real-world-applications-of-object-mother-pattern-in-java)

- In unit testing frameworks to create test fixtures.
- In enterprise applications to generate standard domain objects required across multiple test cases.
- In open-source projects like Apache Commons and Spring Framework for test object creation.

## [Benefits and Trade-offs of Object Mother Pattern](https://java-design-patterns.com/patterns/object-mother/#benefits-and-trade-offs-of-object-mother-pattern)

Benefits:

- Code Simplification: Reduces boilerplate code in tests, making tests more readable and easier to maintain.
- Isolation: Ensures test data setup is isolated from test logic, enhancing clarity.
- Consistency: Provides a consistent way to create objects, reducing the likelihood of errors in test setup.

Trade-offs:

- Maintenance: Requires maintaining the Object Mother class itself, which can grow complex over time.
- Overhead: May introduce additional layers of abstraction that could complicate understanding for new developers.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/object-mother/#related-java-design-patterns)

- [Builder](https://java-design-patterns.com/patterns/builder/): Both patterns deal with object creation. The Object Mother is often simpler and used specifically in a testing context, whereas the Builder Pattern is more general-purpose.
- [Factory Method](https://java-design-patterns.com/patterns/factory-method/): Similar in the sense of centralizing object creation logic. The Object Mother is specifically aimed at tests, while Factory Method is used more broadly in application code.

## [References and Credits](https://java-design-patterns.com/patterns/object-mother/#references-and-credits)

- [Growing Object-Oriented Software, Guided by Tests](https://amzn.to/4dGfIuk)
- [xUnit Test Patterns: Refactoring Test Code](https://amzn.to/4dHGDpm)

---

## [testing/page-object] Page Object
> 官方文档: https://java-design-patterns.com/patterns/page-object/

TestingAbstractionCode simplificationDecouplingEncapsulationTestingWeb developmentAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/page-object/#also-known-as)

- Page Object Model (POM)

## [Intent of Page Object Design Pattern](https://java-design-patterns.com/patterns/page-object/#intent-of-page-object-design-pattern)

The Page Object pattern in Java aims to create a model of the UI elements of a web page to improve the maintainability and readability of test automation code.

## [Detailed Explanation of Page Object Pattern with Real-World Examples](https://java-design-patterns.com/patterns/page-object/#detailed-explanation-of-page-object-pattern-with-real-world-examples)

Real-world example

> Imagine a large corporate office where a receptionist directs visitors to the appropriate department. The receptionist serves as a single point of contact for all incoming visitors, simplifying the process of navigation within the building. Each department provides the receptionist with specific instructions on how to direct visitors to their office.
>
> In this analogy, the receptionist is like a Page Object in a testing framework. The receptionist abstracts the complexities of the office layout from the visitors, just as the Page Object abstracts the details of interacting with web elements from the test scripts. When the layout of the office changes, only the receptionist's instructions need to be updated, not the way visitors are directed, similar to how only the Page Object needs to be updated when the web UI changes, not the test scripts.

In plain words

> The Page Object design pattern creates an abstraction layer for web pages, encapsulating their elements and interactions to simplify and maintain automated UI testing scripts.

selenium.dev says

> Within your web app’s UI, there are areas where your tests interact with. A Page Object only models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix needs only to be applied in one place.
>
> Page Object is a Design Pattern that has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your AUT. The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI are located in one place.

Mind map

![Page Object mind map](https://java-design-patterns.com/assets/img/page-object-mind-map.e3a1eb7c.png)

Flowchart

![Page Object flowchart](https://java-design-patterns.com/assets/img/page-object-flowchart.b9210df1.png)

## [Programmatic Example of Page Object Pattern in Java](https://java-design-patterns.com/patterns/page-object/#programmatic-example-of-page-object-pattern-in-java)

The Page Object design pattern is a popular design pattern in test automation. It helps in enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your Application Under Test (AUT). The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI are located in one place.

Let's consider a simple programmatic example of the Page Object pattern for a login page using Selenium in Java:

```java
public class LoginPage {
    private final WebDriver driver;

    // Web elements on the login page
    private final By usernameInput = By.id("username");
    private final By passwordInput = By.id("password");
    private final By loginButton = By.id("login-button");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    // Methods to interact with the login page

    public void enterUsername(String username) {
        WebElement usernameElement = driver.findElement(usernameInput);
        usernameElement.sendKeys(username);
    }

    public void enterPassword(String password) {
        WebElement passwordElement = driver.findElement(passwordInput);
        passwordElement.sendKeys(password);
    }

    public void clickLoginButton() {
        WebElement loginButtonElement = driver.findElement(loginButton);
        loginButtonElement.click();
    }

    // Other methods specific to the login page if needed
}
```

In this example, the `LoginPage` class represents the login page of a web application. It encapsulates the web elements on the page and provides methods to interact with those elements. The actual Selenium WebDriver instance is passed to the constructor, allowing the methods to perform actions on the web page.

This Page Object can be used in test scripts to interact with the login page without exposing the details of the page structure in the test code, promoting maintainability and reusability.

## [When to Use the Page Object Pattern in Java](https://java-design-patterns.com/patterns/page-object/#when-to-use-the-page-object-pattern-in-java)

Use the Page Object pattern when

- Automating UI tests for web applications.
- You want to separate the UI actions from the test logic.
- Enhancing test code readability and reducing duplication.
- Simplifying maintenance when the web UI changes.

## [Real-World Applications of Page Object Pattern in Java](https://java-design-patterns.com/patterns/page-object/#real-world-applications-of-page-object-pattern-in-java)

- Selenium WebDriver tests for web applications.
- Automated UI testing frameworks in Java.
- Popular test automation frameworks like TestNG and JUnit.

## [Benefits and Trade-offs of Page Object Pattern](https://java-design-patterns.com/patterns/page-object/#benefits-and-trade-offs-of-page-object-pattern)

Benefits:

- Encapsulation: Isolates the page elements and actions from test scripts.
- Code simplification: Reduces code duplication and improves readability.
- Maintainability: Easy to update when the UI changes, as changes are confined to page objects.
- Abstraction: Test scripts focus on what the user does rather than how the actions are performed on the UI.

Trade-offs:

- Initial Setup: Requires extra effort to design and implement page objects.
- Complexity: Overuse may lead to a complex structure with many page objects and methods.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/page-object/#related-java-design-patterns)

- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used alongside Page Objects to add additional responsibilities to objects dynamically.
- [Facade](https://java-design-patterns.com/patterns/facade/): Both provide a simplified interface to a complex subsystem. Page Object abstracts the complexities of the UI.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Acts as a surrogate or placeholder, which can also be used for lazy initialization of page objects.

## [References and Credits](https://java-design-patterns.com/patterns/page-object/#references-and-credits)

- [Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation](https://amzn.to/4bjhTSK)
- [Selenium Design Patterns and Best Practices](https://amzn.to/4aofYv8)
- [Selenium Testing Tools Cookbook](https://amzn.to/3K1QxEN)
- [Page Object (Martin Fowler)](http://martinfowler.com/bliki/PageObject.html)
- [Page Objects (Selenium)](https://github.com/SeleniumHQ/selenium/wiki/PageObjects)

---

## [testing/service-stub] Service Stub
> 官方文档: https://java-design-patterns.com/patterns/service-stub/

TestingAPI designDecouplingIntegrationMicroservicesTestingAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/service-stub/#also-known-as)

- Service Mock
- Test Double

## [Intent of Service Stub Pattern](https://java-design-patterns.com/patterns/service-stub/#intent-of-service-stub-pattern)

Provide a lightweight, simplified implementation of a remote or external service to facilitate testing in isolation.

## [Detailed Explanation of Service Stub Pattern with Real-World Example](https://java-design-patterns.com/patterns/service-stub/#detailed-explanation-of-service-stub-pattern-with-real-world-example)

Real-world example

> A real-world analogy for the Service Stub pattern could be a flight simulator used to train pilots. Instead of learning to fly directly using a real airplane—which would be costly, dangerous, and often impractical—pilots initially practice within a simulator. This simulator provides predefined, realistic scenarios and reactions, enabling pilots to train safely, repeatedly, and predictably without the complexities and risks associated with actual flight operations. Similarly, a Service Stub provides controlled, predictable responses for external services during testing, simplifying and accelerating software development and testing processes.

In plain words

> Use a fake service to return predictable results without relying on external systems.

Wikipedia says

> A test stub is a dummy component used during testing to isolate behavior.

Sequence diagram

![Service Stub sequence diagram](https://java-design-patterns.com/assets/img/service-stub-sequence-diagram.74b0b394.png)

## [Programmatic Example of Service Stub Pattern in Java](https://java-design-patterns.com/patterns/service-stub/#programmatic-example-of-service-stub-pattern-in-java)

We demonstrate the Service Stub pattern using a simple sentiment analysis example. To illustrate this clearly, we define a common interface `SentimentAnalysisServer` and create two separate implementations:

**RealSentimentAnalysisServer**: Represents a slow, realistic sentiment analysis service, returning random sentiment results to simulate external complexity and latency.

**StubSentimentAnalysisServer**: Provides fast, deterministic results based on simple keyword matching, suitable for isolated testing without external dependencies.

### [Step-by-step Example Implementation](https://java-design-patterns.com/patterns/service-stub/#step-by-step-example-implementation)

First, define a common interface that both implementations will use:

```java
public interface SentimentAnalysisServer {
    String analyzeSentiment(String text);
}
```

Next, we create a realistic implementation that simulates a slow, external service. It introduces a delay of 5 seconds and returns random sentiment results (`Positive`, `Negative`, or `Neutral`). For flexibility and easier testing, it allows injecting a custom sentiment supplier:

```java
public class RealSentimentAnalysisServer implements SentimentAnalysisServer {

    private final Supplier<Integer> sentimentSupplier;

    public RealSentimentAnalysisServer(Supplier<Integer> sentimentSupplier) {
        this.sentimentSupplier = sentimentSupplier;
    }

    public RealSentimentAnalysisServer() {
        this(() -> new Random().nextInt(3));
    }

    @Override
    public String analyzeSentiment(String text) {
        int sentiment = sentimentSupplier.get();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return sentiment == 0 ? "Positive" : sentiment == 1 ? "Negative" : "Neutral";
    }
}
```

Then, we provide a simplified stub implementation designed specifically for testing purposes. It returns immediate and predictable results based on simple keyword detection. This enables tests to run quickly and consistently without relying on external factors:

```java
public class StubSentimentAnalysisServer implements SentimentAnalysisServer {

  @Override
  public String analyzeSentiment(String text) {
    if (text.toLowerCase().contains("good")) {
      return "Positive";
    }
    else if (text.toLowerCase().contains("bad")) {
      return "Negative";
    }
    else {
      return "Neutral";
    }
  }
}
```

Finally, here's the main application logic illustrating how to use both implementations in practice. Notice the significant performance difference between the real and stub implementations:

```java
@Slf4j
  public static void main(String[] args) {
  LOGGER.info("Setting up the real sentiment analysis server.");
  RealSentimentAnalysisServer realSentimentAnalysisServer = new RealSentimentAnalysisServer();
  String text = "This movie is soso";
  LOGGER.info("Analyzing input: {}", text);
  String sentiment = realSentimentAnalysisServer.analyzeSentiment(text);
  LOGGER.info("The sentiment is: {}", sentiment);

    LOGGER.info("Setting up the stub sentiment analysis server.");
    StubSentimentAnalysisServer stubSentimentAnalysisServer = new StubSentimentAnalysisServer();
    text = "This movie is so bad";
    LOGGER.info("Analyzing input: {}", text);
    sentiment = stubSentimentAnalysisServer.analyzeSentiment(text);
    LOGGER.info("The sentiment is: {}", sentiment);
  }
```

In summary, implementing a Service Stub involves creating a simplified substitute (`StubSentimentAnalysisServer`) for an actual external service (`RealSentimentAnalysisServer`). This approach allows your tests to run quickly and consistently by isolating them from external complexity and unpredictability.

## [When to Use the Service Stub Pattern in Java](https://java-design-patterns.com/patterns/service-stub/#when-to-use-the-service-stub-pattern-in-java)

- When testing systems with external or third-party service dependencies.
- In integration tests to isolate the service being tested from network or external dependencies.
- During development when the actual services are unavailable or unreliable.
- To speed up tests by avoiding calls to slower external systems.

## [Real-World Applications of Service Stub Pattern in Java](https://java-design-patterns.com/patterns/service-stub/#real-world-applications-of-service-stub-pattern-in-java)

- WireMock: Widely used in Java testing to stub HTTP-based external services.
- Mockito: Allows creating lightweight stubs for dependencies in unit testing.
- Spring Cloud Contract: Provides contracts and stub servers for services in microservices architectures.

## [Benefits and Trade-offs of Service Stub Pattern](https://java-design-patterns.com/patterns/service-stub/#benefits-and-trade-offs-of-service-stub-pattern)

Benefits:

- Simplifies testing by eliminating dependencies on external systems.
- Speeds up testing processes by removing latency from external network calls.
- Allows consistent, repeatable, and predictable testing scenarios.
- Enables parallel test execution, improving overall development productivity.

Trade-offs:

- Stubs need to be regularly updated to reflect changes in the actual external services.
- May introduce false confidence if stubs do not accurately represent external system behavior.
- Can lead to additional overhead and maintenance of stub configurations.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/service-stub/#related-java-design-patterns)

- [Adapter](https://java-design-patterns.com/patterns/adapter/): Service Stub may sometimes implement Adapter interfaces to mimic external dependencies in a test environment.
- Mock Object: Similar to Service Stub, but Mock Objects usually verify interactions explicitly, while Service Stubs primarily provide predefined responses without verification.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Both Service Stub and Proxy introduce intermediate objects to control access or communication with actual components, though Proxy typically manages access control and communication, while Service Stub specifically aims to isolate for testing.

## [References and Credits](https://java-design-patterns.com/patterns/service-stub/#references-and-credits)

- [Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation](https://amzn.to/4bjhTSK)
- [Growing Object-Oriented Software, Guided by Tests](https://amzn.to/4dGfIuk)
- [Mocks Aren't Stubs (Martin Fowler)](https://martinfowler.com/articles/mocksArentStubs.html)
- [xUnit Test Patterns: Refactoring Test Code](https://amzn.to/4dHGDpm)

---

<!-- ============================================ -->
<!-- Messaging 消息模式 (4 个) -->
<!-- ============================================ -->

## [messaging/data-bus] Data Bus
> 官方文档: https://java-design-patterns.com/patterns/data-bus/

MessagingDecouplingEvent-drivenMessagingPublish/subscribeScalabilityAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/data-bus/#also-known-as)

- Event Bus
- Message Bus

## [Intent of Data Bus Design Pattern](https://java-design-patterns.com/patterns/data-bus/#intent-of-data-bus-design-pattern)

The Data Bus design pattern aims to provide a centralized communication channel through which various components of a system can exchange data without being directly connected, thus promoting loose coupling and enhancing scalability and maintainability.

## [Detailed Explanation of Data Bus Pattern with Real-World Examples](https://java-design-patterns.com/patterns/data-bus/#detailed-explanation-of-data-bus-pattern-with-real-world-examples)

Real-world example

> Consider a large airport as an analogous real-world example of the Data Bus pattern. In an airport, various airlines, passengers, baggage handlers, and security personnel all need to communicate and share information. Instead of each entity communicating directly with every other entity, the airport uses a centralized announcement system (the Data Bus). Flight information, security alerts, and other critical updates are broadcast over this system, and each entity listens for the messages relevant to them. This setup allows the airport to decouple the communication process, ensuring that each entity only receives the information they need, while allowing the system to scale and integrate new entities without disrupting the existing ones. This is similar to how the Data Bus pattern in Java promotes centralized communication and event handling, enhancing system scalability and maintainability.

In plain words

> Data Bus is a design pattern that connects components of an application for communication based on the type of message or event being transferred. This pattern promotes decoupling, making it easier to scale and maintain the system by allowing components to communicate without direct dependencies.

Sequence diagram

![Data Bus Sequence Diagram](https://java-design-patterns.com/assets/img/data-bus-sequence-diagram.106db064.png)

## [Programmatic Example of Data Bus Pattern in Java](https://java-design-patterns.com/patterns/data-bus/#programmatic-example-of-data-bus-pattern-in-java)

Say you have an app that enables online bookings and participation in events. You want the app to send notifications, such as event advertisements, to all ordinary members of the community or organization holding the events. However, you do not want to send such advertisements to event administrators or organizers. Instead, you want to send them notifications about the timing of new advertisements sent to all members. The Data Bus enables you to selectively notify community members by type (ordinary members or event administrators) by making their classes or components only accept messages of a certain type. Thus, ordinary members and administrators do not need to know about each other or the specific classes or components used to notify the entire community, except for knowing the type of messages being sent.

In the online events app example above, we first define our `Member` interface and its implementations: `MessageCollectorMember` (ordinary community members) and `StatusMember` (event administrators or organizers).

```java
public interface Member extends Consumer<DataType> {

    void accept(DataType event);
}
```

Next, we implement a data bus to subscribe or unsubscribe members and to publish events to notify all community members.

```java
public class DataBus {

    private static final DataBus INSTANCE = new DataBus();

    private final Set<Member> listeners = new HashSet<>();

    public static DataBus getInstance() {
        return INSTANCE;
    }

    public void subscribe(final Member member) {
        this.listeners.add(member);
    }

    public void unsubscribe(final Member member) {
        this.listeners.remove(member);
    }

    public void publish(final DataType event) {
        event.setDataBus(this);

        listeners.forEach(
                listener -> listener.accept(event));
    }
}
```

The `accept` method is applied to each member in the `publish` method.

For ordinary community members (`MessageCollectorMember`), the `accept` method can handle only `MessageData` type messages.

```java
public class MessageCollectorMember implements Member {

    private final String name;

    private final List<String> messages = new ArrayList<>();

    public MessageCollectorMember(String name) {
        this.name = name;
    }

    @Override
    public void accept(final DataType data) {
        if (data instanceof MessageData) {
            handleEvent((MessageData) data);
        }
    }
}
```

For event administrators or organizers (`StatusMember`), the `accept` method can handle `StartingData` and `StoppingData` type messages.

```java
public class StatusMember implements Member {

    private final int id;

    private LocalDateTime started;

    private LocalDateTime stopped;

    public StatusMember(int id) {
        this.id = id;
    }

    @Override
    public void accept(final DataType data) {
        if (data instanceof StartingData) {
            handleEvent((StartingData) data);
        } else if (data instanceof StoppingData) {
            handleEvent((StoppingData) data);
        }
    }
}
```

Here is the `App` class to demonstrate the Data Bus pattern in action:

```java
class App {

    public static void main(String[] args) {
        final var bus = DataBus.getInstance();
        bus.subscribe(new StatusMember(1));
        bus.subscribe(new StatusMember(2));
        final var foo = new MessageCollectorMember("Foo");
        final var bar = new MessageCollectorMember("Bar");
        bus.subscribe(foo);
        bus.publish(StartingData.of(LocalDateTime.now()));
    }
}
```

When the data bus publishes a message, the output is as follows:

```
02:33:57.627 [main] INFO com.iluwatar.databus.members.StatusMember - Receiver 2 sees application started at 2022-10-26T02:33:57.613529100
02:33:57.633 [main] INFO com.iluwatar.databus.members.StatusMember - Receiver 1 sees application started at 2022-10-26T02:33:57.613529100
```

As shown, `MessageCollectorMembers` only accept messages of type `MessageData`, so they do not see the `StartingData` or `StoppingData` messages, which are only visible to `StatusMember` (the event administrators or organizers). This selective message handling prevents ordinary community members from receiving administrative notifications.

## [When to Use the Data Bus Pattern in Java](https://java-design-patterns.com/patterns/data-bus/#when-to-use-the-data-bus-pattern-in-java)

- When multiple components need to share data or events but direct coupling is undesirable.
- In complex, event-driven systems where the flow of information varies dynamically.
- In distributed systems where components might be deployed across different environments.
- In microservices architectures for inter-service communication.

## [Real-World Applications of Data Bus Pattern in Java](https://java-design-patterns.com/patterns/data-bus/#real-world-applications-of-data-bus-pattern-in-java)

- Event handling systems in large-scale applications.
- Microservices architectures for inter-service communication.
- Real-time data processing systems, such as stock trading platforms.
- In frameworks like Spring, particularly with its application event mechanism.

## [Benefits and Trade-offs of Data Bus Pattern](https://java-design-patterns.com/patterns/data-bus/#benefits-and-trade-offs-of-data-bus-pattern)

Benefits:

- Loose Coupling: Components can interact without having direct dependencies on each other.
- Flexibility: New subscribers or publishers can be added without impacting existing components.
- Scalability: The pattern supports scaling components independently.
- Reusability: The bus and components can be reused across different systems.

Trade-offs:

- Complexity: Introducing a data bus can add complexity to the system architecture.
- Performance Overhead: The additional layer of communication may introduce latency.
- Debugging Difficulty: Tracing data flow through the bus can be challenging, especially in systems with many events.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/data-bus/#related-java-design-patterns)

- [Mediator](https://java-design-patterns.com/patterns/mediator/): Facilitates communication between components, but unlike Data Bus, it centralizes control.
- [Observer](https://java-design-patterns.com/patterns/observer/): Similar in nature to the publish-subscribe mechanism used in Data Bus for notifying changes to multiple objects.
- Publish/Subscribe: The Data Bus pattern is often implemented using the publish-subscribe mechanism, where publishers post messages to the bus without knowledge of the subscribers.

## [References and Credits](https://java-design-patterns.com/patterns/data-bus/#references-and-credits)

- [Enterprise Integration Patterns](https://amzn.to/3J6WoYS)
- [Pattern-Oriented Software Architecture, Volume 4: A Pattern Language for Distributed Computing](https://amzn.to/3PTRGBM)

giscus

#### 0 reactions

#### 0 comments

WritePreview

[Styling with Markdown is supported](https://guides.github.com/features/mastering-markdown/ "Styling with Markdown is supported")

[Sign in with GitHub](https://giscus.app/api/oauth/authorize?redirect_uri=https%3A%2F%2Fjava-design-patterns.com%2Fpatterns%2Fdata-bus%2F)

---

## [messaging/event-aggregator] Event Aggregator
> 官方文档: https://java-design-patterns.com/patterns/event-aggregator/

MessagingDecouplingEvent-drivenMessagingPublish/subscribeReactiveAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/event-aggregator/#also-known-as)

- Event Channel
- Event Central
- Message Hub

## [Intent of Event Aggregator Design Pattern](https://java-design-patterns.com/patterns/event-aggregator/#intent-of-event-aggregator-design-pattern)

An Event Aggregator is a design pattern used for handling events in a system. It centralizes the event handling logic, making it easier to manage and maintain. The Event Aggregator design pattern aims to decouple event generation from event handling. This design pattern collects events from multiple sources and routes them to the appropriate handlers.

## [Detailed Explanation of Event Aggregator Pattern with Real-World Examples](https://java-design-patterns.com/patterns/event-aggregator/#detailed-explanation-of-event-aggregator-pattern-with-real-world-examples)

Real-world example

> The Event Aggregator pattern is often compared to a hub in a wheel. In this analogy, the Event Aggregator is the hub, and the spokes are the event sources. The hub collects events from all the spokes and then distributes them to the appropriate handlers.

In Plain Words

> Event Aggregator is a design pattern that allows multiple event sources to communicate with event handlers through a central point, rather than having each event source communicate directly with each handler.

Sequence diagram

![Event Aggregator sequence diagram](https://java-design-patterns.com/assets/img/event-aggregator-sequence-diagram.680caf03.png)

## [Programmatic Example of Event Aggregator Pattern in Java](https://java-design-patterns.com/patterns/event-aggregator/#programmatic-example-of-event-aggregator-pattern-in-java)

Consider the following example where we use the Event Aggregator to handle multiple events.

King Joffrey sits on the iron throne and rules the seven kingdoms of Westeros. He receives most of his critical information from King's Hand, the second in command. King's hand has many close advisors himself, feeding him with relevant information about events occurring in the kingdom.

In our programmatic example, we demonstrate the implementation of an event aggregator pattern. Some of the objects are event listeners, some are event emitters, and the event aggregator does both.

```java
public interface EventObserver {
    void onEvent(Event e);
}
```

```java
public abstract class EventEmitter {

    private final Map<Event, List<EventObserver>> observerLists;

    public EventEmitter() {
        observerLists = new HashMap<>();
    }

    public final void registerObserver(EventObserver obs, Event e) {
      // implementation omitted
    }

    protected void notifyObservers(Event e) {
        // implementation omitted
    }
}
```

`KingJoffrey` is listening to events from `KingsHand`.

```java

@Slf4j
public class KingJoffrey implements EventObserver {
    @Override
    public void onEvent(Event e) {
        LOGGER.info("Received event from the King's Hand: {}", e.toString());
    }
}
```

`KingsHand` is listening to events from his subordinates `LordBaelish`, `LordVarys`, and `Scout`. Whatever he hears from them, he delivers to `KingJoffrey`.

```java
public class KingsHand extends EventEmitter implements EventObserver {

    public KingsHand() {
    }

    public KingsHand(EventObserver obs, Event e) {
        super(obs, e);
    }

    @Override
    public void onEvent(Event e) {
        notifyObservers(e);
    }
}
```

For example, `LordVarys` finds a traitor every Sunday and notifies the `KingsHand`.

```java

@Slf4j
public class LordVarys extends EventEmitter implements EventObserver {
    @Override
    public void timePasses(Weekday day) {
        if (day == Weekday.SATURDAY) {
            notifyObservers(Event.TRAITOR_DETECTED);
        }
    }
}
```

The following snippet demonstrates how the objects are constructed and wired together.

```java
public static void main(String[] args) {

    var kingJoffrey = new KingJoffrey();

    var kingsHand = new KingsHand();
    kingsHand.registerObserver(kingJoffrey, Event.TRAITOR_DETECTED);
    kingsHand.registerObserver(kingJoffrey, Event.STARK_SIGHTED);
    kingsHand.registerObserver(kingJoffrey, Event.WARSHIPS_APPROACHING);
    kingsHand.registerObserver(kingJoffrey, Event.WHITE_WALKERS_SIGHTED);

    var varys = new LordVarys();
    varys.registerObserver(kingsHand, Event.TRAITOR_DETECTED);
    varys.registerObserver(kingsHand, Event.WHITE_WALKERS_SIGHTED);

    var scout = new Scout();
    scout.registerObserver(kingsHand, Event.WARSHIPS_APPROACHING);
    scout.registerObserver(varys, Event.WHITE_WALKERS_SIGHTED);

    var baelish = new LordBaelish(kingsHand, Event.STARK_SIGHTED);

    var emitters = List.of(
            kingsHand,
            baelish,
            varys,
            scout
    );

    Arrays.stream(Weekday.values())
            .<Consumer<? super EventEmitter>>map(day -> emitter -> emitter.timePasses(day))
            .forEachOrdered(emitters::forEach);
}
```

The console output after running the example.

```
21:37:38.737 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Warships approaching
21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: White walkers sighted
21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Stark sighted
21:37:38.739 [main] INFO com.iluwatar.event.aggregator.KingJoffrey -- Received event from the King's Hand: Traitor detected
```

## [When to Use the Event Aggregator Pattern in Java](https://java-design-patterns.com/patterns/event-aggregator/#when-to-use-the-event-aggregator-pattern-in-java)

Use the Event Aggregator pattern when

- You have multiple event sources and handlers.
- You want to decouple the event generation and handling logic.
- You need a centralized event management system.

## [Real-World Applications of Event Aggregator Pattern in Java](https://java-design-patterns.com/patterns/event-aggregator/#real-world-applications-of-event-aggregator-pattern-in-java)

- Enterprise application integrations where systems need a central point to handle events generated by various subsystems.
- Complex GUI applications where user actions in one part of the interface need to affect other parts without tight coupling between the components.

## [Benefits and Trade-offs of Event Aggregator Pattern](https://java-design-patterns.com/patterns/event-aggregator/#benefits-and-trade-offs-of-event-aggregator-pattern)

Benefits:

- Decoupling: By centralizing event handling, the Event Aggregator minimizes direct interaction between components, leading to a more modular and easier-to-manage system.
- Improves Flexibility and Scalability: Adding new publishers or subscribers involves less effort since the central aggregator handles all routing.
- Simplifies Component Interface: Components need to know only about the Event Aggregator, not about other components.
- Centralizes event management: Makes the system easier to maintain.

Trade-offs:

- Complexity of the Aggregator: The Event Aggregator itself can become a complex and high-maintenance component if not properly designed.
- Potential Performance Bottleneck: If not scaled properly, the central event handling mechanism can become a bottleneck in the system.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/event-aggregator/#related-java-design-patterns)

- [Mediator](https://java-design-patterns.com/patterns/mediator/): Similar to Mediator in that it abstracts direct communications between components, but focused specifically on event messages.
- [Observer](https://java-design-patterns.com/patterns/observer/): The Event Aggregator pattern is often implemented using the Observer pattern, where the aggregator observes events and notifies subscribers.
- Publish-Subscribe: The Event Aggregator can be seen as a special case of the Publish-Subscribe pattern, with the aggregator acting as the broker.

## [References and Credits](https://java-design-patterns.com/patterns/event-aggregator/#references-and-credits)

- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/44eWKXv)
- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/440b0CZ)
- [Java Design Pattern Essentials](https://amzn.to/43XHCgM)
- [Event Aggregator (Martin Fowler)](http://martinfowler.com/eaaDev/EventAggregator.html)

---

## [messaging/microservices-idempotent-consumer] Microservices Idempotent Consumer
> 官方文档: https://java-design-patterns.com/patterns/microservices-idempotent-consumer/

MessagingAsynchronousDecouplingEvent-drivenMessagingMicroservicesResilienceRetryAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#also-known-as)

- Idempotent Subscriber
- Repeatable Message Consumer
- Safe Consumer

## [Intent of Idempotent Consumer Pattern](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#intent-of-idempotent-consumer-pattern)

Ensure that consuming the same message multiple times does not cause unintended side effects in a microservices-based architecture.

## [Detailed Explanation of Idempotent Consumer Pattern with Real-World Examples](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#detailed-explanation-of-idempotent-consumer-pattern-with-real-world-examples)

Real-world example

> In a payment processing system, ensuring that payment messages are idempotent prevents duplicate transactions. For example, if a user’s payment message is accidentally processed twice, the system should recognize the second message as a duplicate and prevent it from executing a second time. By storing unique identifiers for each processed message, such as a transaction ID, the system can skip any duplicate messages. This ensures that a user is not charged twice for the same transaction, maintaining system integrity and customer satisfaction.

In plain words

> The Idempotent Consumer pattern prevents duplicate messages from causing unintended side effects by ensuring that processing the same message multiple times results in the same outcome. This makes message processing safe in distributed systems where duplicates may occur.

Wikipedia says

> In computing, idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.

Flowchart

![Microservices Idempotent Consumer flowchart](https://java-design-patterns.com/assets/img/microservices-idempotent-consumer-flowchart.e3a958e3.png)

## [Programmatic example of Idempotent Consumer Pattern](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#programmatic-example-of-idempotent-consumer-pattern)

In this Java example, we have an idempotent service that creates and updates orders. The `create` method is idempotent, meaning multiple calls with the same order ID return the same result without duplicates. For state changes (like starting or completing an order), the service checks whether the transition is valid and throws an exception if it’s not allowed. The `RequestStateMachine` ensures that order statuses move forward in a valid sequence (e.g., PENDING → STARTED → COMPLETED).

### [RequestService - Managing Idempotent Order Operations](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#requestservice-managing-idempotent-order-operations)

The `RequestService` class provides methods to create and transition an order. The `create` method returns an existing order if it already exists, making it idempotent.

```java
public class RequestService {
    // Idempotent: ensures that the same request is returned if it already exists
    public Request create(UUID uuid) {
        Optional<Request> optReq = requestRepository.findById(uuid);
        if (!optReq.isEmpty()) {
            return optReq.get();  // Return existing request
        }
        return requestRepository.save(new Request(uuid));  // Save and return new request
    }

    public Request start(UUID uuid) {
        Optional<Request> optReq = requestRepository.findById(uuid);
        if (optReq.isEmpty()) {
            throw new RequestNotFoundException(uuid);
        }
        return requestRepository.save(requestStateMachine.next(optReq.get(), Request.Status.STARTED));
    }

    public Request complete(UUID uuid) {
        Optional<Request> optReq = requestRepository.findById(uuid);
        if (optReq.isEmpty()) {
            throw new RequestNotFoundException(uuid);
        }
        return requestRepository.save(requestStateMachine.next(optReq.get(), Request.Status.COMPLETED));
    }
}
```

### [RequestStateMachine - Managing Order Transitions](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#requeststatemachine-managing-order-transitions)

The `RequestStateMachine` enforces valid state changes. If a requested transition is not allowed based on the current status, an exception is thrown.

```java
public class RequestStateMachine {

  public Request next(Request req, Request.Status nextStatus) {
    String transitionStr = String.format("Transition: %s -> %s", req.getStatus(), nextStatus);
    switch (nextStatus) {
      case PENDING -> throw new InvalidNextStateException(transitionStr);
      case STARTED -> {
        if (Request.Status.PENDING.equals(req.getStatus())) {
          return new Request(req.getUuid(), Request.Status.STARTED);  // Valid transition
        }
        throw new InvalidNextStateException(transitionStr);  // Invalid transition
      }
      case COMPLETED -> {
        if (Request.Status.STARTED.equals(req.getStatus())) {
          return new Request(req.getUuid(), Request.Status.COMPLETED);  // Valid transition
        }
        throw new InvalidNextStateException(transitionStr);  // Invalid transition
      }
      default -> throw new InvalidNextStateException(transitionStr);  // Invalid status
    }
  }
}
```

### [Main Application - Running the Idempotent Consumer Example](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#main-application-running-the-idempotent-consumer-example)

Here, we demonstrate how `RequestService` can be called multiple times without creating duplicate orders. We also show how invalid transitions (like trying to start an order twice) result in exceptions, while valid transitions proceed normally.

```java
Request req = requestService.create(UUID.randomUUID());
// Try creating the same Request again with the same UUID (idempotent operation)
requestService.create(req.getUuid());
// Again, try creating the same Request (idempotent operation, no new Request should be created)
requestService.create(req.getUuid());
LOGGER.info("Nb of requests : {}", requestRepository.count()); // 1, processRequest is idempotent
// Attempt to start the Request (the first valid transition)
req = requestService.start(req.getUuid());
// Try to start the Request again, which should throw an exception since it's already started
try {
  req = requestService.start(req.getUuid());
} catch (InvalidNextStateException ex) {
  // Log an error message when trying to start a request twice
  LOGGER.error("Cannot start request twice!");
}
// Complete the Request (valid transition from STARTED to COMPLETED)
req = requestService.complete(req.getUuid());
// Log the final status of the Request to confirm it's been completed
LOGGER.info("Request: {}", req);
```

Program output:

```
19:01:54.382  INFO [main] com.iluwatar.idempotentconsumer.App      : Nb of requests : 1
19:01:54.395 ERROR [main] com.iluwatar.idempotentconsumer.App      : Cannot start request twice!
19:01:54.399  INFO [main] com.iluwatar.idempotentconsumer.App      : Request: Request(uuid=2d5521ef-6b6b-4003-9ade-81e381fe9a63, status=COMPLETED)
```

## [When to Use the Idempotent Consumer Pattern](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#when-to-use-the-idempotent-consumer-pattern)

- When messages can arrive more than once due to network glitches or retries
- When microservices must guarantee consistent state changes regardless of duplicates
- When fault-tolerant event-driven communication is critical to system reliability
- When horizontal scaling requires stateless consumer operations

## [Real-World Applications of Idempotent Consumer Pattern](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#real-world-applications-of-idempotent-consumer-pattern)

- Payment processing systems that receive duplicate charge events
- E-commerce order services that handle duplicate purchase requests
- Notification services that retry failed message deliveries
- Distributed transaction systems where duplicated events are common

## [Benefits and Trade-offs of the Idempotent Consumer Pattern](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#benefits-and-trade-offs-of-the-idempotent-consumer-pattern)

Benefits

- Prevents duplicate side effects
- Increases reliability under repeated or delayed messages
- Simplifies error handling and retry logic

Trade-offs

- Requires careful design to track processed messages
- Can add overhead for maintaining idempotency tokens or state
- May require additional storage or database transactions

## [Related Patterns in Java](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#related-patterns-in-java)

- Outbox Pattern: Uses a dedicated table or storage to reliably publish events and handle deduplication at the source.

## [References and Credits](https://java-design-patterns.com/patterns/microservices-idempotent-consumer/#references-and-credits)

- [Building Microservices](https://amzn.to/3UACtrU)
- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/4dznP2Y)
- [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)

---

## [messaging/publish-subscribe] Publish-Subscribe
> 官方文档: https://java-design-patterns.com/patterns/publish-subscribe/

MessagingArchitectureAsynchronousDecouplingEvent-drivenMessagingMicroservicesPublish/subscribeScalabilityAbout 4 min

* * *

## [Intent of the Publish-Subscribe Design Pattern](https://java-design-patterns.com/patterns/publish-subscribe/#intent-of-the-publish-subscribe-design-pattern)

Defines a one-to-many dependency between objects, enabling automatic notification of multiple subscribers when a publisher's state changes or an event occurs.

## [Detailed Explanation of Publish-Subscribe Pattern with Real-World Examples](https://java-design-patterns.com/patterns/publish-subscribe/#detailed-explanation-of-publish-subscribe-pattern-with-real-world-examples)

Real-world example

> An analogous real-world example of the Publish-Subscribe pattern is a news broadcasting system. A news agency (publisher) broadcasts breaking news stories without knowing who specifically receives them. Subscribers, such as television stations, news websites, or mobile news apps, independently decide which types of news they want to receive (e.g., sports, politics, weather) and are automatically notified whenever relevant events occur. This approach keeps the news agency unaware of subscribers' specifics, allowing flexible and scalable distribution of information.

In plain words

> The Publish-Subscribe design pattern allows senders (publishers) to broadcast messages to multiple receivers (subscribers) without knowing who they are, enabling loose coupling and asynchronous communication in a system.

Wikipedia says

> In software architecture, publish–subscribe or pub/sub is a messaging pattern where publishers categorize messages into classes that are received by subscribers.
>
> This is contrasted to the typical messaging pattern model where publishers send messages directly to subscribers. Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are. Publish–subscribe is a sibling of the message queue paradigm, and is typically one part of a larger message-oriented middleware system.
>
> Most messaging systems support both the pub/sub and message queue models in their API; e.g., Java Message Service (JMS).

Sequence diagram

![Publish-Subscribe sequence diagram](https://java-design-patterns.com/assets/img/publish-subscribe-sequence-diagram.37eb11fe.png)

## [Programmatic Example of Publish-Subscribe Pattern in Java](https://java-design-patterns.com/patterns/publish-subscribe/#programmatic-example-of-publish-subscribe-pattern-in-java)

First, we identify events that trigger the publisher-subscriber interactions. Common examples include:

- Sending alerts based on weather events, like earthquakes, floods, and tornadoes.
- Sending notifications based on temperature changes.
- Sending emails to customer support when support tickets are created.

### [Defining the Message](https://java-design-patterns.com/patterns/publish-subscribe/#defining-the-message)

We start with a simple message class encapsulating the information sent from publishers to subscribers.

```java
public record Message(Object content) {
}
```

### [Defining Topics](https://java-design-patterns.com/patterns/publish-subscribe/#defining-topics)

A Topic represents an event category that subscribers can register to and publishers can publish messages to. Each topic has:

- A unique identifier or name (e.g., WEATHER, TEMPERATURE, CUSTOMER\_SUPPORT).
- A collection of subscribers listening to this topic.

Subscribers can dynamically subscribe or unsubscribe.

```java
@Getter
@Setter
@RequiredArgsConstructor
public class Topic {

  private final String topicName;
  private final Set<Subscriber> subscribers = new CopyOnWriteArraySet<>();

  public void addSubscriber(Subscriber subscriber) {
    subscribers.add(subscriber);
  }

  public void removeSubscriber(Subscriber subscriber) {
    subscribers.remove(subscriber);
  }

  public void publish(Message message) {
    for (Subscriber subscriber : subscribers) {
      CompletableFuture.runAsync(() -> subscriber.onMessage(message));
    }
  }
}
```

### [Publisher Implementation](https://java-design-patterns.com/patterns/publish-subscribe/#publisher-implementation)

The Publisher maintains a collection of topics it can publish to.

- Before publishing, a topic must be registered.
- Upon publishing, it forwards messages to subscribers of the corresponding topic.

```java
public class PublisherImpl implements Publisher {

    private static final Logger logger = LoggerFactory.getLogger(PublisherImpl.class);
    private final Set<Topic> topics = new HashSet<>();

    @Override
    public void registerTopic(Topic topic) {
        topics.add(topic);
    }

    @Override
    public void publish(Topic topic, Message message) {
        if (!topics.contains(topic)) {
            logger.error("This topic is not registered: {}", topic.getName());
            return;
        }
        topic.publish(message);
    }
}
```

### [Defining Subscribers](https://java-design-patterns.com/patterns/publish-subscribe/#defining-subscribers)

Subscribers implement an interface that handles incoming messages.

- Each subscriber processes messages according to specific logic.
- Subscribers can be registered to multiple topics.

```java
public interface Subscriber {
    void onMessage(Message message);
}
```

Subscriber examples:

- WeatherSubscriber: handles alerts for weather events or temperature changes.
- CustomerSupportSubscriber: handles support tickets by sending emails.
- DelayedWeatherSubscriber: simulates delayed processing for demonstrating asynchronous behavior.

### [Example Usage (Invocation)](https://java-design-patterns.com/patterns/publish-subscribe/#example-usage-invocation)

Here's how all components connect:

1. Create Publisher
2. Register Topics with Publisher
3. Create Subscribers and Subscribe to Relevant Topics
4. Publish Messages
5. Manage Subscriptions Dynamically

```java
public static void main(String[] args) throws InterruptedException {

    final String topicWeather = "WEATHER";
    final String topicTemperature = "TEMPERATURE";
    final String topicCustomerSupport = "CUSTOMER_SUPPORT";

    // 1. create the publisher.
    Publisher publisher = new PublisherImpl();

    // 2. define the topics and register on publisher
    Topic weatherTopic = new Topic(topicWeather);
    publisher.registerTopic(weatherTopic);

    Topic temperatureTopic = new Topic(topicTemperature);
    publisher.registerTopic(temperatureTopic);

    Topic supportTopic = new Topic(topicCustomerSupport);
    publisher.registerTopic(supportTopic);

    // 3. Create the subscribers and subscribe to the relevant topics
    // weatherSub1 will subscribe to two topics WEATHER and TEMPERATURE.
    Subscriber weatherSub1 = new WeatherSubscriber();
    weatherTopic.addSubscriber(weatherSub1);
    temperatureTopic.addSubscriber(weatherSub1);

    // weatherSub2 will subscribe to WEATHER topic
    Subscriber weatherSub2 = new WeatherSubscriber();
    weatherTopic.addSubscriber(weatherSub2);

    // delayedWeatherSub will subscribe to WEATHER topic
    // NOTE :: DelayedWeatherSubscriber has a 0.2 sec delay of processing message.
    Subscriber delayedWeatherSub = new DelayedWeatherSubscriber();
    weatherTopic.addSubscriber(delayedWeatherSub);

    // subscribe the customer support subscribers to the CUSTOMER_SUPPORT topic.
    Subscriber supportSub1 = new CustomerSupportSubscriber();
    supportTopic.addSubscriber(supportSub1);
    Subscriber supportSub2 = new CustomerSupportSubscriber();
    supportTopic.addSubscriber(supportSub2);

    // 4. publish message from each topic
    publisher.publish(weatherTopic, new Message("earthquake"));
    publisher.publish(temperatureTopic, new Message("23C"));
    publisher.publish(supportTopic, new Message("support@test.de"));

    // 5. unregister subscriber from TEMPERATURE topic
    temperatureTopic.removeSubscriber(weatherSub1);

    // 6. publish message under TEMPERATURE topic
    publisher.publish(temperatureTopic, new Message("0C"));

    /*
     * Finally, we wait for the subscribers to consume messages to check the output.
     * The output can change on each run, depending on how long the execution on each
     * subscriber would take
     * Expected behavior:
     * - weatherSub1 will consume earthquake and 23C
     * - weatherSub2 will consume earthquake
     * - delayedWeatherSub will take longer and consume earthquake
     * - supportSub1, supportSub2 will consume support@test.de
     * - the message 0C will not be consumed because weatherSub1 unsubscribed from TEMPERATURE topic
     */
    TimeUnit.SECONDS.sleep(2);
}
```

### [Program output](https://java-design-patterns.com/patterns/publish-subscribe/#program-output)

Output may vary due to asynchronous subscriber processing:

```
14:01:45.599 [ForkJoinPool.commonPool-worker-6] INFO com.iluwatar.publish.subscribe.subscriber.CustomerSupportSubscriber -- Customer Support Subscriber: 1416331388 sent the email to: support@test.de
14:01:45.599 [ForkJoinPool.commonPool-worker-4] INFO com.iluwatar.publish.subscribe.subscriber.WeatherSubscriber -- Weather Subscriber: 1949521124 issued message: 23C
14:01:45.599 [ForkJoinPool.commonPool-worker-2] INFO com.iluwatar.publish.subscribe.subscriber.WeatherSubscriber -- Weather Subscriber: 60629172 issued message: earthquake
14:01:45.599 [ForkJoinPool.commonPool-worker-5] INFO com.iluwatar.publish.subscribe.subscriber.CustomerSupportSubscriber -- Customer Support Subscriber: 1807508804 sent the email to: support@test.de
14:01:45.599 [ForkJoinPool.commonPool-worker-1] INFO com.iluwatar.publish.subscribe.subscriber.WeatherSubscriber -- Weather Subscriber: 1949521124 issued message: earthquake
14:01:47.600 [ForkJoinPool.commonPool-worker-3] INFO com.iluwatar.publish.subscribe.subscriber.DelayedWeatherSubscriber -- Delayed Weather Subscriber: 2085808749 issued message: earthquake
```

This demonstrates:

- Subscribers reacting independently to messages published to subscribed topics.
- Dynamic subscription management allows changing which subscribers listen to specific topics.
- The asynchronous and loosely coupled nature of the publish-subscribe pattern in Java applications.

## [When to Use the Publish-Subscribe Pattern](https://java-design-patterns.com/patterns/publish-subscribe/#when-to-use-the-publish-subscribe-pattern)

- When an application requires loose coupling between event producers and consumers.
- In scenarios where multiple subscribers independently react to the same event.
- When developing scalable, asynchronous messaging systems, particularly within microservices architectures.

## [Real-World Applications of Publish-Subscribe Pattern in Java](https://java-design-patterns.com/patterns/publish-subscribe/#real-world-applications-of-publish-subscribe-pattern-in-java)

- Java Message Service (JMS) implementations (ActiveMQ, RabbitMQ)
- Apache Kafka (used extensively in Java-based microservices)
- Spring Framework's event publishing and listening mechanisms
- Google Cloud Pub/Sub in Java applications
- AWS Simple Notification Service (SNS) with Java SDK

## [Benefits and Trade-offs of Publish-Subscribe Pattern](https://java-design-patterns.com/patterns/publish-subscribe/#benefits-and-trade-offs-of-publish-subscribe-pattern)

Benefits:

- Loose coupling between publishers and subscribers promotes flexibility.
- Improved scalability and maintainability as new subscribers can be easily added.
- Supports asynchronous communication, enhancing system responsiveness.

Trade-offs:

- Increased complexity due to asynchronous message handling and debugging difficulties.
- Potential message delivery delays and inconsistency if the infrastructure isn't reliable.
- Risk of message flooding, requiring proper infrastructure and consumer management.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/publish-subscribe/#related-java-design-patterns)

- [Observer Pattern](https://java-design-patterns.com/patterns/observer/): Both patterns establish a publisher-subscriber relationship; however, Observer typically works within a single application boundary synchronously, whereas Publish-Subscribe is often distributed and asynchronous.
- [Mediator Pattern](https://java-design-patterns.com/patterns/mediator/): Mediator encapsulates interactions between objects in a centralized manner, whereas Publish-Subscribe provides decentralized, loosely-coupled interactions.

## [References and Credits](https://java-design-patterns.com/patterns/publish-subscribe/#references-and-credits)

- [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3WcFVui)
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
- [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V)
- [Publisher-Subscriber Pattern (Microsoft)](https://learn.microsoft.com/en-us/azure/architecture/patterns/publisher-subscriber)

---

<!-- ============================================ -->
<!-- Performance Optimization 性能优化模式 (3 个) -->
<!-- ============================================ -->

## [performance-optimization/caching] Caching
> 官方文档: https://java-design-patterns.com/patterns/caching/

Performance optimizationCachingData accessPerformanceResource managementAbout 9 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/caching/#also-known-as)

- Cache
- Temporary Storage

## [Intent of Caching Design Pattern](https://java-design-patterns.com/patterns/caching/#intent-of-caching-design-pattern)

The Java Caching Design Pattern is crucial for performance optimization and resource management. It involves various caching strategies such as write-through, read-through, and LRU cache to ensure efficient data access. The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them again.

## [Detailed Explanation of Caching Pattern with Real-World Examples](https://java-design-patterns.com/patterns/caching/#detailed-explanation-of-caching-pattern-with-real-world-examples)

Real-world example

> A real-world example of the Caching Design Pattern in Java is a library's catalog system. By caching frequently searched book results, the system reduces database load and enhances performance. When patrons frequently search for popular books, the system can cache the results of these searches. Instead of querying the database every time a user searches for a popular book, the system quickly retrieves the results from the cache. This reduces the load on the database and provides faster response times for users, enhancing their overall experience. However, the system must also ensure that the cache is updated when new books are added or existing ones are checked out, to maintain accurate information.

In plain words

> Caching pattern keeps frequently needed data in fast-access storage to improve performance.

Wikipedia says

> In computing, a cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store; thus, the more requests that can be served from the cache, the faster the system performs.

Flowchart

![Caching flowchart](https://java-design-patterns.com/assets/img/caching-flowchart.15b6f6cb.png)

## [Programmatic Example of Caching Pattern in Java](https://java-design-patterns.com/patterns/caching/#programmatic-example-of-caching-pattern-in-java)

In this programmatic example, we demonstrate different Java caching strategies, including write-through, write-around, and write-behind, using a user account management system.

A team is working on a website that provides new homes for abandoned cats. People can post their cats on the website after registering, but all the new posts require approval from one of the site moderators. The user accounts of the site moderators contain a specific flag and the data is stored in a MongoDB database. Checking for the moderator flag each time a post is viewed becomes expensive, and it's a good idea to utilize caching here.

Let's first look at the data layer of our application. The interesting classes are `UserAccount` which is a simple Java object containing the user account details, and `DbManager` interface which handles reading and writing of these objects to/from database.

```java

@Data
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class UserAccount {
    private String userId;
    private String userName;
    private String additionalInfo;
}

public interface DbManager {

    void connect();

    void disconnect();

    UserAccount readFromDb(String userId);

    UserAccount writeToDb(UserAccount userAccount);

    UserAccount updateDb(UserAccount userAccount);

    UserAccount upsertDb(UserAccount userAccount);
}
```

In the example, we are demonstrating various different caching policies. The following caching strategies are implemented in Java: Write-through, Write-around, Write-behind, and Cache-aside. Each strategy offers unique benefits for improving performance and reducing load on the database.

- Write-through writes data to the cache and DB in a single transaction
- Write-around writes data immediately into the DB instead of the cache
- Write-behind writes data into the cache initially whilst the data is only written into the DB when the cache is full
- Cache-aside pushes the responsibility of keeping the data synchronized in both data sources to the application itself
- Read-through strategy is also included in the aforementioned strategies, and it returns data from the cache to the caller if it exists, otherwise queries from DB and stores it into the cache for future use.

The cache implementation in `LruCache` is a hash table accompanied by a doubly linked-list. The linked-list helps in capturing and maintaining the LRU data in the cache. When data is queried (from the cache), added (to the cache), or updated, the data is moved to the front of the list to depict itself as the most-recently-used data. The LRU data is always at the end of the list.

```java

@Slf4j
public class LruCache {

    static class Node {
        String userId;
        UserAccount userAccount;
        Node previous;
        Node next;

        public Node(String userId, UserAccount userAccount) {
            this.userId = userId;
            this.userAccount = userAccount;
        }
    }

    // Other properties and methods...

    public LruCache(int capacity) {
        this.capacity = capacity;
    }

    public UserAccount get(String userId) {
        if (cache.containsKey(userId)) {
            var node = cache.get(userId);
            remove(node);
            setHead(node);
            return node.userAccount;
        }
        return null;
    }

    public void set(String userId, UserAccount userAccount) {
        if (cache.containsKey(userId)) {
            var old = cache.get(userId);
            old.userAccount = userAccount;
            remove(old);
            setHead(old);
        } else {
            var newNode = new Node(userId, userAccount);
            if (cache.size() >= capacity) {
                LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId);
                cache.remove(end.userId); // remove LRU data from cache.
                remove(end);
                setHead(newNode);
            } else {
                setHead(newNode);
            }
            cache.put(userId, newNode);
        }
    }

    public boolean contains(String userId) {
        return cache.containsKey(userId);
    }

    public void remove(Node node) { /* ... */ }

    public void setHead(Node node) { /* ... */ }

    public void invalidate(String userId) { /* ... */ }

    public boolean isFull() { /* ... */ }

    public UserAccount getLruData() { /* ... */ }

    public void clear() { /* ... */ }

    public List<UserAccount> getCacheDataInListForm() { /* ... */ }

    public void setCapacity(int newCapacity) { /* ... */ }
}
```

The next layer we are going to look at is `CacheStore` which implements the different caching strategies.

```java

@Slf4j
public class CacheStore {

    private static final int CAPACITY = 3;
    private static LruCache cache;
    private final DbManager dbManager;

    // Other properties and methods...

    public UserAccount readThrough(final String userId) {
        if (cache.contains(userId)) {
            LOGGER.info("# Found in Cache!");
            return cache.get(userId);
        }
        LOGGER.info("# Not found in cache! Go to DB!!");
        UserAccount userAccount = dbManager.readFromDb(userId);
        cache.set(userId, userAccount);
        return userAccount;
    }

    public void writeThrough(final UserAccount userAccount) {
        if (cache.contains(userAccount.getUserId())) {
            dbManager.updateDb(userAccount);
        } else {
            dbManager.writeToDb(userAccount);
        }
        cache.set(userAccount.getUserId(), userAccount);
    }

    public void writeAround(final UserAccount userAccount) {
        if (cache.contains(userAccount.getUserId())) {
            dbManager.updateDb(userAccount);
            // Cache data has been updated -- remove older
            cache.invalidate(userAccount.getUserId());
            // version from cache.
        } else {
            dbManager.writeToDb(userAccount);
        }
    }

    public static void clearCache() {
        if (cache != null) {
            cache.clear();
        }
    }

    public static void flushCache() {
        LOGGER.info("# flushCache...");
        Optional.ofNullable(cache)
                .map(LruCache::getCacheDataInListForm)
                .orElse(List.of())
                .forEach(DbManager::updateDb);
    }

    // ... omitted the implementation of other caching strategies ...

}
```

`AppManager` helps to bridge the gap in communication between the main class and the application's back-end. DB connection is initialized through this class. The chosen caching strategy/policy is also initialized here. Before the cache can be used, the size of the cache has to be set. Depending on the chosen caching policy, `AppManager` will call the appropriate function in the `CacheStore` class.

```java

@Slf4j
public final class AppManager {

    private static CachingPolicy cachingPolicy;
    private final DbManager dbManager;
    private final CacheStore cacheStore;

    private AppManager() {
    }

    public void initDb() { /* ... */ }

    public static void initCachingPolicy(CachingPolicy policy) { /* ... */ }

    public static void initCacheCapacity(int capacity) { /* ... */ }

    public UserAccount find(final String userId) {
        LOGGER.info("Trying to find {} in cache", userId);
        if (cachingPolicy == CachingPolicy.THROUGH
                || cachingPolicy == CachingPolicy.AROUND) {
            return cacheStore.readThrough(userId);
        } else if (cachingPolicy == CachingPolicy.BEHIND) {
            return cacheStore.readThroughWithWriteBackPolicy(userId);
        } else if (cachingPolicy == CachingPolicy.ASIDE) {
            return findAside(userId);
        }
        return null;
    }

    public void save(final UserAccount userAccount) {
        LOGGER.info("Save record!");
        if (cachingPolicy == CachingPolicy.THROUGH) {
            cacheStore.writeThrough(userAccount);
        } else if (cachingPolicy == CachingPolicy.AROUND) {
            cacheStore.writeAround(userAccount);
        } else if (cachingPolicy == CachingPolicy.BEHIND) {
            cacheStore.writeBehind(userAccount);
        } else if (cachingPolicy == CachingPolicy.ASIDE) {
            saveAside(userAccount);
        }
    }

    public static String printCacheContent() {
        return CacheStore.print();
    }

    // Other properties and methods...
}
```

Here is what we do in the main class of the application.

```java

@Slf4j
public class App {

    public static void main(final String[] args) {
        boolean isDbMongo = isDbMongo(args);
        if (isDbMongo) {
            LOGGER.info("Using the Mongo database engine to run the application.");
        } else {
            LOGGER.info("Using the 'in Memory' database to run the application.");
        }
        App app = new App(isDbMongo);
        app.useReadAndWriteThroughStrategy();
        String splitLine = "==============================================";
        LOGGER.info(splitLine);
        app.useReadThroughAndWriteAroundStrategy();
        LOGGER.info(splitLine);
        app.useReadThroughAndWriteBehindStrategy();
        LOGGER.info(splitLine);
        app.useCacheAsideStategy();
        LOGGER.info(splitLine);
    }

    public void useReadAndWriteThroughStrategy() {
        LOGGER.info("# CachingPolicy.THROUGH");
        appManager.initCachingPolicy(CachingPolicy.THROUGH);

        var userAccount1 = new UserAccount("001", "John", "He is a boy.");

        appManager.save(userAccount1);
        LOGGER.info(appManager.printCacheContent());
        appManager.find("001");
        appManager.find("001");
    }

    public void useReadThroughAndWriteAroundStrategy() { /* ... */ }

    public void useReadThroughAndWriteBehindStrategy() { /* ... */ }

    public void useCacheAsideStrategy() { /* ... */ }
}
```

The program output:

```
17:00:56.302 [main] INFO com.iluwatar.caching.App -- Using the 'in Memory' database to run the application.
17:00:56.304 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.THROUGH
17:00:56.305 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.308 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=001, userName=John, additionalInfo=He is a boy.)
----
17:00:56.308 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 001 in cache
17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache!
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 001 in cache
17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache!
17:00:56.309 [main] INFO com.iluwatar.caching.App -- ==============================================
17:00:56.309 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.AROUND
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.309 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
----
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache
17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Not found in cache! Go to DB!!
17:00:56.309 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=002, userName=Jane, additionalInfo=She is a girl.)
----
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache
17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache!
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.309 [main] INFO com.iluwatar.caching.LruCache -- # 002 has been updated! Removing older version from cache...
17:00:56.309 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
----
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache
17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Not found in cache! Go to DB!!
17:00:56.309 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=002, userName=Jane G., additionalInfo=She is a girl.)
----
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 002 in cache
17:00:56.309 [main] INFO com.iluwatar.caching.CacheStore -- # Found in Cache!
17:00:56.309 [main] INFO com.iluwatar.caching.App -- ==============================================
17:00:56.309 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.BEHIND
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.309 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.310 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=005, userName=Isaac, additionalInfo=He is allergic to mustard.)
UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.)
UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.)
----
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 003 in cache
17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Found in cache!
17:00:56.310 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.)
UserAccount(userId=005, userName=Isaac, additionalInfo=He is allergic to mustard.)
UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.)
----
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Cache is FULL! Writing LRU data to DB...
17:00:56.310 [main] INFO com.iluwatar.caching.LruCache -- # Cache is FULL! Removing 004 from cache...
17:00:56.310 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=006, userName=Yasha, additionalInfo=She is an only child.)
UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.)
UserAccount(userId=005, userName=Isaac, additionalInfo=He is allergic to mustard.)
----
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 004 in cache
17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Not found in Cache!
17:00:56.310 [main] INFO com.iluwatar.caching.CacheStore -- # Cache is FULL! Writing LRU data to DB...
17:00:56.310 [main] INFO com.iluwatar.caching.LruCache -- # Cache is FULL! Removing 005 from cache...
17:00:56.310 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.)
UserAccount(userId=006, userName=Yasha, additionalInfo=She is an only child.)
UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.)
----
17:00:56.310 [main] INFO com.iluwatar.caching.App -- ==============================================
17:00:56.310 [main] INFO com.iluwatar.caching.App -- # CachingPolicy.ASIDE
17:00:56.310 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
----
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Save record!
17:00:56.310 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
----
17:00:56.310 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 003 in cache
17:00:56.313 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.)
----
17:00:56.313 [main] INFO com.iluwatar.caching.AppManager -- Trying to find 004 in cache
17:00:56.313 [main] INFO com.iluwatar.caching.App --
--CACHE CONTENT--
UserAccount(userId=004, userName=Rita, additionalInfo=She hates cats.)
UserAccount(userId=003, userName=Adam, additionalInfo=He likes food.)
----
17:00:56.313 [main] INFO com.iluwatar.caching.App -- ==============================================
17:00:56.314 [Thread-0] INFO com.iluwatar.caching.CacheStore -- # flushCache...
```

Implementing the Java Caching Design Pattern using various strategies like LRU cache and write-through caching significantly enhances application performance and scalability.

## [When to Use the Caching Pattern in Java](https://java-design-patterns.com/patterns/caching/#when-to-use-the-caching-pattern-in-java)

Use the Caching pattern when

- Repetitious acquisition, initialization, and release of the same resource cause unnecessary performance overhead
- In scenarios where the cost of recomputing or re-fetching data is significantly higher than storing and retrieving it from cache
- For read-heavy applications with relatively static data or data that changes infrequently

## [Real-World Applications of Caching Pattern in Java](https://java-design-patterns.com/patterns/caching/#real-world-applications-of-caching-pattern-in-java)

- Web page caching to reduce server load and improve response time
- Database query caching to avoid repeated expensive SQL queries
- Caching results of CPU-intensive computations
- Content Delivery Networks (CDNs) for caching static resources like images, CSS, and JavaScript files closer to the end users

## [Benefits and Trade-offs of Caching Pattern](https://java-design-patterns.com/patterns/caching/#benefits-and-trade-offs-of-caching-pattern)

Benefits:

- Improved Performance: Significantly reduces data access latency, leading to faster application performance
- Reduced Load: Decreases the load on the underlying data source, which can lead to cost savings and increased longevity of the resource
- Scalability: Enhances the scalability of applications by efficiently handling increases in load without proportional increases in resource utilization

Trade-Offs:

- Complexity: Introduces complexity in terms of cache invalidation, consistency, and synchronization
- Resource Utilization: Requires additional memory or storage resources to maintain the cache
- Stale Data: There's a risk of serving outdated data if the cache is not properly invalidated or updated when the underlying data changes

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/caching/#related-java-design-patterns)

- [Proxy](https://java-design-patterns.com/patterns/proxy/): Caching can be implemented using the Proxy pattern, where the proxy object intercepts requests and returns cached data if available
- [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify the cache when the underlying data changes, so that it can be updated or invalidated accordingly
- [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add caching behavior to an existing object without modifying its code
- [Strategy](https://java-design-patterns.com/patterns/strategy/): Different caching strategies can be implemented using the Strategy pattern, allowing the application to switch between them at runtime

## [References and Credits](https://java-design-patterns.com/patterns/caching/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [High Performance Browser Networking](https://amzn.to/3TiNNY4)
- [Java EE 8 High Performance](https://amzn.to/44T8vmH)
- [Java Performance: In-Depth Advice for Tuning and Programming Java 8, 11, and Beyond](https://amzn.to/3yyD58W)
- [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://amzn.to/3Wu5neF)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3PMAHRZ)
- [Scalable Internet Architectures](https://amzn.to/48V3ni9)
- [Write-through, write-around, write-back: Cache explained (ComputerWeekly)](http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained)
- [Cache-Aside Pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/cache-aside)

---

## [performance-optimization/data-locality] Data Locality
> 官方文档: https://java-design-patterns.com/patterns/data-locality/

Performance optimizationCachingData accessGame programmingMemory managementPerformanceAbout 4 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/data-locality/#also-known-as)

- Cache-Friendly Design
- Data-Oriented Design

## [Intent of Data Locality Design Pattern](https://java-design-patterns.com/patterns/data-locality/#intent-of-data-locality-design-pattern)

The Data Locality design pattern aims to minimize data access times and improve cache utilization by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing, real-time data processing, and game development where access speed is crucial.

## [Detailed Explanation of Data Locality Pattern with Real-World Examples](https://java-design-patterns.com/patterns/data-locality/#detailed-explanation-of-data-locality-pattern-with-real-world-examples)

Real-world example

> Consider a supermarket where items are arranged based on purchase patterns and categories for efficiency. Just like the Data Locality pattern organizes data in memory for quick access, the supermarket places frequently bought items together and in easily accessible areas. This layout minimizes the time shoppers spend searching for items, enhancing their shopping experience by ensuring that related and popular items are close at hand, much like how data locality improves cache utilization and reduces access latency in computing.

In plain words

> The Data Locality pattern organizes data in memory to reduce access times and improve performance by ensuring that data frequently accessed together is stored close together. This is crucial for high-performance applications like game engines and real-time data processing systems.

Mind map

![Data Locality mind map](https://java-design-patterns.com/assets/img/data-locality-mind-map.e63f3f9e.png)

Flowchart

![Data Locality flowchart](https://java-design-patterns.com/assets/img/data-locality-flowchart.4c971433.png)

## [Programmatic Example of Data Locality Pattern in Java](https://java-design-patterns.com/patterns/data-locality/#programmatic-example-of-data-locality-pattern-in-java)

The Data Locality pattern is a design pattern that aims to improve performance by arranging data in memory to take advantage of spatial locality. This pattern is particularly useful in high-performance computing and game development where access speed is crucial.

In the data-locality module, the pattern is demonstrated using a game loop that processes a bunch of game entities. These entities are decomposed into different domains: AI, physics, and rendering.

The `GameEntity` class is the main class that represents a game entity. It contains an array of `AiComponent`, `PhysicsComponent`, and `RenderComponent` objects. These components represent different aspects of a game entity.

```java
public class GameEntity {
    private final AiComponent[] aiComponents;
    private final PhysicsComponent[] physicsComponents;
    private final RenderComponent[] renderComponents;
    // Other properties and methods...
}
```

The `GameEntity` class has a start method that initializes all the components.

```java
public void start() {
  for (int i = 0; i < numEntities; i++) {
    aiComponents[i] = new AiComponent();
    physicsComponents[i] = new PhysicsComponent();
    renderComponents[i] = new RenderComponent();
  }
}
```

The `GameEntity` class also has an update method that updates all the components. This method demonstrates the data locality pattern. Instead of updating all aspects of a single entity at a time (AI, physics, and rendering), it updates the same aspect (e.g., AI) for all entities first, then moves on to the next aspect (e.g., physics). This approach improves cache utilization because it's more likely that the data needed for the update is already in the cache.

```java
public void update() {
  for (int i = 0; i < numEntities; i++) {
    aiComponents[i].update();
  }
  for (int i = 0; i < numEntities; i++) {
    physicsComponents[i].update();
  }
  for (int i = 0; i < numEntities; i++) {
    renderComponents[i].update();
  }
}
```

The `Application` class contains the main method that creates a `GameEntity` object and starts the game loop.

```java
public class Application {
  public static void main(String[] args) {
    var gameEntity = new GameEntity(NUM_ENTITIES);
    gameEntity.start();
    gameEntity.update();
  }
}
```

The console output:

```
10:19:52.155 [main] INFO com.iluwatar.data.locality.Application -- Start Game Application using Data-Locality pattern
10:19:52.157 [main] INFO com.iluwatar.data.locality.game.GameEntity -- Init Game with #Entity : 5
10:19:52.158 [main] INFO com.iluwatar.data.locality.game.GameEntity -- Start Game
10:19:52.158 [main] INFO com.iluwatar.data.locality.game.component.manager.AiComponentManager -- Start AI Game Component
10:19:52.158 [main] INFO com.iluwatar.data.locality.game.component.manager.PhysicsComponentManager -- Start Physics Game Component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.manager.RenderComponentManager -- Start Render Game Component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.GameEntity -- Update Game Component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.manager.AiComponentManager -- Update AI Game Component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.AiComponent -- update AI component
10:19:52.159 [main] INFO com.iluwatar.data.locality.game.component.manager.PhysicsComponentManager -- Update Physics Game Component
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.PhysicsComponent -- Update physics component of game
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.manager.RenderComponentManager -- Update Render Game Component
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component
10:19:52.160 [main] INFO com.iluwatar.data.locality.game.component.RenderComponent -- Render Component
```

In this way, the data-locality module demonstrates the Data Locality pattern. By updating all components of the same type together, it increases the likelihood that the data needed for the update is already in the cache, thereby improving performance.

## [When to Use the Data Locality Pattern in Java](https://java-design-patterns.com/patterns/data-locality/#when-to-use-the-data-locality-pattern-in-java)

This pattern is applicable in scenarios where large datasets are processed and performance is critical. It's particularly useful in:

- Game development for efficient rendering and physics calculations.
- High-performance computing tasks that require rapid access to large data sets.
- Real-time data processing systems where latency is a critical factor.
- Scientific computing applications needing optimized matrix operations.
- Data-intensive applications requiring enhanced memory access patterns.

## [Real-World Applications of Data Locality Pattern in Java](https://java-design-patterns.com/patterns/data-locality/#real-world-applications-of-data-locality-pattern-in-java)

- Game engines (e.g., Unity, Unreal Engine) to optimize entity and component data access.
- High-performance matrix libraries in scientific computing to optimize matrix operations.
- Real-time streaming data processing systems for efficient data manipulation and access.

## [Benefits and Trade-offs of Data Locality Pattern](https://java-design-patterns.com/patterns/data-locality/#benefits-and-trade-offs-of-data-locality-pattern)

Benefits:

- Improved Cache Utilization: By enhancing spatial locality, data frequently accessed together is stored close together in memory, improving cache hit rates.
- Reduced Access Latency: Minimizes the time taken to fetch data from memory, leading to performance improvements.
- Enhanced Performance: Overall system performance is improved due to reduced memory access times and increased efficiency in data processing.

Trade-offs:

- Complexity in Implementation: Managing data layout can add complexity to the system design and implementation.
- Maintenance Overhead: As data access patterns evolve, the layout may need to be re-evaluated, adding to the maintenance overhead.
- Less Flexibility: The tight coupling of data layout to access patterns can reduce flexibility in how data structures are used and evolved over time.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/data-locality/#related-java-design-patterns)

- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Can be used in conjunction with Data Locality to share data efficiently among multiple objects.
- [Object Pool](https://java-design-patterns.com/patterns/object-pool/): Often used together to manage a group of initialized objects that can be reused, further optimizing memory usage and access.
- [Iterator](https://java-design-patterns.com/patterns/iterator/): Facilitates navigation through a collection of data laid out with data locality in mind.

## [References and Credits](https://java-design-patterns.com/patterns/data-locality/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Game Programming Patterns](https://amzn.to/3vK8c0d)
- [High-Performance Java Persistence](https://amzn.to/3TMc8Wd)
- [Java Performance: The Definitive Guide](https://amzn.to/3Ua392J)
- [Game Programming Patterns Optimization Patterns: Data Locality](http://gameprogrammingpatterns.com/data-locality.html)

---

## [performance-optimization/lazy-loading] Lazy Loading
> 官方文档: https://java-design-patterns.com/patterns/lazy-loading/

Performance optimizationInstantiationMemory managementOptimizationPerformancePersistenceResource managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/lazy-loading/#also-known-as)

- Lazy Initialization

## [Intent of Lazy Loading Design Pattern](https://java-design-patterns.com/patterns/lazy-loading/#intent-of-lazy-loading-design-pattern)

The Lazy Loading design pattern in Java defers object initialization until the object is actually needed, minimizing memory usage and reducing startup times. This technique is crucial for optimizing Java application performance.

## [Detailed Explanation of Lazy Loading Pattern with Real-World Examples](https://java-design-patterns.com/patterns/lazy-loading/#detailed-explanation-of-lazy-loading-pattern-with-real-world-examples)

Real-world example

> A real-world analogy for the Lazy Loading pattern in Java is using lights in a smart home. Instead of switching all lights on at once when someone enters the house, motion sensors detect and turn on lights only in rooms being used. This mirrors how Java developers can optimize performance by delaying object creation.

In plain words

> The Lazy Loading pattern defers the creation of an object or resource until it's actually needed, optimizing memory usage and improving performance.

Wikipedia says

> Lazy loading (also known as asynchronous loading) is a technique used in computer programming, especially web design and web development, to defer initialization of an object until it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. This makes it ideal in use cases where network content is accessed and initialization times are to be kept at a minimum, such as in the case of web pages. For example, deferring loading of images on a web page until they are needed for viewing can make the initial display of the web page faster. The opposite of lazy loading is eager loading.

Sequence diagram

![Lazy Loading Sequence Diagram](https://java-design-patterns.com/assets/img/lazy-loading-sequence-diagram.dc18e6ce.png)

## [Programmatic Example of Lazy Loading Pattern in Java](https://java-design-patterns.com/patterns/lazy-loading/#programmatic-example-of-lazy-loading-pattern-in-java)

The Lazy Loading design pattern is a performance optimization technique that delays the initialization of an object or a costly computation until it's absolutely necessary. This pattern can significantly improve the performance of your application by avoiding unnecessary computation and reducing memory usage.

In the provided code, we can see an example of the Lazy Loading pattern in the `App`, `HolderNaive`, `HolderThreadSafe`, and `Java8Holder` classes.

The `App` class is the entry point of the application. It creates instances of `HolderNaive`, `HolderThreadSafe`, and `Java8Holder`, and retrieves the `Heavy` object from them.

```java
@Slf4j
public class App {

  public static void main(String[] args) {

    var holderNaive = new HolderNaive();
    var heavy = holderNaive.getHeavy();
    LOGGER.info("heavy={}", heavy);

    var holderThreadSafe = new HolderThreadSafe();
    var another = holderThreadSafe.getHeavy();
    LOGGER.info("another={}", another);

    var java8Holder = new Java8Holder();
    var next = java8Holder.getHeavy();
    LOGGER.info("next={}", next);
  }
}
```

The `HolderNaive`, `HolderThreadSafe`, and `Java8Holder` classes are implementations of the Lazy Loading pattern with increasing sophistication.

The `HolderNaive` class is a simple, non-thread-safe implementation of the pattern.

```java
public class HolderNaive {
  private Heavy heavy;

  public HolderNaive() {
      LOGGER.info("HolderNaive created");
  }

  public Heavy getHeavy() {
    if (heavy == null) {
      heavy = new Heavy();
    }
    return heavy;
  }
}
```

The `HolderThreadSafe` class is a thread-safe implementation of the pattern, but with heavy synchronization on each access.

```java
public class HolderThreadSafe {
  private Heavy heavy;

  public synchronized Heavy getHeavy() {
    if (heavy == null) {
      heavy = new Heavy();
    }
    return heavy;
  }
}
```

The `Java8Holder` class is the most efficient implementation of the pattern, utilizing Java 8 features.

```java
public class Java8Holder {

  private Supplier<Heavy> heavy = this::createAndCacheHeavy;

  public Java8Holder() {
      LOGGER.info("Java8Holder created");
  }

  public Heavy getHeavy() {
    return heavy.get();
  }

  private synchronized Heavy createAndCacheHeavy() {
    class HeavyFactory implements Supplier<Heavy> {
      private final Heavy heavyInstance = new Heavy();

      public Heavy get() {
        return heavyInstance;
      }
    }

    if (!(heavy instanceof HeavyFactory)) {
      heavy = new HeavyFactory();
    }

    return heavy.get();
  }
}
```

In this example, the `App` class retrieves a `Heavy` object from `HolderNaive`, `HolderThreadSafe`, and `Java8Holder`. These classes delay the creation of the `Heavy` object until it's actually needed, demonstrating the Lazy Loading pattern.

## [When to Use the Lazy Loading Pattern in Java](https://java-design-patterns.com/patterns/lazy-loading/#when-to-use-the-lazy-loading-pattern-in-java)

Use Lazy Loading when:

- An object is resource-intensive to create and might not always be used.
- You need to delay object creation to optimize memory usage or improve startup times.
- Loading data or resources should happen just-in-time rather than at application startup.

## [Real-World Applications of Lazy Loading Pattern in Java](https://java-design-patterns.com/patterns/lazy-loading/#real-world-applications-of-lazy-loading-pattern-in-java)

- Hibernate (Java ORM Framework): Delays loading of related objects until they are accessed, leveraging the Lazy Loading pattern to optimize Java application performance.
- JPA annotations @OneToOne, @OneToMany, @ManyToOne, @ManyToMany and fetch = FetchType.LAZY
- Spring Framework (Dependency Injection): Loads beans only when required, reducing application startup time.

## [Benefits and Trade-offs of Lazy Loading Pattern](https://java-design-patterns.com/patterns/lazy-loading/#benefits-and-trade-offs-of-lazy-loading-pattern)

Benefits:

- Reduces memory usage by initializing objects only when required.
- Improves application startup performance by postponing expensive object creation.

Trade-offs:

- Complexity in implementation if objects are interdependent.
- Risk of latency spikes if initialization occurs at an unexpected point.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/lazy-loading/#related-java-design-patterns)

- [Proxy](https://java-design-patterns.com/patterns/proxy/): Can act as a placeholder for lazy-loaded objects, deferring their actual loading until necessary.
- Virtual Proxy: Specific type of Proxy that handles object creation on demand.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Often combined with Lazy Loading to ensure only one instance of an object is created and loaded lazily.

## [References and Credits](https://java-design-patterns.com/patterns/lazy-loading/#references-and-credits)

- [J2EE Design Patterns](https://amzn.to/4dpzgmx)
- [Java Performance: The Definitive Guide: Getting the Most Out of Your Code](https://amzn.to/3Wu5neF)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

<!-- ============================================ -->
<!-- Resource Management 资源管理模式 (3 个) -->
<!-- ============================================ -->

## [resource-management/resource-acquisition-is-initialization] Resource Acquisition Is Initialization
> 官方文档: https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/

Resource managementEncapsulationMemory managementResource managementAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#also-known-as)

- RAII
- Scope-based Resource Management

## [Intent of Resource Acquisition Is Initialization Design Pattern](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#intent-of-resource-acquisition-is-initialization-design-pattern)

Ensure efficient Java resource management by tying the resource lifecycle to object lifetime, utilizing the RAII pattern.

## [Detailed Explanation of Resource Acquisition Is Initialization Pattern with Real-World Examples](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#detailed-explanation-of-resource-acquisition-is-initialization-pattern-with-real-world-examples)

Real-world example

> In a car rental service, each car represents a resource. Using the RAII pattern, when a customer rents a car (acquires the resource), the car is marked as rented. When the customer returns the car (the object goes out of scope), the car is automatically made available for the next customer. This ensures that cars are properly managed and available without manual intervention for checking availability or returns.

In plain words

> The RAII pattern in Java allows for exception-safe resource management, ensuring robust handling of critical resources.

Wikipedia says

> Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically typed programming languages to describe a particular language behavior. Resource allocation (or acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the destructor.

Sequence diagram

![Resource Acquisition Is Initialization sequence diagram](https://java-design-patterns.com/assets/img/raii-sequence-diagram.fc3d918b.png)

## [Programmatic Example of RAII Pattern in Java](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#programmatic-example-of-raii-pattern-in-java)

The RAII pattern is a common idiom used in software design where the acquisition of a resource is done during object creation (initialization), and the release of the resource is done during object destruction. This pattern is particularly useful in dealing with resource leaks and is critical in writing exception-safe code in C++. In Java, RAII is achieved with try-with-resources statement and interfaces `java.io.Closeable` and `AutoCloseable`.

```java
// This is an example of a resource class that implements the AutoCloseable interface.
// The resource is acquired in the constructor and released in the close method.

@Slf4j
public class SlidingDoor implements AutoCloseable {

  public SlidingDoor() {
    LOGGER.info("Sliding door opens."); // Resource acquisition is done here
  }

  @Override
  public void close() {
    LOGGER.info("Sliding door closes."); // Resource release is done here
  }
}
```

In the above code, `SlidingDoor` is a resource that implements the `AutoCloseable` interface. The resource (in this case, a door) is "acquired" in the constructor (the door is opened), and "released" in the `close` method (the door is closed).

```java
// This is another example of a resource class that implements the Closeable interface.
// The resource is acquired in the constructor and released in the close method.

@Slf4j
public class TreasureChest implements Closeable {

  public TreasureChest() {
    LOGGER.info("Treasure chest opens."); // Resource acquisition is done here
  }

  @Override
  public void close() {
    LOGGER.info("Treasure chest closes."); // Resource release is done here
  }
}
```

Similarly, `TreasureChest` is another resource that implements the `Closeable` interface. The resource (a treasure chest) is "acquired" in the constructor (the chest is opened), and "released" in the `close` method (the chest is closed).

```java
// This is an example of how to use the RAII pattern in Java using the try-with-resources statement.

@Slf4j
public class App {

  public static void main(String[] args) {

    try (var ignored = new SlidingDoor()) {
      LOGGER.info("Walking in.");
    }

    try (var ignored = new TreasureChest()) {
      LOGGER.info("Looting contents.");
    }
  }
}
```

In the `main` method of the `App` class, we see the RAII pattern in action. The `try-with-resources` statement is used to ensure that each resource is closed at the end of the statement. This is where the `AutoCloseable` or `Closeable` interfaces come into play. When the `try` block is exited (either normally or via an exception), the `close` method of the resource is automatically called, thus ensuring the resource is properly released.

The console output:

```
10:07:14.833 [main] INFO com.iluwatar.resource.acquisition.is.initialization.SlidingDoor -- Sliding door opens.
10:07:14.835 [main] INFO com.iluwatar.resource.acquisition.is.initialization.App -- Walking in.
10:07:14.835 [main] INFO com.iluwatar.resource.acquisition.is.initialization.SlidingDoor -- Sliding door closes.
10:07:14.835 [main] INFO com.iluwatar.resource.acquisition.is.initialization.TreasureChest -- Treasure chest opens.
10:07:14.835 [main] INFO com.iluwatar.resource.acquisition.is.initialization.App -- Looting contents.
10:07:14.835 [main] INFO com.iluwatar.resource.acquisition.is.initialization.TreasureChest -- Treasure chest closes.
```

## [When to Use the Resource Acquisition Is Initialization Pattern in Java](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#when-to-use-the-resource-acquisition-is-initialization-pattern-in-java)

- Implement RAII in Java applications to manage essential resources such as file handles, network connections, and memory seamlessly.
- Suitable in environments where deterministic resource management is crucial, such as real-time systems or applications with strict resource constraints.

## [Real-World Applications of RAII Pattern in Java](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#real-world-applications-of-raii-pattern-in-java)

- Java `try-with-resources` statement: Ensures that resources are closed automatically at the end of the statement.
- Database connections: Using connection pools where the connection is obtained at the beginning of a scope and released at the end.
- File I/O: Automatically closing files using `try-with-resources`.

## [Benefits and Trade-offs of Resource Acquisition Is Initialization Pattern](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#benefits-and-trade-offs-of-resource-acquisition-is-initialization-pattern)

Benefits:

- Automatic and deterministic resource management.
- Reduces the likelihood of resource leaks.
- Enhances code readability and maintainability by clearly defining the scope of resource usage.

Trade-offs:

- May introduce complexity in understanding object lifetimes.
- Requires careful design to ensure all resources are correctly encapsulated.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#related-java-design-patterns)

- [Object Pool](https://java-design-patterns.com/patterns/object-pool/): Manages a pool of reusable objects to optimize resource allocation and performance, often used for resources that are expensive to create and manage.

## [References and Credits](https://java-design-patterns.com/patterns/resource-acquisition-is-initialization/#references-and-credits)

- [Effective Java](https://amzn.to/4cGk2Jz)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Resource acquisition is initialization](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization)

---

## [resource-management/server-session] Server Session
> 官方文档: https://java-design-patterns.com/patterns/server-session/

Resource managementClient-serverCookiesSession managementState trackingWeb developmentAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/server-session/#also-known-as)

- Server-Side Session Management

## [Intent of Server Session Design Pattern](https://java-design-patterns.com/patterns/server-session/#intent-of-server-session-design-pattern)

Effectively manage user session data on the server-side with Java's Server Session pattern to maintain consistent state across multiple client interactions, enhancing both security and user experience.

## [Detailed Explanation of Server Session Pattern with Real-World Examples](https://java-design-patterns.com/patterns/server-session/#detailed-explanation-of-server-session-pattern-with-real-world-examples)

Real-world example

> Imagine a hotel where each guest is given a unique room key card upon check-in. Similar to how a hotel key card stores a guest's personal preferences (such as preferred room temperature, wake-up call times, and minibar choices), the Server Session pattern in Java securely stores user preferences server-side, ensuring a personalized and secure user experience. Whenever the guest interacts with hotel services, such as ordering room service or accessing the gym, the system retrieves their preferences using the information on the key card. The hotel’s central server maintains these preferences, ensuring consistent and personalized service throughout the guest's stay. Similarly, the Server Session design pattern manages user data on the server, providing a seamless experience across multiple interactions within a web application.

In plain words

> The Server Session design pattern manages and stores user session data on the server to maintain state across multiple client requests in web applications.

Wikipedia says

> A session token is a unique identifier that is generated and sent from a server to a client to identify the current interaction session. The client usually stores and sends the token as an HTTP cookie and/or sends it as a parameter in GET or POST queries. The reason to use session tokens is that the client only has to handle the identifier—all session data is stored on the server (usually in a database, to which the client does not have direct access) linked to that identifier.

Sequence diagram

![Server Session sequence diagram](https://java-design-patterns.com/assets/img/server-session-sequence-diagram.90cc9920.png)

## [Programmatic Example of Server Session Pattern in Java](https://java-design-patterns.com/patterns/server-session/#programmatic-example-of-server-session-pattern-in-java)

The Server Session design pattern is a behavioral design pattern that assigns the responsibility of storing session data on the server side. This pattern is particularly useful in the context of stateless protocols like HTTP where all requests are isolated events independent of previous requests.

In this pattern, when a user logs in, a session identifier is created and stored for future requests in a list. When a user logs out, the session identifier is deleted from the list along with the appropriate user session data.

Let's take a look at a programmatic example of the Server Session design pattern.

The `main` application starts a server and assigns handlers to manage login and logout requests. It also starts a background task to check for expired sessions.

```java
public class App {

  private static Map<String, Integer> sessions = new HashMap<>();
  private static Map<String, Instant> sessionCreationTimes = new HashMap<>();
  private static final long SESSION_EXPIRATION_TIME = 10000;

  public static void main(String[] args) throws IOException {
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

    server.createContext("/login", new LoginHandler(sessions, sessionCreationTimes));
    server.createContext("/logout", new LogoutHandler(sessions, sessionCreationTimes));

    server.start();

    sessionExpirationTask();
  }

  private static void sessionExpirationTask() {
    new Thread(() -> {
      while (true) {
        try {
          Thread.sleep(SESSION_EXPIRATION_TIME);
          Instant currentTime = Instant.now();
          synchronized (sessions) {
            synchronized (sessionCreationTimes) {
              Iterator<Map.Entry<String, Instant>> iterator =
                  sessionCreationTimes.entrySet().iterator();
              while (iterator.hasNext()) {
                Map.Entry<String, Instant> entry = iterator.next();
                if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) {
                  sessions.remove(entry.getKey());
                  iterator.remove();
                }
              }
            }
          }
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
    }).start();
  }
}
```

The `LoginHandler` is responsible for handling login requests. When a user logs in, a session identifier is created and stored for future requests in a list.

```java
public class LoginHandler {

  private Map<String, Integer> sessions;
  private Map<String, Instant> sessionCreationTimes;

  public LoginHandler(Map<String, Integer> sessions, Map<String, Instant> sessionCreationTimes) {
    this.sessions = sessions;
    this.sessionCreationTimes = sessionCreationTimes;
  }

  public void handle(HttpExchange exchange) {
    // Implementation of the handle method
  }
}
```

The `LogoutHandler` is responsible for handling logout requests. When a user logs out, the session identifier is deleted from the list along with the appropriate user session data.

```java
public class LogoutHandler {

  private Map<String, Integer> sessions;
  private Map<String, Instant> sessionCreationTimes;

  public LogoutHandler(Map<String, Integer> sessions, Map<String, Instant> sessionCreationTimes) {
    this.sessions = sessions;
    this.sessionCreationTimes = sessionCreationTimes;
  }

  public void handle(HttpExchange exchange) {
    // Implementation of the handle method
  }
}
```

Console output for starting the `App` class's `main` method:

```
12:09:50.998 [Thread-1] INFO com.iluwatar.sessionserver.App -- Session expiration checker started...
12:09:50.998 [main] INFO com.iluwatar.sessionserver.App -- Server started. Listening on port 8080...
```

This is a basic example of the Server Session design pattern. The actual implementation of the `handle` methods in the `LoginHandler` and `LogoutHandler` classes would depend on the specific requirements of your application.

## [When to Use the Server Session Pattern in Java](https://java-design-patterns.com/patterns/server-session/#when-to-use-the-server-session-pattern-in-java)

- Use when building web applications that require maintaining user state information across multiple requests.
- Suitable for applications needing to track user interactions, preferences, or authentication state.
- Ideal for scenarios where client-side storage is insecure or insufficient.

## [Real-World Applications of Server Session Pattern in Java](https://java-design-patterns.com/patterns/server-session/#real-world-applications-of-server-session-pattern-in-java)

- Java EE applications using HttpSession for session management.
- Spring Framework's `@SessionAttributes` for handling user session data.
- Apache Tomcat's session management mechanism.

## [Benefits and Trade-offs of Server Session Pattern](https://java-design-patterns.com/patterns/server-session/#benefits-and-trade-offs-of-server-session-pattern)

Benefits:

- Simplifies client-side logic by offloading state management to the server.
- Enhances security by storing sensitive information server-side.
- Supports complex state management scenarios like multistep forms or shopping carts.

Trade-offs:

- Increases server memory usage due to storage of session data.
- Requires session management logic to handle session timeouts and data persistence.
- Potential scalability issues with high user concurrency.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/server-session/#related-java-design-patterns)

- [State](https://java-design-patterns.com/patterns/state/): Manages state-specific behavior, which can be utilized within session management to handle different user states.
- [Proxy](https://java-design-patterns.com/patterns/proxy/): Can be used to add a layer of control over session data access.
- [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used to create a single instance of a session manager.

## [References and Credits](https://java-design-patterns.com/patterns/server-session/#references-and-credits)

- [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
- [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
- [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)

---

## [resource-management/throttling] Throttling
> 官方文档: https://java-design-patterns.com/patterns/throttling/

Resource managementAPI designFault tolerancePerformanceResilienceScalabilityAbout 5 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/throttling/#also-known-as)

- Rate Limiting

## [Intent of Throttling Design Pattern](https://java-design-patterns.com/patterns/throttling/#intent-of-throttling-design-pattern)

The Throttling Pattern, also known as Rate Limiting, limits the number of requests a system can process within a given time frame to prevent overload and ensure stability. It is crucial for resource management in Java applications.

## [Detailed Explanation of Throttling Pattern with Real-World Examples](https://java-design-patterns.com/patterns/throttling/#detailed-explanation-of-throttling-pattern-with-real-world-examples)

Real-world example

> Imagine a popular amusement park that limits the number of visitors who can enter per hour to prevent overcrowding. This ensures that all visitors can enjoy the park without long wait times and maintain a pleasant experience. Similarly, the Throttling design pattern in software controls the rate of requests to a system, preventing it from being overwhelmed and ensuring consistent performance for all users.

In plain words

> Throttling pattern is used to rate-limit access to a resource.

[Microsoft documentation](https://docs.microsoft.com/en-us/azure/architecture/patterns/throttling) says

> Control the consumption of resources used by an instance of an application, an individual tenant, or an entire service. This can allow the system to continue to function and meet service level agreements, even when an increase in demand places an extreme load on resources.

Flowchart

![Throttling Pattern Flowchart](https://java-design-patterns.com/assets/img/throttling-flowchart.1cd42a2f.png)

## [Programmatic Example of Throttling Pattern in Java](https://java-design-patterns.com/patterns/throttling/#programmatic-example-of-throttling-pattern-in-java)

In this Java example, we demonstrate throttling. A young human and an old dwarf walk into a bar. They start ordering beers from the bartender. The bartender immediately sees that the young human shouldn't consume too many drinks too fast and refuses to serve if enough time has not passed. For the old dwarf, the serving rate can be higher.

`BarCustomer` class presents the clients of the `Bartender` API. `CallsCount` tracks the number of calls per `BarCustomer`.

```java
@Getter
public class BarCustomer {

    private final String name;
    private final int allowedCallsPerSecond;

    public BarCustomer(String name, int allowedCallsPerSecond, CallsCount callsCount) {
        if (allowedCallsPerSecond < 0) {
            throw new InvalidParameterException("Number of calls less than 0 not allowed");
        }
        this.name = name;
        this.allowedCallsPerSecond = allowedCallsPerSecond;
        callsCount.addTenant(name);
    }
}
```

```java
@Slf4j
public final class CallsCount {
    private final Map<String, AtomicLong> tenantCallsCount = new ConcurrentHashMap<>();

    public void addTenant(String tenantName) {
        tenantCallsCount.putIfAbsent(tenantName, new AtomicLong(0));
    }

    public void incrementCount(String tenantName) {
        tenantCallsCount.get(tenantName).incrementAndGet();
    }

    public long getCount(String tenantName) {
        return tenantCallsCount.get(tenantName).get();
    }

    public void reset() {
        tenantCallsCount.replaceAll((k, v) -> new AtomicLong(0));
        LOGGER.info("reset counters");
    }
}
```

Next, the service that the tenants are calling is introduced. To track the call count, a throttler timer is used.

```java
public interface Throttler {
    void start();
}
```

```java
public class ThrottleTimerImpl implements Throttler {

    private final int throttlePeriod;
    private final CallsCount callsCount;

    public ThrottleTimerImpl(int throttlePeriod, CallsCount callsCount) {
        this.throttlePeriod = throttlePeriod;
        this.callsCount = callsCount;
    }

    @Override
    public void start() {
        new Timer(true).schedule(new TimerTask() {
            @Override
            public void run() {
                callsCount.reset();
            }
        }, 0, throttlePeriod);
    }
}
```

`Bartender` offers the `orderDrink` service to the `BarCustomer`s. The customers probably don't know that the beer serving rate is limited by their appearances.

```java
class Bartender {

    private static final Logger LOGGER = LoggerFactory.getLogger(Bartender.class);
    private final CallsCount callsCount;

    public Bartender(Throttler timer, CallsCount callsCount) {
        this.callsCount = callsCount;
        timer.start();
    }

    public int orderDrink(BarCustomer barCustomer) {
        var tenantName = barCustomer.getName();
        var count = callsCount.getCount(tenantName);
        if (count >= barCustomer.getAllowedCallsPerSecond()) {
            LOGGER.error("I'm sorry {}, you've had enough for today!", tenantName);
            return -1;
        }
        callsCount.incrementCount(tenantName);
        LOGGER.debug("Serving beer to {} : [{} consumed] ", barCustomer.getName(), count + 1);
        return getRandomCustomerId();
    }

    private int getRandomCustomerId() {
        return ThreadLocalRandom.current().nextInt(1, 10000);
    }
}
```

Now it is possible to see the full example in action. `BarCustomer` young human is rate-limited to 2 calls per second and the old dwarf to 4.

```java
@Slf4j
public class App {

    public static void main(String[] args) {
        var callsCount = new CallsCount();
        var human = new BarCustomer("young human", 2, callsCount);
        var dwarf = new BarCustomer("dwarf soldier", 4, callsCount);

        var executorService = Executors.newFixedThreadPool(2);

        executorService.execute(() -> makeServiceCalls(human, callsCount));
        executorService.execute(() -> makeServiceCalls(dwarf, callsCount));

        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }

    private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) {
        var timer = new ThrottleTimerImpl(1000, callsCount);
        var service = new Bartender(timer, callsCount);
        // Sleep is introduced to keep the output in check and easy to view and analyze the results.
        IntStream.range(0, 50).forEach(i -> {
            service.orderDrink(barCustomer);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                LOGGER.error("Thread interrupted: {}", e.getMessage());
            }
        });
    }
}
```

An excerpt from the example's console output:

```
18:46:36.218 [Timer-0] INFO com.iluwatar.throttling.CallsCount - reset counters
18:46:36.218 [Timer-1] INFO com.iluwatar.throttling.CallsCount - reset counters
18:46:36.242 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [1 consumed]
18:46:36.242 [pool-1-thread-1] DEBUG com.iluwatar.throttling.Bartender - Serving beer to young human : [1 consumed]
18:46:36.342 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [2 consumed]
18:46:36.342 [pool-1-thread-1] DEBUG com.iluwatar.throttling.Bartender - Serving beer to young human : [2 consumed]
18:46:36.443 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:36.443 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [3 consumed]
18:46:36.544 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:36.544 [pool-1-thread-2] DEBUG com.iluwatar.throttling.Bartender - Serving beer to dwarf soldier : [4 consumed]
18:46:36.645 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today!
18:46:36.645 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:36.745 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:36.745 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today!
18:46:36.846 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:36.846 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today!
18:46:36.947 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today!
18:46:36.947 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:37.048 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today!
18:46:37.048 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:37.148 [pool-1-thread-1] ERROR com.iluwatar.throttling.Bartender - I'm sorry young human, you've had enough for today!
18:46:37.148 [pool-1-thread-2] ERROR com.iluwatar.throttling.Bartender - I'm sorry dwarf soldier, you've had enough for today!
```

## [When to Use the Throttling Pattern in Java](https://java-design-patterns.com/patterns/throttling/#when-to-use-the-throttling-pattern-in-java)

- You need to protect resources from being overwhelmed by too many requests.
- You want to ensure fair usage of a service among multiple users.
- You need to maintain the quality of service under high load conditions.

## [Real-World Applications of Throttling Pattern in Java](https://java-design-patterns.com/patterns/throttling/#real-world-applications-of-throttling-pattern-in-java)

- APIs of major cloud providers like AWS, Google Cloud, and Azure use throttling to manage resource usage.
- Web services to prevent denial-of-service (DoS) attacks by limiting the number of requests from a single IP address.
- Online platforms like social media sites and e-commerce websites to ensure even distribution of server load.

## [Benefits and Trade-offs of Throttling Pattern](https://java-design-patterns.com/patterns/throttling/#benefits-and-trade-offs-of-throttling-pattern)

Benefits:

- Prevents resource exhaustion, ensuring system stability.
- Helps in maintaining consistent performance and quality of service.
- Improves fault tolerance by avoiding system crashes under high load.

Trade-offs:

- May cause increased latency or delay in request processing.
- Requires careful tuning to balance between resource protection and user experience.
- Could lead to denial of service to legitimate users if not configured correctly.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/throttling/#related-java-design-patterns)

- [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Works in tandem with throttling to prevent repeated attempts to access an overloaded service.
- Bulkhead: Isolates different parts of the system to limit the impact of throttling on other components.

## [References and Credits](https://java-design-patterns.com/patterns/throttling/#references-and-credits)

- [Throttling pattern (Microsoft)](https://docs.microsoft.com/en-us/azure/architecture/patterns/throttling)
- [Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications](https://amzn.to/4dLvowg)

---

<!-- ============================================ -->
<!-- Idiom 惯用法模式 (1 个) -->
<!-- ============================================ -->

## [idiom/immutable] Immutable
> 官方文档: https://java-design-patterns.com/patterns/immutable/

IdiomImmutabilityThread safetyConcurrencyObject compositionAbout 3 min

* * *

## [Also known as](https://java-design-patterns.com/patterns/immutable/#also-known-as)

Value Object (when applied strictly to small domain values)

## [Intent of Immutable Design Pattern](https://java-design-patterns.com/patterns/immutable/#intent-of-immutable-design-pattern)

Ensure that an object's state cannot be changed after it is constructed, making it inherently thread-safe and easier to reason about.

## [Detailed Explanation of Immutable Pattern with Real-World Examples](https://java-design-patterns.com/patterns/immutable/#detailed-explanation-of-immutable-pattern-with-real-world-examples)

Real-world example

> A birth certificate is a perfect real-world analogy for the Immutable pattern. Once issued, a birth certificate records a person's name, date of birth, and place of birth permanently. You cannot alter the certificate itself; if a legal correction is needed, a new certificate is issued. The original document remains unchanged, guaranteeing that every copy handed to a bank, school, or government office reflects exactly the same facts.

In plain words

> An immutable object is one whose state is fixed at construction time and can never change. Instead of modifying an existing object, you create a new one with the desired state.

Wikipedia says

> In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

## [Programmatic Example of Immutable Pattern in Java](https://java-design-patterns.com/patterns/immutable/#programmatic-example-of-immutable-pattern-in-java)

The core of the pattern is `ImmutableUser`. All fields are `final`, the mutable `roles` list is defensively copied via `List.copyOf`, and "mutation" is expressed by returning a new instance.

```java
public final class ImmutableUser {

  private final String name;
  private final int age;
  private final List<String> roles;

  public ImmutableUser(String name, int age, List<String> roles) {
    this.name = name;
    this.age = age;
    this.roles = List.copyOf(roles);
  }

  public String getName() { return name; }
  public int getAge()     { return age; }
  public List<String> getRoles() { return roles; }

  public ImmutableUser withAge(int newAge) {
    return new ImmutableUser(this.name, newAge, this.roles);
  }
}
```

`App` demonstrates the pattern in action:

```java
var alice = new ImmutableUser("Alice", 30, List.of("admin", "user"));
LOGGER.info("Original user: {}", alice);

var olderAlice = alice.withAge(31);
LOGGER.info("Updated user (new object): {}", olderAlice);
LOGGER.info("Original is unchanged: {}", alice);

var mutableRoles = new ArrayList<>(List.of("viewer"));
var bob = new ImmutableUser("Bob", 25, mutableRoles);
mutableRoles.add("editor");
LOGGER.info("Bob's roles (unchanged despite external list mutation): {}", bob.getRoles());
```

Running the example produces output similar to:

```
INFO  com.iluwatar.immutable.App - Original user: ImmutableUser{name='Alice', age=30, roles=[admin, user]}
INFO  com.iluwatar.immutable.App - Updated user (new object): ImmutableUser{name='Alice', age=31, roles=[admin, user]}
INFO  com.iluwatar.immutable.App - Original is unchanged: ImmutableUser{name='Alice', age=30, roles=[admin, user]}
INFO  com.iluwatar.immutable.App - Bob's roles (unchanged despite external list mutation): [viewer]
```

## [When to Use the Immutable Pattern in Java](https://java-design-patterns.com/patterns/immutable/#when-to-use-the-immutable-pattern-in-java)

- When objects are shared across threads and synchronization overhead is undesirable.
- When you need objects to be used safely as map keys or in sets (consistent `hashCode`).
- When you want to model value types such as money, dates, or coordinates.
- When defensive programming is critical and you must prevent accidental state corruption.

## [Real-World Applications of Immutable Pattern in Java](https://java-design-patterns.com/patterns/immutable/#real-world-applications-of-immutable-pattern-in-java)

- `java.lang.String` — the quintessential immutable class in the JDK.
- `java.time.LocalDate`, `LocalDateTime` — immutable date/time representations.
- `java.math.BigDecimal`, `BigInteger` — immutable numeric types.
- Record classes introduced in Java 16 — compiler-generated immutable data carriers.

## [Benefits and Trade-offs of Immutable Pattern](https://java-design-patterns.com/patterns/immutable/#benefits-and-trade-offs-of-immutable-pattern)

Benefits:

- **Thread safety**: No synchronization needed; immutable objects can be shared freely across threads.
- **Simplicity**: Absence of state changes eliminates a whole category of bugs.
- **Safe sharing**: Can be freely passed to untrusted code without defensive copying at call sites.
- **Cache-friendly**: Immutable objects can be cached, interned, or pre-computed without risk.

Trade-offs:

- **Object creation overhead**: Every logical "update" allocates a new object, which may pressure the garbage collector in hot paths.
- **Verbose construction**: Complex objects often require a Builder to avoid unwieldy constructors.
- **Not always applicable**: Objects that model inherently stateful entities (e.g., a network connection) cannot reasonably be immutable.

## [Related Java Design Patterns](https://java-design-patterns.com/patterns/immutable/#related-java-design-patterns)

- [Value Object](https://java-design-patterns.com/patterns/value-object/): Overlapping concept; value objects are typically immutable and compared by value rather than identity.
- [Builder](https://java-design-patterns.com/patterns/builder/): Commonly paired with Immutable to construct complex objects step-by-step before freezing them.
- [Prototype](https://java-design-patterns.com/patterns/prototype/): Cloning a mutable object is an alternative to immutability when shared state must occasionally change.
- [Flyweight](https://java-design-patterns.com/patterns/flyweight/): Leverages immutability to safely share fine-grained objects across many contexts.

## [References and Credits](https://java-design-patterns.com/patterns/immutable/#references-and-credits)

- [Effective Java, 3rd Edition — Item 17: Minimize Mutability](https://amzn.to/3JIYJoL)
- [Java Concurrency in Practice](https://amzn.to/3vXyUEh)
- [Clean Code: A Handbook of Agile Software Craftsmanship](https://amzn.to/3JIYJoL)
- [Wikipedia — Immutable object](https://en.wikipedia.org/wiki/Immutable_object)

---

<!-- ============================================ -->
<!-- Service Discovery 服务发现模式 (1 个) -->
<!-- ============================================ -->

## [service-discovery/microservices-self-registration] Microservices Self-Registration
> 官方文档: https://java-design-patterns.com/patterns/microservices-self-registration/

Service DiscoveryMicroservicesSelf-RegistrationService DiscoveryEurekaSpring BootSpring CloudJavaDynamic ConfigurationResilienceAbout 6 min

* * *

## [Intent of Microservices Self-Registration Pattern](https://java-design-patterns.com/patterns/microservices-self-registration/#intent-of-microservices-self-registration-pattern)

The intent of the Self-Registration pattern is to enable microservices to automatically announce their presence and location to a central registry (like Eureka) upon startup, simplifying service discovery and allowing other services to find and communicate with them without manual configuration or hardcoded addresses. This promotes dynamic and resilient microservices architectures.

## [What's in the Project](https://java-design-patterns.com/patterns/microservices-self-registration/#what-s-in-the-project)

This project demonstrates the Microservices Self-Registration pattern using Java, Spring Boot (version 3.4.4), and Eureka for service discovery. It consists of three main components: a Eureka Server and two simple microservices, a Greeting Service and a Context Service, which discover and communicate with each other.

### [Project Structure](https://java-design-patterns.com/patterns/microservices-self-registration/#project-structure)

- **`eureka-server`:** The central service registry where microservices register themselves.
- **`greeting-service`:** A simple microservice that provides a greeting.
- **`context-service`:** A microservice that consumes the greeting from the Greeting Service and adds context.

The **Eureka Server** acts as the discovery service. Microservices register themselves with the Eureka Server, providing their network location.

```
package com.example.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
```

The **Greeting Service** is a simple microservice that exposes an endpoint to retrieve a greeting.

```
package com.example.greetingservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class GreetingServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GreetingServiceApplication.class, args);
    }
}
```

Greeting Controller

```
package com.example.greetingservice.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @GetMapping("/greeting")
    public String getGreeting() {
        return "Hello";
    }
}
```

The **Context Service** consumes the greeting from the Greeting Service using OpenFeign and adds contextual information.

```
package com.example.contextservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ContextServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ContextServiceApplication.class, args);
    }
}
```

Feign Client : Spring Cloud OpenFeign is a declarative HTTP client that makes it easier to consume RESTful web services in your Spring Cloud applications. Instead of writing the boilerplate code for making HTTP requests, you simply declare interface with annotations that describe the web service you want to consume.

```
package com.example.contextservice.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "greeting-service")
public interface GreetingServiceClient {

    @GetMapping("/greeting")
    String getGreeting();
}
```

Context Controller

```
package com.example.contextservice.controller;

import com.example.contextservice.client.GreetingServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ContextController {

    @Autowired
    private GreetingServiceClient greetingServiceClient;

    @Value("${user.region}")
    private String userRegion;

    @GetMapping("/context")
    public String getContext() {
        String greeting = greetingServiceClient.getGreeting();
        return "The Greeting Service says: " + greeting + " from " + userRegion + "!";
    }
}
```

1. Both the Greeting Service and the Context Service register themselves with the Eureka Server upon startup using the _@EnableDiscoveryClient_ annotation.
2. The Context Service, annotated with _@EnableFeignClients_, uses the GreetingServiceClient interface with _@FeignClient(name = "greeting-service")_ to declare its intent to communicate with the service named "greeting-service" in Eureka.
3. When the /context endpoint of the Context Service is accessed, it calls the _getGreeting()_ method of the GreetingServiceClient.
4. OpenFeign, leveraging the service discovery information from Eureka, resolves the network location of an available instance of the Greeting Service and makes an HTTP GET request to its /greeting endpoint.
5. The Greeting Service responds with "Hello", and the Context Service then adds the configured user.region to the response.

This project utilizes Spring Boot Actuator, which is included as a dependency, to provide health check endpoints for each microservice. These endpoints (e.g., /actuator/health) can be used by Eureka Server to monitor the health of the registered instances.

## [Steps to use for this Project](https://java-design-patterns.com/patterns/microservices-self-registration/#steps-to-use-for-this-project)

Prerequisites:

- Java Development Kit (JDK): Make sure you have a compatible JDK installed (ideally Java 17 or later, as Spring Boot 3.x requires it).
- Maven or Gradle: You'll need either Maven (if you chose Maven during Spring Initializr setup) or Gradle (if you chose Gradle) installed on your system.
- An IDE (Optional but Recommended): IntelliJ IDEA, Eclipse, or Spring Tool Suite (STS) can make it easier to work with the project.
- Web Browser: You'll need a web browser to access the Eureka dashboard and the microservice endpoints.

Step :

- You'll need to build each microservice individually. Navigate to the root directory of each project in your terminal or command prompt and run the appropriate build command:

_cd eurekaserver_

_mvn clean install_

_cd ../greetingservice_

_mvn clean install_

_cd ../contextservice_

_mvn clean install_

Step :
- Navigate to the root directory of your eurekaserver project in your terminal or command prompt

_mvn spring-boot:run_
- Wait for the Eureka Server application to start. You should see logs in the console indicating that it has started on port 8761 (as configured).
- Open your web browser and go to [http://localhost:8761/](http://localhost:8761/). You should see the Eureka Server dashboard. Initially, the list of registered instances will be empty.

Step :
- Run the Greeting Service
  - Open a new terminal or command prompt.
  - Navigate to the root directory of your greetingservice project.
  - Run the Spring Boot application: _mvn spring-boot:run_
  - Wait for the Greeting Service to start. You should see logs indicating that it has registered with the Eureka Server.
  - Go back to your Eureka Server dashboard in the browser ( [http://localhost:8761/](http://localhost:8761/)). You should now see GREETINGSERVICE listed under the "Instances currently registered with Eureka". Its status should be "UP".

     Step :
- Run the Context Service
  - Open a new terminal or command prompt.
  - Navigate to the root directory of your contextservice project.
  - Run the Spring Boot application: _mvn spring-boot:run_
  - Wait for the Context Service to start. You should see logs indicating that it has registered with the Eureka Server.
  - Go back to your Eureka Server dashboard in the browser ( [http://localhost:8761/](http://localhost:8761/)). You should now see CONTEXTSERVICE listed under the "Instances currently registered with Eureka". Its status should be "UP".

     STEP :
  - Test the Greeting Service Directly: Open your web browser and go to [http://localhost:8081/greeting](http://localhost:8081/greeting). You should see the output: Hello.
  - Test the Context Service (which calls the Greeting Service): Open your web browser and go to [http://localhost:8082/context](http://localhost:8082/context). You should see the output: The Greeting Service says: Hello from Chennai, Tamil Nadu, India!. This confirms that the Context Service successfully discovered and called the Greeting Service through Eureka.

Optional: Check Health Endpoints

You can also verify the health status of each service using Spring Boot Actuator:

- Greeting Service Health: [http://localhost:8081/actuator/health](http://localhost:8081/actuator/health) (should return {"status":"UP"})
- Context Service Health: [http://localhost:8082/actuator/health](http://localhost:8082/actuator/health) (should return {"status":"UP"})
- Eureka Server Health: [http://localhost:8761/actuator/health](http://localhost:8761/actuator/health) (should return {"status":"UP"})

## [When to use Microservices Self-Registration Pattern](https://java-design-patterns.com/patterns/microservices-self-registration/#when-to-use-microservices-self-registration-pattern)

- **Dynamic Environments:** When your microservices are frequently deployed, scaled up or down, or their network locations (IP addresses and ports) change often. This is common in cloud-based or containerized environments (like Docker and Kubernetes).
- **Large Number of Services:** As the number of microservices in your system grows, manually managing their configurations and dependencies becomes complex and error-prone. Self-registration automates this process.
- **Need for Automatic Service** Discovery: When services need to find and communicate with each other without hardcoding network locations. This allows for greater flexibility and reduces coupling.
- **Implementing Load Balancing:** Service registries like Eureka often integrate with load balancers, enabling them to automatically distribute traffic across available instances of a service that have registered themselves.
- **Improving System Resilience:** If a service instance fails, the registry will eventually be updated (through heartbeats or health checks), and other services can discover and communicate with the remaining healthy instances.
- **DevOps Automation:** This pattern aligns well with DevOps practices, allowing for more automated deployment and management of microservices.

## [Real-World Applications of Self-Registration pattern](https://java-design-patterns.com/patterns/microservices-self-registration/#real-world-applications-of-self-registration-pattern)

- E-Commerce platforms have numerous independent services for product catalogs, order processing, payments, shipping, etc. Self-registration allows these services to dynamically discover and communicate with each other as the system scales during peak loads or as new features are deployed.
- Streaming services rely on many microservices for user authentication, content delivery networks (CDNs), recommendation engines, billing systems, etc. Self-registration helps these services adapt to varying user demands and infrastructure changes.
- Social media These platforms use microservices for managing user profiles, timelines, messaging, advertising, and more. Self-registration enables these services to scale independently and handle the massive traffic they experience.

## [Advantages](https://java-design-patterns.com/patterns/microservices-self-registration/#advantages)

- Microservices can dynamically locate and communicate with each other without needing to know their specific network addresses beforehand. This is crucial in dynamic environments where IP addresses and ports can change frequently.
- Reduces the need for manual configuration of service locations in each microservice. Services don't need to be updated every time another service's location changes.
- Scaling microservices up or down becomes easier. New instances automatically register themselves with the service registry, making them immediately discoverable by other services without manual intervention.
- If a service instance fails, it will eventually stop sending heartbeats to the registry and will be removed. Consumers can then discover and connect to other healthy instances, improving the system's overall resilience.
- Services are less tightly coupled as they don't have direct dependencies on the physical locations of other services. This makes deployments and updates more flexible.
- Service registries often integrate with load balancers. When a new service instance registers, the load balancer can automatically include it in the pool of available instances, distributing traffic effectively.
- Microservices can be deployed across different environments (development, testing, production) without significant changes to their discovery mechanism, as long as they are configured to connect to the appropriate service registry for that environment.

## [Trade-offs](https://java-design-patterns.com/patterns/microservices-self-registration/#trade-offs)

- Introducing a service registry adds another component to your system that needs to be set up, managed, and monitored. This increases the overall complexity of the infrastructure.
- The service registry itself becomes a critical component. If the service registry becomes unavailable, it can disrupt communication between microservices. High availability for the service registry is therefore essential.
- Microservices need to communicate with the service registry for registration, sending heartbeats, and querying for other services. This can lead to increased network traffic.
- There might be a slight delay between when a microservice instance starts and when it becomes fully registered and discoverable in the service registry. This needs to be considered, especially during scaling events.
- You need to consider how your microservices will behave if they fail to register with the service registry upon startup. Robust error handling and retry mechanisms are often necessary.
- Microservices need to include and configure client libraries (like the Eureka Discovery Client) to interact with the service registry. This adds a dependency to your application code.
- In distributed service registries, ensuring consistency of the registry data across all nodes can be a challenge. Different registries might have different consistency models (e.g., eventual consistency).

## [References](https://java-design-patterns.com/patterns/microservices-self-registration/#references)

- Microservices Patterns: [https://microservices.io/](https://microservices.io/)
- Eureka Documentation: [https://github.com/Netflix/eureka](https://github.com/Netflix/eureka) \| [https://spring.io/projects/spring-cloud-netflix](https://spring.io/projects/spring-cloud-netflix)
- Spring Boot Documentation: [https://spring.io/projects/spring-boot](https://spring.io/projects/spring-boot)
- Spring Cloud OpenFeignDocumentation: [https://spring.io/projects/spring-cloud-openfeign](https://spring.io/projects/spring-cloud-openfeign)
- Spring Boot Actuator Documentation: [https://www.baeldung.com/spring-boot-actuators](https://www.baeldung.com/spring-boot-actuators)

---


---

<!-- ============================================ -->
<!-- 设计原则 (Design Principles) — 25 个 -->
<!-- ============================================ -->

## [principles/kiss] KISS 保持简单
> 官方文档: https://java-design-patterns.com/principles/

Most systems work best if they are kept simple rather than made complex.

Why

- Less code takes less time to write, has less bugs, and is easier to modify.
- Simplicity is the ultimate sophistication.

---

## [principles/yagni] YAGNI 你不会需要它
> 官方文档: https://java-design-patterns.com/principles/

YAGNI stands for "you aren't gonna need it": don't implement something until it is necessary.

Why

- Any work that's only used for a feature that's needed tomorrow, means losing effort from features that need to be done for the current iteration.
- It leads to code bloat; the software becomes larger and more complicated.

How

- Always implement things when you actually need them, never when you just foresee that you need them.

## [Do The Simplest Thing That Could Possibly Work](https://java-design-patterns.com/principles/#do-the-simplest-thing-that-could-possibly-work)

Why

- Real progress against the real problem is maximized if we just work on what the problem really is.

How

- Ask yourself: "What is the simplest thing that could possibly work?"

---

## [principles/separation-of-concerns] Separation of Concerns 关注点分离
> 官方文档: https://java-design-patterns.com/principles/

Separation of concerns is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. For example the business logic of the application is a concern and the user interface is another concern.

Why

- Simplify development and maintenance of software applications.
- When concerns are well-separated, individual sections can be reused, as well as developed and updated independently.

How

- Break program functionality into separate modules that overlap as little as possible.

---

## [principles/dry] DRY (Don't Repeat Yourself) 不要重复自己
> 官方文档: https://java-design-patterns.com/principles/

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Why

- Duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.

How

- Put business rules, long expressions, if statements, math formulas, metadata, etc. in only one place.
- Apply the Rule of three.

---

## [principles/code-for-the-maintainer] Code For The Maintainer 为维护者编码
> 官方文档: https://java-design-patterns.com/principles/

Why

- Maintenance is by far the most expensive phase of any project.

How

- Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.

---

## [principles/avoid-premature-optimization] Avoid Premature Optimization 避免过早优化
> 官方文档: https://java-design-patterns.com/principles/

Quoting Donald Knuth: "Premature optimization is the root of all evil."

Why

- It is unknown upfront where the bottlenecks will be.
- After optimization, it might be harder to read and thus maintain.

How

- Make It Work Make It Right Make It Fast

---

## [principles/minimise-coupling] Minimise Coupling 最小化耦合
> 官方文档: https://java-design-patterns.com/principles/

Coupling between modules/components is their degree of mutual interdependence; lower coupling is better.

Why

- A change in one module usually forces a ripple effect of changes in other modules.

How

- Eliminate, minimise, and reduce complexity of necessary relationships.
- Apply the Law of Demeter.

---

## [principles/law-of-demeter] Law of Demeter 迪米特法则
> 官方文档: https://java-design-patterns.com/principles/

Don't talk to strangers.

How

A method of an object may only call methods of:
1. The object itself.
2. An argument of the method.
3. Any object created within the method.
4. Any direct properties/fields of the object.

---

## [principles/composition-over-inheritance] Composition Over Inheritance 组合优于继承
> 官方文档: https://java-design-patterns.com/principles/

Why

- Less coupling between classes.
- Using inheritance, subclasses easily make assumptions, and break LSP.

How

- Compose when there is a "has a" relationship, inherit when "is a".

---

## [principles/orthogonality] Orthogonality 正交性
> 官方文档: https://java-design-patterns.com/principles/

Things that are not related conceptually should not be related in the system. The more orthogonal the design, the fewer exceptions.

---

## [principles/robustness-principle] Robustness Principle 健壮性原则
> 官方文档: https://java-design-patterns.com/principles/

Be conservative in what you do, be liberal in what you accept from others.

---

## [principles/inversion-of-control] Inversion of Control 控制反转
> 官方文档: https://java-design-patterns.com/principles/

Also known as the Hollywood Principle, "Don't call us, we'll call you". Custom-written portions receive the flow of control from a generic framework.

How

- Using Factory pattern, Service Locator pattern, Dependency Injection, Template Method pattern, Strategy pattern.

---

## [principles/maximise-cohesion] Maximise Cohesion 最大化内聚
> 官方文档: https://java-design-patterns.com/principles/

Cohesion of a single module/component is the degree to which its responsibilities form a meaningful unit; higher cohesion is better.

---

## [principles/liskov-substitution-principle] Liskov Substitution Principle (LSP) 里氏替换原则
> 官方文档: https://java-design-patterns.com/principles/

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

---

## [principles/open-closed-principle] Open/Closed Principle (OCP) 开闭原则
> 官方文档: https://java-design-patterns.com/principles/

Software entities should be open for extension, but closed for modification.

---

## [principles/single-responsibility-principle] Single Responsibility Principle (SRP) 单一职责原则
> 官方文档: https://java-design-patterns.com/principles/

A class should never have more than one reason to change.

---

## [principles/hide-implementation-details] Hide Implementation Details 隐藏实现细节
> 官方文档: https://java-design-patterns.com/principles/

A software module hides information by providing an interface, and not leak any unnecessary information.

---

## [principles/curlys-law] Curly's Law 科里定律
> 官方文档: https://java-design-patterns.com/principles/

Do One Thing. Choose a single, clearly defined goal for any particular bit of code.

---

## [principles/encapsulate-what-changes] Encapsulate What Changes 封装变化
> 官方文档: https://java-design-patterns.com/principles/

A good design identifies the hotspots that are most likely to change and encapsulates them behind an API.

---

## [principles/interface-segregation-principle] Interface Segregation Principle (ISP) 接口隔离原则
> 官方文档: https://java-design-patterns.com/principles/

Reduce fat interfaces into multiple smaller and more specific client specific interfaces.

---

## [principles/boy-scout-rule] Boy-Scout Rule 童子军规则
> 官方文档: https://java-design-patterns.com/principles/

Leave the campground cleaner than you found it. Always leave the code cleaner than we found it.

---

## [principles/command-query-separation] Command Query Separation (CQS) 命令查询分离
> 官方文档: https://java-design-patterns.com/principles/

Each method should be either a command that performs an action or a query that returns data to the caller but not both. Asking a question should not modify the answer.

---

## [principles/murphys-law] Murphy's Law 墨菲定律
> 官方文档: https://java-design-patterns.com/principles/

Anything that can go wrong will go wrong.

---

## [principles/brooks-law] Brooks's Law 布鲁克斯定律
> 官方文档: https://java-design-patterns.com/principles/

Adding manpower to a late software project makes it later.

---

## [principles/linus-law] Linus's Law 林纳斯定律
> 官方文档: https://java-design-patterns.com/principles/

Given enough eyeballs, all bugs are shallow.

---

