When you want to replace the generated products in groups , Consider using the abstract factory pattern , The abstract factory pattern class diagram is shown in the following figure
Abstract factory class AbstractFactory The interface used to define the factory class . stay Python This class does not have to be defined in the language , Just define it when you need to realize common functions , This can improve the reusability of the code .
Concrete factory (ConcreteFactory1 perhaps ConcreteFactory2) Responsible for building a set of actual products according to the expanded requirements . To clarify the responsibilities of classes , The class name can be Factory As a suffix .
Similar to the abstract factory class ,Python Abstract product classes in languages ProductA、ProductB It is not necessary to define , As long as the product class generated by each factory method supports the same operation (Python Language calls this situation Protocol), This is somewhat similar to the template .
Concrete products (ConcreteProductA1、ConcreteProductA2、ConcreteProductB1、ConcreteProductB2) Follow the conventions of abstract product classes and realize their own functions .PyExecutor Corresponding to concrete products are various functional modules and connecting lines in general function module logic and small household appliance control logic .
Sample code
# MiniBody Classes and MiniWheel class
class MiniBody:
def __init__( self):
pass
class MiniWhell:
def __init__( self):
pass
# HeavyBody Classes and BigWheel class
class HeavyBody:
def __init__( self):
pass
class BigWheel:
def __init__( self) :
pass
class CarPartsFactory:
def create_boy( self):
return MiniBody()
def create_wheel( self):
return MiniWheel()
class TruckPartsFactory:
def create_boy( self):
return MiniBody()
def create_wheel( self):
return MiniWheel()