Whether the factory method and abstract factory are foolishness can not be distinguished, and strive to understand pattern design in the simplest and most direct way. After all, the original intention of pattern is to simplify complexity, so we should use the simplest way to understand.
Example code:
Factory mode
# -*- coding:utf-8 -*-
class A:
def __init__(self):
self.word = "Function A"
def run(self):
print(self.word)
class B:
def __init__(self):
self.word = "Function B"
def run(self):
print(self.word)
def Interface(classname):
"""
//Factory mode interface function
:param classname:
:return:
"""
run = dict(A=A, B=B)
return run[classname]()
if __name__ == '__main__':
test1 = Interface('A')
test1.run()
test2 = Interface('B')
test2.run()
//Result:
//Run A
//Run B
Abstract factory mode:
# -*- coding:utf-8 -*-
class A:
def __init__(self):
self.word = "Function A"
def run(self):
print(self.word)
class B:
def __init__(self):
self.word = "Function B"
def run(self):
print(self.word)
class Interface:
"""
//Abstract factory pattern interface class
:param classname:
:return:
"""
def __init__(self, classname=None):
self.test = classname
def run(self):
self.test().run()
if __name__ == '__main__':
test1 = Interface()
test1.test = A
test1.run()
test1.test = B
test1.run()
//Result:
//Run A
//Run B
Abstract factory: create a series of related or interdependent abstract object Interface without specifying the instantiation of class A or class B
Factory method: define an Interface function Interface for creating objects, and let the subclass decide which class A or B to instantiate
Comparison of abstract factory and factory method: the class instantiated by the abstract factory has been listed in the interface method by dictionary, that is, either instantiation A or B, but the class instantiated by the abstract factory is unknown. You can pass in A or B in the abstract interface class, or you can create A new C class to pass in.
Class itself is the abstraction of object, but abstract factory is the abstraction of class, the combination of the same method and the same property.
As shown in the figure above, abstract factory has two methods to produce frame and tire, but he didn't specify which brand to produce. There are two brands in the figure above: Flying Pigeon bicycle, permanent bicycle, and so on. In the factory mode, there are pigeon factory and permanent factory, and these two factories can only produce corresponding tires.