创建型
1.Factory Method(工厂方法)
意图:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
适用性:
当一个类不知道它所必须创建的对象的类的时候。
当一个类希望由它的子类来指定它所创建的对象的时候。
当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#!/usr/bin/python #coding:utf8 ''' Factory Method ''' class ChinaGetter: """A simple localizer a la gettext""" def __init__( self ): self .trans = dict (dog = u "小狗" , cat = u "小猫" ) def get( self , msgid): """We'll punt if we don't have a translation""" try : return self .trans[msgid] except KeyError: return str (msgid) class EnglishGetter: """Simply echoes the msg ids""" def get( self , msgid): return str (msgid) def get_localizer(language = "English" ): """The factory method""" languages = dict (English = EnglishGetter, China = ChinaGetter) return languages[language]() # Create our localizers e, g = get_localizer( "English" ), get_localizer( "China" ) # Localize some text for msgid in "dog parrot cat bear" .split(): print (e.get(msgid), g.get(msgid)) |
他通过保存类的地址让子类选择实例化的对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#!/usr/bin/python #coding:utf8 ''' Abstract Factory ''' import random class PetShop: """A pet shop""" def __init__( self , animal_factory = None ): """pet_factory is our abstract factory. We can set it at will.""" self .pet_factory = animal_factory def show_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 makes class Dog: def speak( self ): return "woof" def __str__( self ): return "Dog" class Cat: def speak( self ): return "meow" def __str__( self ): return "Cat" # Factory classes class DogFactory: def get_pet( self ): return Dog() def get_food( self ): return "dog food" class CatFactory: def get_pet( self ): return Cat() def get_food( self ): return "cat food" # Create the proper family def get_factory(): """Let's be dynamic!""" return random.choice([DogFactory, CatFactory])() # Show pets with various factories if __name__ = = "__main__" : shop = PetShop() for i in range ( 3 ): shop.pet_factory = get_factory() shop.show_pet() print ( "=" * 20 ) |
他改变了里面的方法,让他可以随机生成dog和cat的对象导致他可以使用他们的方法