装饰者模式是一种结构型设计模式,它允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于打开/关闭原则,即对扩展开放,对修改关闭。

以下是一个简单的装饰者模式示例:

示例说明

在这个例子中,我们有一个Coffee类,代表咖啡。我们可以通过添加不同的装饰器来为咖啡添加不同的配料,如糖、牛奶等。

代码示例

class Coffee:
    def __init__(self):
        self.description = "Unflavored Coffee"

    def get_description(self):
        return self.description

class Milk(Coffee):
    def __init__(self, coffee):
        super().__init__()
        self.coffee = coffee
        self.description = self.coffee.get_description() + ", Milk"

    def get_description(self):
        return self.description

class Sugar(Coffee):
    def __init__(self, coffee):
        super().__init__()
        self.coffee = coffee
        self.description = self.coffee.get_description() + ", Sugar"

    def get_description(self):
        return self.description

使用示例

my_coffee = Coffee()
print(my_coffee.get_description())  # 输出: Unflavored Coffee

milk_coffee = Milk(my_coffee)
print(milk_coffee.get_description())  # 输出: Unflavored Coffee, Milk

sugar_coffee = Sugar(milk_coffee)
print(sugar_coffee.get_description())  # 输出: Unflavored Coffee, Milk, Sugar

扩展阅读

想要了解更多关于设计模式的信息,可以访问设计模式页面。

图片示例

下面是几种咖啡的图片:

Coffee
Milk_Coffee
Sugar_Coffee