舉例分析Python中設(shè)計模式之外觀模式的運用
應(yīng)用特性:
在很多復(fù)雜而小功能需要調(diào)用需求時,而且這些調(diào)用往往還有一定相關(guān)性,即一調(diào)用就是一系列的。
結(jié)構(gòu)特性:
把原本復(fù)雜而繁多的調(diào)用,規(guī)劃統(tǒng)一到一個入口類中,從此只通過這一個入口調(diào)用就可以了。
代碼結(jié)構(gòu)示例:
class ModuleOne(object): def Create(self): print 'create module one instance' def Delete(self): print 'delete module one instance' class ModuleTwo(object): def Create(self): print 'create module two instance' def Delete(self): print 'delete module two instance' class Facade(object): def __init__(self): self.module_one = ModuleOne() self.module_two = ModuleTwo() def create_module_one(self): self.module_one.Create() def create_module_two(self): self.module_two.Create() def create_both(self): self.module_one.Create() self.module_two.Create() def delete_module_one(self): self.module_one.Delete() def delete_module_two(self): self.module_two.Delete() def delete_both(self): self.module_one.Delete() self.module_two.Delete()
有點類似代理模式,不同之處是,外觀模式不僅代理了一個子系統(tǒng)的各個模塊的功能,同時站在子系統(tǒng)的角度,通過組合子系統(tǒng)各模塊的功能,對外提供更加高層的接口,從而在語義上更加滿足子系統(tǒng)層面的需求。
隨著系統(tǒng)功能的不斷擴張,當(dāng)需要將系統(tǒng)劃分成多個子系統(tǒng)或子模塊,以減少耦合、降低系統(tǒng)代碼復(fù)雜度、提高可維護性時,代理模式通常會有用武之地。
再來看一個例子:
class small_or_piece1: def __init__(self): pass def do_small1(self): print 'do small 1' class small_or_piece_2: def __init__(self): pass def do_small2(self): print 'do small 2' class small_or_piece_3: def __init__(self): pass def do_small3(self): print 'do small 3' class outside: def __init__(self): self.__small1 = small_or_piece1() self.__small2 = small_or_piece_2() self.__small3 = small_or_piece_3() def method1(self): self.__small1.do_small1() ##如果這里調(diào)用的不只2兩函數(shù),作用就顯示出來了,可以把原本復(fù)雜的函數(shù)調(diào)用關(guān)系清楚化,統(tǒng)一化 self.__small2.do_small2() def method2(self): self.__small2.do_small2() self.__small3.do_small3() if __name__ == '__main__': osd = outside() osd.method1() osd.method2()
結(jié)果:
do small 1 do small 2 do small 2 do small 3
相關(guān)文章
Sonar編譯問題對應(yīng):File [...] can''t be indexed twice.
今天小編就為大家分享一篇關(guān)于Sonar編譯問題對應(yīng):File [...] can't be indexed twice.,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12分享關(guān)于JAVA 中使用Preferences讀寫注冊表時要注意的地方
這篇文章介紹了關(guān)于JAVA 中使用Preferences讀寫注冊表時要注意的地方,有需要的朋友可以參考一下2013-08-08使用spring oauth2框架獲取當(dāng)前登錄用戶信息的實現(xiàn)代碼
這篇文章主要介紹了使用spring oauth2框架獲取當(dāng)前登錄用戶信息的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07