Detailed analysis of factory mode

  Factory mode

        If there are three types of take-out meals to choose from: burgers and other main meals, snacks, and drinks. When we choose the food we need and the payment is completed, the order is generated.
    Or if you need a car, you can pick up the goods directly from the factory, regardless of how the car is made and the specific implementation in the car.
    
   Advantages : 1. A caller wants to create an object, as long as he knows its name, it does not need to know other detailed information.  
                2. As the caller, shield the specific implementation of the product, and the caller only cares about the interface of the product

    Disadvantages :

           1 When a new type is to be added to the system, the factory class must be modified and the necessary processing logic must be added, which violates the "opening and closing principle".
           2 in simple factory pattern, all products are created by the same factory, the factory class is heavy duty, more complex business logic, concrete products and factory classes of 
             coupling between the high, seriously affecting the flexibility and expansion of the system sex,
             and factory method pattern can be a good solution to this problem.

           Use case:

        1. Log recorder: Records may be recorded to local hard disk, system events, remote servers, etc. The user can choose where to record the log.   

        2. Database access, when the user does not know which type of database the system uses in the end, and the database may change.
        3. To design a framework to connect to the server, three protocols are required, "POP3", "IMAP", and "HTTP". These three can be used as product classes to implement an interface together.

        Expansion: "Open-closed principle". The so-called open for extension, closed for modification

             Factory Method Pattern: The same interface produces different series of products, and multiple different instances of the same type are obtained.
             In the factory method pattern, the factory parent class is responsible for defining the public interface for creating product objects, while the factory subclass is responsible for generating specific product objects. The purpose of this is to delay the instantiation of the product class to the factory subclass. That is, the factory subclass is used to determine which specific product class should be instantiated.
             Even use the same interface to handle different things.

             Disadvantages: When adding new products, you need to write new specific product categories and provide corresponding specific factory categories. The number of categories in the system will increase in pairs, which increases the complexity of the system to a certain extent. More classes need to be compiled and run, which will bring some additional overhead to the system.

    # 工厂模式:
     def create_shape(name):
        if name =='Circle':
            return Circle()
        elif name == 'Rectangle':
            return Rectangle()
        elif name == 'Triangle':
            return Triangle()
        elif name == 'Ellipse':
            return Ellipse()
        else:
            return None
 #   工厂方法模式:
 import math
 
#定义4个图形类,并且每一个图形都有一个可以计算面积的方法
class Circle:
    def Area(self,radius):
        return math.pow(radius,2)*math.pi
 
class Rectangle:
    def Area(self,longth,width):
        return 2*longth*width
 
class Triangle:
    def Area(self,baselong,height):
        return baselong*height/2
 
class Ellipse:
    def Area(self,long_a,short_b):
        return long_a*short_b*math.pi
 
#定义创建对象的工厂接口,因为python中并没有接口的概念,所以,这里打算通过“类的继承”加以实现
class IFactory:  #模拟接口
    def create_shape(self):  #定义接口的方法,只提供方法的声明,不提供方法的具体实现
        pass
 
class CircleFactory(IFactory): #模拟类型实现某一个接口,实际上是类的继承
    def create_shape(self, name):  #重写接口中的方法
        if name =='Circle':
            return Circle()
 
class RectangleFactory(IFactory): #模拟类型实现某一个接口,实际上是类的继承
    def create_shape(self, name):  #重写接口中的方法
        if name =='Rectangle':
            return Rectangle()
 
class TriangleFactory(IFactory): #模拟类型实现某一个接口,实际上是类的继承
    def create_shape(self, name):  #重写接口中的方法
        if name =='Triangle':
            return Triangle()
 
class EllipseFactory(IFactory): #模拟类型实现某一个接口,实际上是类的继承
    def create_shape(self, name):  #重写接口中的方法
        if name =='Ellipse':
            return Ellipse()
 
 
if __name__=='__main__':
    factory1=CircleFactory()
    factory2=RectangleFactory()
    factory3=TriangleFactory()
    factory4=EllipseFactory()
 
    circle=factory1.create_shape('Circle')
    circle_area=circle.Area(2)
    print(f'这是一个圆,它的面积是:{circle_area}')
 
    rectangle=factory2.create_shape('Rectangle')
    rectangle_area=rectangle.Area(2,3)
    print(f'这是一个长方形,它的面积是:{rectangle_area}')
 
    triangle=factory3.create_shape('Triangle')
    triangle_area=triangle.Area(2,3)
    print(f'这是一个三角形,它的面积是:{triangle_area}')
 
    ellipse=factory4.create_shape('Ellipse')
    ellipse_area=ellipse.Area(3,2)
    print(f'这是一个椭圆,它的面积是:{ellipse_area}')

    Factory mode:

          For a series of classes (such as Circle, Rectangle, Ellipse, Triangle), they have a lot in common. In layman's terms, it is a series of classes. Use a factory, use a factory creation function to create a certain class.

    A series of classes -> a factory -> a creation function -> a specific class

    Factory method pattern:

           For a series of classes (such as Circle, Rectangle, Ellipse, Triangle), use an abstract factory interface, and then write a factory class for each specific class, and then create a function in each class.

    A series of classes -> an abstract factory interface -> multiple factory classes corresponding to the series -> each class has a creation function -> a specific class

    

Summary: The simple factory model is a general contract service, no matter how many classes need to be created, all are completed by a factory;

          The factory function pattern is a customized one-to-one service. Each factory can only create a specific class, but these factories uniformly follow the principle specified by the general factory
         (that is, the creation method of the abstract factory interface).

    So what is the abstract factory pattern?
    Abstract Factory Pattern (Abstract Factory Pattern) is to create other factories around a super factory. This super factory is also called the factory of other factories. This type of design pattern is a creational pattern, which provides the best way to create objects.

    Simple factory model: centralized production

    Factory method model: decentralized production

    Abstract factory model: for the same series of centralized production, for different series of decentralized production (the combination of the former two)


   Comparison of factory methods and abstract factory methods The
              factory method has developed a method to create an object. The   
              abstract factory method opens one or more methods to create a series of related objects. The
              factory method uses inheritance and subclasses to decide which object to create. The
              abstract communicative method is used The composition delegates the task of creating objects to other class-
              community methods to create a product
              abstract factory method to create a series of related products

Refer to the "Four Steps" strategy to fully implement the abstract factory model ( https://blog.csdn.net/qq_27825451/article/details/84284681 )

import math
 
#定义一个“形状”的接口,里面定义一个面积的接口方法,只有方法的定义,并没有实现体
class IShape(object): 
    def Area(self):
        pass
 
#定义4个图形类,都是实现Ishape接口,并且每一个图形都有一个可以计算面积的方法,相当于重写接口方法
class Circle(IShape):
    def Area(self,radius):
        return math.pow(radius,2)*math.pi
 
class Rectangle(IShape):
    def Area(self,longth,width):
        return 2*longth*width
 
class Triangle(IShape):
    def Area(self,baselong,height):
        return baselong*height/2
 
class Ellipse(IShape):
    def Area(self,long_a,short_b):
        return long_a*short_b*math.pi

 

2. The second step is to define the color series again

#定义一个“颜色”的接口,里面定义一个颜色名称的接口方法,只有方法的定义,并没有实现体
class IColor(object): 
    def color(self):
        pass
 
#定义3个颜色类,都是实现IColor接口,并且每一个图形都有一个可以获取颜色名称的方法,相当于重写接口方法
class Red(IColor):
    def color(self,name):
        print(f'我的颜色是:{name}')
 
class Blue(IColor):
    def color(self,name):
        print(f'我的颜色是:{name}')
 
class Black(IColor):
    def color(self,name):
        print(f'我的颜色是:{name}')

3. The third step is to define the abstract factory and the factory corresponding to each series

class IFactory:  #模拟接口
    def create_shape(self):  #定义接口的方法,只提供方法的声明,不提供方法的具体实现
        pass
    def create_color(self):
        pass
 
#创建形状这一个系列的工厂
class ShapeFactory(IFactory): #模拟类型实现某一个接口,实际上是类的继承
    def create_shape(self, name):  #重写接口中的方法
        if name =='Circle':
            return Circle()
        elif name == 'Rectangle':
            return Rectangle()
        elif name == 'Triangle':
            return Triangle()
        elif name == 'Ellipse':
            return Ellipse()
        else:
            return None
 
#创建颜色这一个系列的工厂
class ColorFactory(IFactory): #模拟类型实现某一个接口,实际上是类的继承
    def create_color(self, name):  #重写接口中的方法
        if name =='Red':
            return Red()
        elif name =='Blue':
            return Blue()
        elif name =='Black':
            return Black()
        else:
            return None
 

 

Note: The abstract factory here is a bit different from the abstract factory in the "factory method pattern", because there are two series of types that need to be generated, so there need to be two functional interfaces in the abstract factory, one to generate "shape " and one to generate " Color " , and then rewritten separately in the factory that implements the interface.

4. The fourth step is to define the class that produces the factory class-the core of the abstract factory pattern

定义一个专门产生工厂的类
class FactoryProducer:
    def get_factory(self,name):
        if name=='Shape':
            return ShapeFactory()
        elif name=='Color':
            return ColorFactory()
        else:
            return None

Note: This step is the most distinctive of the abstract factory pattern. If you follow the "simple factory pattern", you only need to proceed to the third step, because then I use the ShapeFactory factory class and the ColorFactory class to generate each series separately An instance of the class is fine, but we did not do this. But define a new one

"Factory produces class" to let us decide which class instance is to be produced.

to sum up:

Abstract Factory Pattern (Abstract Factory Pattern) is to create other factories around a super factory. This super factory is also called the factory of other factories. This type of design pattern is a creational pattern, which provides the best way to create objects. (The FactoryProducer here is the super factory)

In the abstract factory pattern, the interface is a factory responsible for creating a related object, and there is no need to explicitly specify their class. Each generated factory can provide objects in accordance with the factory pattern.
 

Guess you like

Origin blog.csdn.net/weixin_42322206/article/details/100087908