代理模式
Proxy模式是一種常用的設計模式,它主要用來通過一個對象(比如B)給一個對象(比如A) 提供'代理'的方式方式訪問。比如一個對象不方便直接引用,代理就在這個對象和訪問者之間做了中介
python的例子
你先設想:一個對象提供rgb三種顏色值,我想獲得一個對象的rgb三種顏色,但是我不想讓你獲得藍色屬性,怎么辦?
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
|
class Proxy( object ): def __init__( self , subject): self .__subject = subject # 代理其實本質上就是屬性的委托 def __getattr__( self , name): return getattr ( self .__subject, name) class RGB: def __init__( self , red, green, blue): self .__red = red self .__green = green self .__blue = blue def Red( self ): return self .__red def Green( self ): return self .__green def Blue( self ): return self .__blue class NoBlueProxy(Proxy): # 我在這個子代理類攔截了blue的訪問,這樣就不會返回被代理的類的Blue屬性 def Blue( self ): return 0 if __name__ = = '__main__' : rgb = RGB( 100 , 192 , 240 ) print rgb.Red() proxy = Proxy(rgb) print proxy.Green() noblue = NoBlueProxy(rgb) print noblue.Green() print noblue.Blue() |
模板方法模式
不知道你有沒有注意過,我們實現某個業務功能,在不同的對象會有不同的細節實現, 如果說策略模式, 策略模式是將邏輯封裝在一個類(提到的文章中的Duck)中,然后使用委托的方式解決。 模板方法模式的角度是:把不變的框架抽象出來,定義好要傳入的細節的接口. 各產品類的公共的行為 會被提出到公共父類,可變的都在這些產品子類中
python的例子
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
|
# 整個例子我們要根據不同需求處理的內容 ingredients = "spam eggs apple" line = '-' * 10 # 這是被模板方法調用的基礎函數 def iter_elements(getter, action): """循環處理的骨架""" # getter是要迭代的數據,action是要執行的函數 for element in getter(): action(element) print (line) def rev_elements(getter, action): """反向的""" for element in getter()[:: - 1 ]: action(element) print (line) # 數據經過函數處理就是我們最后傳給模板的內容 def get_list(): return ingredients.split() # 同上 def get_lists(): return [ list (x) for x in ingredients.split()] # 對數據的操作 def print_item(item): print (item) #反向處理數據 def reverse_item(item): print (item[:: - 1 ]) # 模板函數 def make_template(skeleton, getter, action): # 它抽象的傳入了 骨架,數據,和子類的操作函數 def template(): skeleton(getter, action) return template # 列表解析,數據就是前面的2種骨架(定義怎么樣迭代),2個分割數據的函數,正反向打印數據的組合 templates = [make_template(s, g, a) for g in (get_list, get_lists) for a in (print_item, reverse_item) for s in (iter_elements, rev_elements)] # 執行 for template in templates: template() |