(Python3 代码实现)《大话设计模式》八:外观模式

在这里插入图片描述

  • 模式特点:为一组调用提供一致的接口。
  • 程序实例:接口将几种调用分别组合成为两组,用户通过接口调用其中的一组。
  • 代码特点:无
class SubSystemOne:
    def MethodOne(self):
        print("SubSysOne")


class SubSystemTwo:
    def MethodTwo(self):
        print("SubSysTwo")


class SubSystemThree:
    def MethodThree(self):
        print("SubSysThree")


class SubSystemFour:
    def MethodFour(self):
        print("SubSysFour")


class Facade:
    def __init__(self):
        self.one = SubSystemOne()
        self.two = SubSystemTwo()
        self.three = SubSystemThree()
        self.four = SubSystemFour()

    def MethodA(self):
        print("MethodA")
        self.one.MethodOne()
        self.two.MethodTwo()
        self.four.MethodFour()

    def MethodB(self):
        print("MethodB")
        self.two.MethodTwo()
        self.three.MethodThree()


if __name__ == "__main__":
    facade = Facade()
    facade.MethodA()
    facade.MethodB()
设计模式是一种解决软件设计问题的经验总结,它提供了一套可重用的设计思想和解决方案。在Python中,我们也可以应用设计模式来提高代码的可维护性、可扩展性和可复用性。下面是一些常见的设计模式Python中的实现: 1. 单例模式(Singleton Pattern):确保一个类只有一个实例,并提供全局访问点。 ```python class Singleton: _instance = None def __new__(cls): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance ``` 2. 工厂模式(Factory Pattern):通过一个工厂类来创建对象,而不是直接实例化对象。 ```python class Product: def __init__(self, name): self.name = name class ProductFactory: @staticmethod def create_product(name): return Product(name) ``` 3. 观察者模式(Observer Pattern):定义了一种一对多的关系,让多个观察者对象同时监听某一个主题对象。 ```python class Subject: def __init__(self): self.observers = [] def attach(self, observer): self.observers.append(observer) def detach(self, observer): self.observers.remove(observer) def notify(self): for observer in self.observers: observer.update() class Observer: def update(self): print("Received update from subject.") ``` 以上是三个常见的设计模式Python中的简单示例,实际应用中可能会更加复杂。当然,根据具体的需求和场景,选择合适的设计模式是很重要的。希望这些示例对你有所帮助!如果你对其他设计模式感兴趣,可以继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值