1. Factory method (Factory methods)
Intent: Defines an interface for creating an object, letting subclasses decide which class to instantiate. The Factory method defers the instantiation of a class to its subclasses.
Applicability:
- When a class does not know the class of the object it must create.
- When a class wants to specify the object it creates by its subclasses.
- When a class delegates the responsibility of creating an object to one of several helper subclasses, and you want to set which helper subclass is the agent this information is localized.
#!/usr/bin/python#coding: UTF8"' Factory Method 'ClassChinagetter:"" A simple localizer a la gettext "" "Def__init__(self): Self.trans = Dict (dog=U "Puppy", cat=U "Kitten")DefGet(Self, MsgId):"" "We'll punt if we don ' t have a translation" ""Tryreturn Self.trans[msgid]Except Keyerror:Return str (MSGID)ClassEnglishgetter:"" "Simply echoes the Msg IDs" ""def get (self, msgid): return str (msgid) def get_localizer (Language= "中文版") : return Languages[language] () # Create our localizerse, G = get_ Localizer ( "中文版"), Get_localizer ( "China") # Localize some textfor msgid in " dog Parrot Cat Bear ". Split (): Print (E.get (msgid), G.get (MsgId))
2. Abstract Factory (Abstraction Factory)
Intent: Provides an interface that creates a series of related or interdependent objects without specifying their specific classes.
Applicability:
A system is independent of the creation, composition, and presentation of its products.
When a system is to be configured by one of multiple product families.
When you want to emphasize the design of a series of related product objects for joint use.
When you provide a Product class library and just want to display their interfaces instead of implementing them.
#!/usr/bin/python#coding: UTF8"' Abstract Factory 'Import RandomClassPetShop:"" A Pet Shop "" "Def__init__(Self, Animal_factory=none):"" "Pet_factory is our abstract factory. We can set it at would. "" "Self.pet_factory = Animal_factoryDefShow_pet(self):"" "creates and shows a pet using the abstract factory" "" "Pet = Self.pet_factory.get_pet () print ("This is a lovely", str (PET)) print ("It says", Pet.speak ()) Print ("It Eats", Self.pet_factory.get_food ())# Stuff that our factory makesClassDog:DefSpeak(self):Return"Woof"Def__str__(self):Return"Dog"ClassCat:DefSpeak(self):Return"Meow"Def__str__(self):Return"Cat"# Factory ClassesClassDogfactory:DefGet_pet(self):Return Dog ()DefGet_food(self):Return"Dog Food"ClassCatfactory:DefGet_pet(self):Return Cat ()def get_food (self): return " cat food "# Create the proper Familydef get_factory (): "" "Let's Be dynamic!" "" return random.choice ([Dogfactory, Catfactory]) () # Show Pets With various Factoriesif __name__ = "__main__": Shop = PetShop () for i in range (3): shop.pet_ Factory = Get_factory () shop.show_pet () print ( "=" * 20)
3. Builder (Builders)
Intent: To separate the construction of a complex object from its representation so that the same build process can create different representations.
Applicability:
When creating complex objects, the algorithm should be independent of the parts of the object and how they are assembled.
When the construction process must allow the constructed object to have different representations.
#!/usr/bin/python#coding: UTF8"" "Builder" ""# DirectorClassDirector(object):Def__init__(self): Self.builder =NoneDefConstruct_building(self): self.builder.new_building () Self.builder.build_floor () self.builder.build_size ()DefGet_building(self):Return self.builder.building# Abstract BuilderClassBuilder(object):Def__init__(self): self.building =NoneDefNew_building(self): self.building = Building ()# concrete BuilderClassBuilderhouse(Builder):DefBuild_floor(self): Self.building.floor =' One 'DefBuild_size(self): Self.building.size =' Big 'ClassBuilderflat(Builder):DefBuild_floor(self): Self.building.floor =' More than one 'DefBuild_size(self): Self.building.size =' Small '# ProductClassBuilding(object): def __init__(self): Self.floor = None self.size = none def __repr__(self) : return ' Floor:%s | Size:%s '% (Self.floor, self.size)# Clientif __name__ = = "__main__": Director = Director () Director.builde R = Builderhouse () director.construct_building () building = Director.get_building () print (building) Director.builder = Builderflat () director.construct_building () building = Director.get_building () print (building)
4. Prototype (prototype)
Intent: Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.
Applicability:
- When the class to instantiate is specified at run time, for example, by dynamic loading.
- To avoid creating a factory class hierarchy that is parallel to the product class hierarchy.
- When an instance of a class can have only one of several different state combinations. Building the corresponding number of prototypes and cloning them may be more convenient than manually instantiating the class each time you use the appropriate state.
#!/usr/bin/python#coding: UTF8"' Prototype 'Import CopyClassPrototype:Def__init__(self): self._objects = {}DefRegister_object(self, name, obj):"" "Register An Object" "" self._objects[name] = objDefUnregister_object(self, name):"" "Unregister An Object" ""Del Self._objects[name]DefClone(Self, Name, **attr):"" "Clone a registered object and update inner attributes dictionary" "" obj = copy.deepcopy (self._objects.get (name)) obj.__ Dict__.update (attr)return objdef main(): class A: def __str__(self): return "I am a" a = A () Prototype = prototype () Prototype.register_object (' a ', a) b = Prototype.clone (' A ', a=1, b=2, c= 3) print (a) print (B.A, b.b, B.C)if __name__ = = ' __main__ ': Main () /c13>
Reference articles
Https://www.cnblogs.com/Liqiongyu/p/5916710.html
Python design mode (2): Create type