门面(facade)指建筑物的表面,尤其是最有吸引力的那一面。当人们从建筑物旁边经过时,可以欣赏其外部面貌,而不必了解其本身结构的复杂性。门面在隐藏内部复杂性的同时,也为客户端提供了一个可以轻松访问的接口。
比如需要到某个商店买东西,但对于该商店的布局并不清楚。可以直接找店主说明需要哪些东西,由店主将这些商品找到并提供给顾客。即店主作为购物的接口,顾客无需了解具体商品的位置。
门面设计模式的特点:
- 为子系统的一组接口提供一个统一的高级接口,帮助客户端以更简单的方式使用这些子系统
- 门面并不是封装子系统,而是对底层子系统进行组合。即用单个接口对象表示复杂的子系统
门面
- 一个接口,知道某个请求应该交由那个子系统处理
- 通过组合的方式将客户端的请求委派给相应的子系统对象
系统
- 实现子系统的功能,由一组负责不同任务的类来表示
- 处理门面对象分配的工作,但并不知道门面也不引用它
客户端
- 会实例化门面
- 会向门面提出请求
class EventManager: def __init__(self): print("Event Manager:: Let me talk to the folks\n") def arrange(self): self.hotelier = Hotelier() self.hotelier.bookHotel() self.florist = Florist() self.florist.setFlowerRequirements() self.caterer = Caterer() self.caterer.setCuisine() self.musician = Musician() self.musician.setMusicType() class Hotelier: def __init__(self): print("Arranging the Hotel for Marriage? --") def __isAvailable(self): print("Is the Hotel free for the event on given day?") return True def bookHotel(self): if self.__isAvailable(): print("Registered the Booking\n\n") class Florist: def __init__(self): print("Flower Decorations for the Event? --") def setFlowerRequirements(self): print("Carnations, Roses and Lilies would be used for Decorations\n\n") class Caterer: def __init__(self): print("Food Arrangements for the Event --") def setCuisine(self): print("Chinese & Continental Cuisine to be served\n\n") class Musician: def __init__(self): print("Musical Arrangements for the Marriage --") def setMusicType(self): print("Jazz and Classical will be played\n\n") class You: def __init__(self): print("You:: Whoa! Marriage Arrangements??!!!") def asskEventManager(self): print("You:: Let's Contact the Event Manager\n\n") em = EventManager() em.arrange() def __del__(self): print("You:: Thanks to Event Manager, all preparations done!") you = You() you.asskEventManager() # => You:: Whoa! Marriage Arrangements??!!! # => You:: Let's Contact the Event Manager # => Event Manager:: Let me talk to the folks # => Arranging the Hotel for Marriage? -- # => Is the Hotel free for the event on given day? # => Registered the Booking # => Flower Decorations for the Event? -- # => Carnations, Roses and Lilies would be used for Decorations # => Food Arrangements for the Event -- # => Chinese & Continental Cuisine to be served # => Musical Arrangements for the Marriage -- # => Jazz and Classical will be played # => You:: Thanks to Event Manager, all preparations done!
最少知识原则
门面能够将客户端与实现具体功能的子系统解耦,其背后的设计原理即最少知识原则。
- 在设计系统时,对于创建的每个对象,都应该考察与之交互的类的数量,以及交互的方式
- 避免创建许多彼此紧密耦合的类。若类之间存在大量的依赖关系,系统就会变得难以维护,应坚决避免