02. Factory method method

  1. As more fruits were grown, more than a dozen new varieties were added.

[ , , (img-rFTUeetP-1614856576913)(http://img.wyhcsl.cn//blog/20200701115419647.png)]

  1. As the types of fruits are constantly increasing, the StaticeFactory class will continue to be modified, and the method extension is very large and difficult to manage.

  2. The method of expanding fruit types is very elegant, and the following principles do not conform to the six principles of design patterns:

    • Single responsibility principle: A class is responsible for making different fruits
    • Opening and closing principle: When extending a type, you need to change the existing code

    Subsequently,The simple factory style does not belong to 23 classic design models

  3. If each class has its own factory when expanding new types, this means:

    • The static factory dissipates, each category of fruit corresponds to the fruit product to be produced

    • When you need to expand the Fruit class, the plant corresponding to the Fruit class corresponds

Definition of

Define a factory interface that creates an object to delay the actual creation of the object in a given subclass. This corresponds to the ‘Create and use split’ properties required in the create form.

structure

The main role of the method factory mode is:

  • Abstract Factory: Provides an interface to create products (fruits), and the caller can create products by getting the factory method of specific factories.
  • Concrete factory: This is mainly to achieve abstract methods in abstract factories and complete the creation of concrete products.
  • Abstract Products (Product): Define product specifications and describe the main features and functions of the product.
  • Concrete product: An interface defined by abstract symbols for the product is created by the concrete plants, which correspond to a specific plant.

UML class diagram

code

Implement

fruit interface (abstract product)

public interface Fruit {

    public void getFruit();

}

Types of fruits (specific products)

public class Apple implements Fruit {

    @Override
    public void getFruit() {
                 System.out.println («Я яблоко»);
    }
}

public class Banana implements Fruit {

    @Override
    public void getFruit() {
                 System.out.println («Я банан»);
    }
}

public class Orange implements Fruit {

    @Override
    public void getFruit() {
                 System.out.println («Я апельсин»);
    }
}

factory method (abstract product)

/**
   * Интерфейс фабричного метода
 */
public interface FruitFactory {
    /**
           * Получите фрукты
     */
    public Fruit getFruit();
}

factory method (product specific)

/**
 * Apple Factory
 */
public class AppleFactory implements FruitFactory{
    @Override
    public Fruit getFruit() {
        return new Apple();
    }
}

/**
   * Оранжевая фабрика
 */
public class OrangeFactory implements FruitFactory {
    @Override
    public Fruit getFruit() {
        return new Orange();
    }
}

/**
   * Банановая фабрика
 */
public class BananaFactory implements FruitFactory{
    @Override
    public Fruit getFruit() {
        return new Banana();
    }
}

client call

public class TestClient {

    public static void main(String[] args) {
                 // Хочу Apple
        getApple();
                 // хочу апельсин
        getOrange();
                 // хочу банан
        getBanana();
    }

    /**
           * Получите Apple
     */
    public static void getApple() {
        FruitFactory appleFactory = new AppleFactory();
        Fruit apple = appleFactory.getFruit();
        apple.getFruit();
    }

    /**
           * Получите апельсин
     */
    public static void getOrange() {
        FruitFactory orangeFactory = new OrangeFactory();
        Fruit orange = orangeFactory.getFruit();
        orange.getFruit();
    }

    /**
           * Получите бананы
     */
    public static void getBanana() {
        FruitFactory bananaFactory = new BananaFactory();
        Fruit banana = bananaFactory.getFruit();
        banana.getFruit();
    }
}

a result

Я яблоко
 Я оранжевый
 Я банан

priority

  • Users only need to know the name of a specific factory to get the products they want, and there is no need to know the specific process of creating a product
  • When adding the system to the system, you only need to add specific product categories and corresponding specific factories. You do not need to change the original factory to match the opening and closing principle

Shortage

  • Each additional product is added to add a specific product category and a corresponding factory category, which increases the complexity of the system.
Суть режима метода заводского метода: задержка суб -категории, чтобы выбрать реализацию

The factory method itself is not familiar with the product interface. The specific implementation of the product has been registered. The factory plan method only needs to be defined for execution.

  • Customers only know the factory name when creating products, and do not know the specific name of the product. Such as TCL TV Factory, Hisense TV Factory, etc.
  • The task of creating objects is done by a number of concrete subfactories, while abstract factories only provide an interface for creating products.
  • Customers don’t care about the details of creating products, they only care about the brand.

When there are not many products to generate and will not be incremented, the concrete factory class can do the job and the abstract factory class can be removed. At present, the factory method model will turn into a simple factory model.

Leave a Comment