The biggest advantage of the simple factory mode is that the factory class contains the necessary logic judgment. The client only needs to provide selection conditions, so that the client does not need to know the specific product information.
However, each time a product is added, the factory class must be modified, which violates the "open-closed" principle.
Therefore, with the factory method model
Factory method mode: defines an interface used to create objects, so that the subclass determines which class to instantiate.
Compared with the simple factory mode, the factory method mode
AdvantagesIt abstracts the product factory class and turns it into an interface. As long as a class implements this interface, it can be used as a factory class, in this way, each time a product is added, the corresponding production factory class will be added and can be used elsewhere, meeting the "open-closed" principle;
DisadvantagesThat is, the logical judgment of production products is removed from the factory.
# Encoding = UTF-8 ## by Panda # factory method mode def printinfo (Info): Print Unicode (Info, 'utf-8 '). encode ('gbk') # Lei Feng class Leifeng (): def sweep (Self): printinfo ('cleaning') def wash (Self): printinfo ('laundry ') def buyrice (Self): printinfo ('buy my') # undergraduate (Leifeng): def _ init _ (Self): printinfo (' ') pass # community volunteer class volunteer (Leifeng): def _ init _ (Self): printinfo ('Community volunteer') pass # simple Lei Feng factory class simplefactory (): @ staticmethod def createleifeng (type): If type = 'student from Lei Feng ': Return undergraduate () Elif type = 'Community volunteer': pass # Lei Feng abstract factory class ifacloud (): @ staticmethod def createleifeng (): Return Leifeng () # le's community volunteer factory class volunteerfactory (ifacfactory): @ staticmethod def createleifeng (): Return volunteer () # undergraduatefactory (ifacloud): @ staticmethod def createleifeng (): Return undergraduate () def clientui (): printinfo ('-------------- simple factory model --------------') studenta = simplefactory. createleifeng ('College student of Lei Feng ') studenta. buyrice () studenta. sweep () studenta. wash () printinfo ('---------------- factory method mode --------------') studentb = volunteerfactory. createleifeng () studentb. buyrice () studentb. sweep () studentb. wash () returnif _ name _ = '_ main _': clientui ();
Class Diagram: This is the class chart for the calculator to change to the factory method mode. The class chart for learning Lei Feng is similar.