In the Java design patterns – factory pattern (1) simple factory we introduced the mode of simple factory pattern, referred to the simple factory pattern is in violation of the principle of open and close, and the factory method pattern is further abstraction of simple factory pattern, its advantage is can make the system without modifying the original code under the condition of introduction of new products, which satisfy the open closed principle.

Location: Shunhe Village, Lanshan County, Yongzhou City, Hunan Province

Author: Laugh with your heart * 😁 Be happy every day

Design Mode series:

  • Java Design pattern – singleton pattern
  • Java Design Pattern – Factory Pattern (1) Simple Factory pattern
  • Java Design Pattern – Factory Pattern (2) Factory method pattern
  • Java Design Pattern – Factory Pattern (3) Abstract Factory pattern
  • Java Design pattern – Builder pattern
  • Java Design pattern – Proxy pattern
  • Java Design pattern – Adapter pattern
  • Java Design pattern – Decorator pattern
  • Java Design pattern – Bridge pattern
  • Java Design pattern – Appearance pattern
  • Java Design pattern – Composite pattern
  • Java Design pattern – Share meta pattern
  • Java Design Pattern – Template method pattern
  • Java Design pattern – Policy pattern
  • Java Design pattern – Chain of Responsibility pattern
  • Java Design Pattern – The Mediator pattern
  • Java Design Pattern – Observer Pattern (publish/subscribe pattern)
  • Continuously updated…

One, foreword

1) Overview:

The meaning of the Factory Method pattern is to define a Factory interface to create product objects, deferring the actual creation to subclasses. The core factory class is no longer responsible for the creation of products, so that the core class becomes an abstract factory role, only responsible for the interfaces that the concrete factory subclasses must implement. The benefit of this further abstraction is that the factory method pattern enables the system to introduce new products without modifying the concrete factory role.

The factory method pattern is derived from the simple factory pattern and solves many problems of the simple factory pattern. First of all, the ‘open – close principle’ is fully implemented to achieve scalability. The second, more complex hierarchy can be applied to situations where the product results are complex.

The factory method pattern abstracts the simple factory pattern. There is an abstract Factory class (which can be an abstract class and an interface) that is no longer responsible for the concrete production of the product, but just for the specification, and the concrete production is done by its subclasses. In this pattern, the factory class and the product class often correspond in sequence. That is, an abstract factory corresponds to an abstract product, and a concrete factory corresponds to a concrete product, and this concrete factory is responsible for producing corresponding products.

2) Role Structure:

Abstract Factory (Creator) : Is the core of the factory method pattern, application-independent. The factory class of any object created in the schema must implement this interface.

Concrete Creator: This is a Concrete factory class that implements an abstract factory interface, contains application-specific logic, and is called by the application to create product objects. In the figure above, there are two such characters: BulbCreator and TubeCreator.

Abstract Product: A supertype of an object created by the factory method pattern, that is, a common parent or jointly owned interface of the Product object. In the image above, the character is Light.

Concrete Product: This role implements the interface defined by the abstract Product role. A specific product is created in a specific factory, often with a one-to-one correspondence between them.

Blogger soliloquy: speak human language is to go up and then extract a layer (so really is no what is to add a layer can not be solved, a layer is not good to add two layers) 😁


Same question from last time:

Requirements: Design a coffee shop ordering system.

Design a Coffee class and define its two subclasses (AmericanCoffee and latte); Design a coffee shop (CoffeeStore), coffee shop has the function of ordering coffee.


3) Class Diagram relationship:

The simple factory class diagram from the previous article:

Factory method class diagram:

In the simple factory pattern, CoffeeStore and SimpleCoffeeFactory were directly associated. At that time, there were some specific operations that needed to be done in the SimpleCoffeeFactory simple factory, but here again, an extraction was performed to split the factory into two layers. One is abstract factory, the other is concrete implementation factory. Again, a decoupling operation is done.

To learn about simple Factory patterns go to 👉Java Design Patterns – Factory Patterns (1) Simple Factory Patterns

Specific or look at the code to achieve it, at the end of the text to compare the summary 😁

Two, code implementation

1) Coffce abstract Class (Product Abstract class)

public abstract class Coffee {
    public abstract void addMilk(a);
    public abstract void addSugar(a);
    public abstract String getName(a);
}
Copy the code

2) AmericanCoffee, LatteCoffee (specific product category)

public class AmericanCoffee extends Coffee {
    @Override
    public void addMilk(a) {  System.out.println("Milk your coffee."); }

    @Override
    public void addSugar(a) { System.out.println("Sugar your coffee."); }

    @Override
    public String getName(a) {   return "Americano"; }}Copy the code
public class LatteCoffee extends Coffee {

    @Override
    public void addMilk(a) {   System.out.println("Milk your coffee."); }

    @Override
    public void addSugar(a) {  System.out.println("Sugar your coffee."); }

    @Override
    public String getName(a) {   return "Latte"; }}Copy the code

3) CoffeeFactory (Abstract Factory)

public interface CoffeeFactory {
    Coffee createCoffee(a);
}
Copy the code

4) AmericanCoffeeFactory, LatteCoffeeFactory class (concrete implementation factory)

public class AmericanCoffeeFactory implements CoffeeFactory {

    @Override
    public Coffee createCoffee(a) {      return newAmericanCoffee(); }}Copy the code
public class LatteCoffeeFactory implements CoffeeFactory {

    @Override
    public Coffee createCoffee(a) {  return newLatteCoffee(); }}Copy the code

5) Coffee shops (customers with specific products)

public class CoffeeStore {

    private CoffeeFactory factory;

    public CoffeeStore(CoffeeFactory factory) {   this.factory = factory; }

    public Coffee orderCoffee(String type) {
        Coffee coffee = factory.createCoffee();
        coffee.addMilk();
        coffee.addSugar();
        returncoffee; }}Copy the code

6) test

So let’s test that out

public class Client {
    public static void main(String[] args) {

        CoffeeStore coffeeStore = new CoffeeStore(new AmericanCoffeeFactory());
        Coffee americano = coffeeStore.orderCoffee("americano");
        System.out.println(americano.getName());
        /** * Add milk to coffee * Sugar to coffee * Americano */}}Copy the code

Third, summary

3.1 Summary:

From the above code, this perfectly solves the “open close principle” violated in the simple factory method, where new products are added by writing a concrete implementation factory class without modifying the original code.

The factory method pattern is a further abstraction of the simple factory pattern. By using polymorphism, the factory method pattern retains the advantages of the simple factory pattern and overcomes its disadvantages.

3.2 advantages:

  • Users only need to know the name of the specific factory to get the product they want, without knowing the specific creation process of the product.
  • Increased flexibility allows for the creation of new products by simply writing a corresponding concrete factory class. There is no need to modify the original factory to meet the open and close principle
  • A typical decoupling framework. A high-level module only needs to know the abstract class of the product and does not need to care about other implementation classes, satisfying Demeter’s law, dependency inversion principle and Richter’s substitution principle.

3.3. Disadvantages:

  • It is easy to have too many classes and add complexity
  • The system is abstract and difficult to understand
  • Abstract products can only produce one product, which can be solved by using the abstract factory model. (The next post is being updated at 😀)

3.4 Application Scenarios:

  • The customer only knows the name of the factory that created the product, not the specific product name. Such as TCL TV factory, Hisense TV factory and so on.
  • The task of creating an object is done by one of several concrete sub-factories, whereas an abstract factory provides only an interface to create a product.
  • Customers don’t care about the details of creating a product, just the brand of the product

4. Talk to yourself

I do not know whether the article is useful or useless, just want to do a share. I hope you can enjoy it and have a good harvest here.

Hello, be happy every day. See you in the next article.

This series is still being updated…. 👉 I will definitely come back. 😁