Python 设计模式——门面模式

2020-12-25  本文已影响0人  rollingstarky

门面(facade)指建筑物的表面,尤其是最有吸引力的那一面。当人们从建筑物旁边经过时,可以欣赏其外部面貌,而不必了解其本身结构的复杂性。门面在隐藏内部复杂性的同时,也为客户端提供了一个可以轻松访问的接口。

比如需要到某个商店买东西,但对于该商店的布局并不清楚。可以直接找店主说明需要哪些东西,由店主将这些商品找到并提供给顾客。即店主作为购物的接口,顾客无需了解具体商品的位置。

门面设计模式的特点:

UML

门面

系统

客户端

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!

最少知识原则

门面能够将客户端与实现具体功能的子系统解耦,其背后的设计原理即最少知识原则。

上一篇 下一篇

猜你喜欢

热点阅读