外觀.png
思想:重復代碼的封裝
意圖:
為子系統(tǒng)中的一組接口提供一個一致的界面沫勿,F(xiàn)acade模式定義了一個高層接口痹扇,這個接口使得這一子系統(tǒng)更加容易使用斑鸦。
適用性:
當你要為一個復雜子系統(tǒng)提供一個簡單接口時。子系統(tǒng)往往因為不斷演化而變得越來越復雜勺择。大多數(shù)模式使用時都會產(chǎn)生更多更小的類。這使得子系統(tǒng)更具可重用性伦忠,也更容易對子系統(tǒng)進行定制省核,但這也給那些不需要定制子系統(tǒng)的用戶帶來一些使用上的困難。Facade 可以提供一個簡單的缺省視圖昆码,這一視圖對大多數(shù)用戶來說已經(jīng)足夠芳撒,而那些需要更多的可定制性的用戶可以越過facade層。
客戶程序與抽象類的實現(xiàn)部分之間存在著很大的依賴性未桥。引入facade 將這個子系統(tǒng)與客戶以及其他的子系統(tǒng)分離,可以提高子系統(tǒng)的獨立性和可移植性芥备。
當你需要構建一個層次結構的子系統(tǒng)時冬耿,使用facade模式定義子系統(tǒng)中每層的入口點。如果子系統(tǒng)之間是相互依賴的萌壳,你可以讓它們僅通過facade進行通訊亦镶,從而簡化了它們之間的依賴關系。
案例一
import time
SLEEP = 0.5
# Complex Parts
class TC1:
def run(self):
print("###### In Test 1 ######")
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(SLEEP)
print("Test Finished\n")
class TC2:
def run(self):
print("###### In Test 2 ######")
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(SLEEP)
print("Test Finished\n")
class TC3:
def run(self):
print("###### In Test 3 ######")
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(SLEEP)
print("Test Finished\n")
# Facade
class TestRunner:
def __init__(self):
self.tc1 = TC1()
self.tc2 = TC2()
self.tc3 = TC3()
self.tests = [i for i in (self.tc1, self.tc2, self.tc3)]
def runAll(self):
[i.run() for i in self.tests]
# Client
if __name__ == '__main__':
testrunner = TestRunner()
testrunner.runAll()