Python实现外观模式、桥接模式、组合模式和享元模式

2024年 4月 12日 91.0k 0

今天介绍四种结构型设计模式:外观模式、桥接模式、组合模式和享元模式。

外观模式

外观模式(Facade Pattern),它为子系统提供一个统一的接口,使得子系统更加容易使用。

在Python中,我们可以通过定义一个外观类来实现外观模式。这个外观类包含了一组子系统的接口,并提供了一个简单的接口供客户端使用。

下面是一个简单的例子:

class Subsystem1:
    def method1(self):
        print("Subsystem1 method1")

class Subsystem2:
    def method2(self):
        print("Subsystem2 method2")

class Facade:
    def __init__(self):
        self.subsystem1 = Subsystem1()
        self.subsystem2 = Subsystem2()

    def operation(self):
        self.subsystem1.method1()
        self.subsystem2.method2()

if __name__ == "__main__":
    facade = Facade()
    facade.operation()

在这个例子中,Subsystem1和Subsystem2是两个子系统,它们分别实现了自己的一组接口。Facade是一个外观类,它包含了Subsystem1和Subsystem2的接口,并提供了一个简单的operation接口供客户端使用。

举例说明:

假设我们有一个电子商务网站,它包含了一组子系统:商品管理、订单管理、用户管理等。我们可以通过定义一个外观类,将这些子系统的接口封装起来,提供一个简单的接口供客户端使用。

class ProductManager:
    def add_product(self, product):
        print("Add product:", product)

class OrderManager:
    def add_order(self, order):
        print("Add order:", order)

class UserManager:
    def add_user(self, user):
        print("Add user:", user)

class ECommerceFacade:
    def __init__(self):
        self.product_manager = ProductManager()
        self.order_manager = OrderManager()
        self.user_manager = UserManager()

    def add_product(self, product):
        self.product_manager.add_product(product)

    def add_order(self, order):
        self.order_manager.add_order(order)

    def add_user(self, user):
        self.user_manager.add_user(user)

if __name__ == "__main__":
    facade = ECommerceFacade()
    facade.add_product("iPhone")
    facade.add_order("Order001")
    facade.add_user("User001")

在这个例子中,ProductManager、OrderManager、UserManager是三个子系统,它们分别实现了自己的一组接口。ECommerceFacade是一个外观类,它包含了这三个子系统的接口,并提供了一个简单的add_product、add_order、add_user接口供客户端使用。

客户端只需要调用ECommerceFacade提供的接口,就可以完成商品、订单、用户的添加操作,而不需要了解具体的子系统实现。这样就大大简化了客户端的代码。

桥接模式

桥接模式(Bridge Pattern),它将抽象部分和实现部分分离开来,使得它们可以独立地变化。在Python中,我们可以通过定义一个抽象类和一个实现类来实现桥接模式。

from abc import ABC, abstractmethod

class Abstraction(ABC):
    def __init__(self, implementation):
        self.implementation = implementation

    @abstractmethod
    def operation(self):
        pass

class Implementation:
    def operation_impl(self):
        pass

class ConcreteAbstraction(Abstraction):
    def operation(self):
        self.implementation.operation_impl()

在上面的代码中,我们定义了一个抽象类Abstraction和一个实现类Implementation。在Abstraction类中,我们定义了一个抽象方法operation,在ConcreteAbstraction类中,我们实现了operation方法,调用了实现类的方法。这样,我们就将抽象部分和实现部分分离开来了。

组合模式

组合模式(Composite Pattern),它允许我们将对象组合成树形结构来表示“部分-整体”的层次结构。在Python中,我们可以通过定义一个抽象类和一个组合类来实现组合模式。

from abc import ABC, abstractmethod

class Component(ABC):
    @abstractmethod
    def operation(self):
        pass

class Composite(Component):
    def __init__(self):
        self.children = []

    def add(self, component):
        self.children.append(component)

    def remove(self, component):
        self.children.remove(component)

    def operation(self):
        for child in self.children:
            child.operation()

在上面的代码中,我们定义了一个抽象类Component和一个组合类Composite。在Composite类中,我们定义了一个children列表,用来存储子组件。在add和remove方法中,我们可以添加和删除子组件。在operation方法中,我们遍历子组件,调用其operation方法。

享元模式

享元模式(Flyweight Pattern),它通过共享对象来减少内存的使用。在Python中,我们可以通过定义一个享元工厂类和一个享元类来实现享元模式。

class Flyweight:
    def __init__(self, state):
        self.state = state

    def operation(self, extrinsic_state):
        pass

class FlyweightFactory:
    def __init__(self):
        self.flyweights = {}

    def get_flyweight(self, state):
        if state not in self.flyweights:
            self.flyweights[state] = Flyweight(state)
        return self.flyweights[state]

在上面的代码中,我们定义了一个享元类Flyweight和一个享元工厂类FlyweightFactory。在Flyweight类中,我们定义了一个state属性,表示享元的内部状态,在operation方法中,我们可以传入一个外部状态extrinsic_state,用来改变享元的行为。在FlyweightFactory类中,我们维护了一个flyweights字典,用来存储已经创建的享元对象。在get_flyweight方法中,我们根据传入的状态state,返回一个已经创建的享元对象或者新创建一个享元对象。这样,我们就可以通过共享对象来减少内存的使用了。

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论