美文网首页设计模式
设计模式-装饰者模式

设计模式-装饰者模式

作者: Hengry | 来源:发表于2023-10-13 09:39 被阅读0次

装饰者模式(Decorator Pattern)是一种结构型设计模式,它允许你在不修改现有对象的基础上,动态地添加功能>或责任。这种模式通常用于扩展类的功能,同时保持类的封装性。

下面是一个简单的装饰者模式的案例,假设我们有一个简单的咖啡店,需要制作不同种类的咖啡,并可以根据客户的需求添加额外的配料,如牛奶和糖。

首先,定义一个咖啡接口:

protocol Coffee {
    func cost() -> Double
    func description() -> String
}

然后,实现具体的咖啡类:

class SimpleCoffee: Coffee {
    func cost() -> Double {
        return 1.0 // 简单咖啡的价格
    }

    func description() -> String {
        return "简单咖啡"
    }
}

接下来,创建装饰者类,用于动态地添加配料:

class CoffeeDecorator: Coffee {
    private let decoratedCoffee: Coffee

    init(decoratedCoffee: Coffee) {
        self.decoratedCoffee = decoratedCoffee
    }

    func cost() -> Double {
        return decoratedCoffee.cost()
    }

    func description() -> String {
        return decoratedCoffee.description()
    }
}

然后,创建具体的配料装饰者,如牛奶和糖:

class MilkDecorator: CoffeeDecorator {
    override func cost() -> Double {
        return super.cost() + 0.5 // 加入牛奶的价格
    }

    override func description() -> String {
        return super.description() + ", 牛奶"
    }
}

class SugarDecorator: CoffeeDecorator {
    override func cost() -> Double {
        return super.cost() + 0.2 // 加入糖的价格
    }

    override func description() -> String {
        return super.description() + ", 糖"
    }
}

现在,你可以使用装饰者模式来制作不同种类的咖啡,并根据客户的需求添加配料:

var coffee: Coffee = SimpleCoffee()
print("咖啡描述:\(coffee.description()), 价格:$\(coffee.cost())")

coffee = MilkDecorator(decoratedCoffee: coffee)
print("咖啡描述:\(coffee.description()), 价格:$\(coffee.cost())")

coffee = SugarDecorator(decoratedCoffee: coffee)
print("咖啡描述:\(coffee.description()), 价格:$\(coffee.cost())")

通过装饰者模式,你可以灵活地组合不同种类的咖啡和配料,而不需要创建大量的子类,同时保持了代码的可扩展性和可维护性。这种模式常用于构建复杂的对象组合和装饰。

相关文章

  • 设计模式

    设计模式 单例模式、装饰者模式、

  • 设计模式笔记汇总

    目录 设计原则 “依赖倒置”原则 未完待续... 设计模式 设计模式——策略模式 设计模式——装饰者模式 设计模式...

  • java IO 的知识总结

    装饰者模式 因为java的IO是基于装饰者模式设计的,所以要了解掌握IO 必须要先清楚什么事装饰者模式(装饰者模式...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • JavaScript 设计模式核⼼原理与应⽤实践 之 结构型设计

    JavaScript 设计模式核⼼原理与应⽤实践 之 结构型设计模式 装饰器模式,又名装饰者模式。它的定义是“在不...

  • 8种设计模式:

    主要介绍 单例设计模式,代理设计模式,观察者设计模式,模板模式(Template), 适配器模式,装饰模式(Dec...

  • 装饰者模式

    JavaScript 设计模式 张容铭第十二章 房子装修--装饰者模式 (102页) 装饰者模式(Decorato...

  • Summary of February 2017

    READING Head First 设计模式:完成50%。内容:观察者模式、装饰者模式、工厂模式、单件模式、命令...

  • 装饰对象:装饰者模式

    装饰对象:装饰者模式   这是《Head First设计模式(中文版)》第三章的读书笔记。   装饰者模式,可以称...

  • 设计模式之装饰器模式

    也称装饰者模式、装饰器模式、Wrapper、Decorator。 装饰模式是一种结构型设计模式,允许你通过将对象放...

网友评论

    本文标题:设计模式-装饰者模式

    本文链接:https://www.haomeiwen.com/subject/ljxabdtx.html