外观模式
外观模式又叫做门面模式。
外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个可以访问系统的接口。
外观模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。
场景
在现实生活中,常常存在办事较复杂的例子,如办房产证或注册一家公司,有时要同多个部门联系,这时要是有一个综合部门能解决一切手续问题就好了。
软件设计也是这样,当一个系统的功能越来越强,子系统会越来越多,客户对系统的访问也变得越来越复杂。这时如果系统内部发生改变,客户端也要跟着改变,这违背了“开闭原则”,也违背了“迪米特法则”,所以有必要为多个子系统提供一个统一的接口,从而降低系统的耦合度,这就是外观模式的目标。
模式的结构
外观(Facade)模式包含以下主要角色。
1.外观(Facade)角色:为多个子系统对外提供一个共同的接口。
2.子系统(Sub System)角色:实现系统的部分功能,客户可以通过外观角色访问它。
3.客户(Client)角色:通过一个外观角色访问各个子系统的功能。
实现
import time
SLEEP = 0.5
# Sub System
class Sub1:
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 Sub2:
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 Sub3:
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 Fac:
def __init__(self):
self.sub1 = Sub1()
self.sub2 = Sub2()
self.sub3 = Sub3()
self.all = [i for i in (self.sub1, self.sub2, self.sub3)]
def run_all(self):
[i.run() for i in self.all]
# Client
if __name__ == '__main__':
facade = Fac()
facade.run_all()
优点
1.减少系统相互依赖。
2.提高灵活性。
3.提高了安全性。
缺点
1.不能很好地限制客户使用子系统类,很容易带来未知风险。
2.增加新的子系统可能需要修改外观类或客户端的源代码,违背了“开闭原则”。