Design Patterns - Factory Method Pattern and Abstract Factory Pattern

Why use factory methods?

Duck duck=new MallardDuck();
//使用接口让代码更具有弹性
//但是还是建立了具体类的实例

When there is a group of related classes, code like this will be written on the spot

Duck duck;

if(picnic){
    duck=new MallarDuck();
}
if(hunting){
    duck=new DecoyDuck();
}
else if(inBathTub){
    duck=new RubberDuck();
}

In many cases, which concrete class we want to instantiate depends on some conditions at runtime. When you see such code, once there are changes or extensions, you must reopen this code to check and modify. Often such modified code will make parts of the system harder to maintain and update, and more prone to errors.

Using new directly does not conform to the principle of "close to modification", we should write code according to the principle of "find out the principles that will change and separate them from the unchanged parts".

solution:

What a factory method!

Factory Method Pattern : Defines an interface for creating objects, but lets subclasses decide which class to instantiate. Factory methods let classes defer instantiation to subclasses.

Abstract Factory Pattern : Provides an interface for creating families of related or dependent objects without explicitly specifying a specific class.

 

Principle: rely on abstraction, not on concrete classes.

Purpose: To get looser coupling and more flexible design.

 

Simple understanding:

Instance -> Class -> Class Factory

Instance -> Class -> Class Factory -> Abstract Factory

 

A factory method is a method that is used to create "a product" in the abstract interface provided.

createPizza();

Then the concrete subclass implements the specific method of this createPizze() by implementing this interface.

An abstract factory is an interface in which "many products" (or a family of products, because there is a certain connection between products) are created.

createDough();
createSauce();
createCheese();
//多个产品,但是相互之间有联系,都是一种披萨的配料

Then specific subclasses can create this product family by implementing this interface, and each of the create methods can be implemented using factory methods .

It can be said that the implementation of the abstract factory uses the factory method.

In other words: the task of the abstract factory is to define an interface responsible for creating a set of products, each method in this interface is responsible for creating a concrete product, and we use the subclass that implements the abstract factory to provide these concrete algorithms. Therefore, it is quite natural to implement the production method with the factory method in the abstract factory.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325623877&siteId=291194637