iOS设计模式-装饰器

概念

装饰器模式是一种结构型设计模式 ,它允许你在不修改原有类的情况下,通过"包裹"的方式动态地为对象添加新功能。与继承不同,它在运行时灵活组合,符合开闭原则(对扩展开放,对修改关闭)。

适用场景

适用于 在基本功能基础上,进行功能叠加场景。

角色

协议:行为抽象

功能组件:遵守协议,实现基础功能

装饰器基类:遵守协议,持有功能组件,调用转发

装饰器扩展:继承自装饰器基类,通过重载,进行行为扩展(功能叠加)

示例:咖啡配料系统

  • 定义协议
scss 复制代码
protocol Coffee {
    func description() -> String
    func cost() -> Double
}
  • 功能组件,遵守协议。

实现基本功能。

csharp 复制代码
class PlainCoffee: Coffee {
    func description() -> String { "简单咖啡" }
    func cost() -> Double { 10.0 }
}
  • 基础装饰器(持有引用功能组件,同时也遵守协议,转发调用)

作为基类

swift 复制代码
class CoffeeDecorator: Coffee {

    private let decoratedCoffee: Coffee

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

    // 协议调用 转发
    func description() -> String {
        decoratedCoffee.description()
    }

    func cost() -> Double {
        decoratedCoffee.cost()
    }
}
  • 具体装饰器(扩展行为)

继承自 基础装饰器,重载;

职责单一: 每个装饰器只做一件事,(每种功能分开写在一个子类中

swift 复制代码
class MilkDecorator: CoffeeDecorator {
    override func description() -> String {
        super.description() + ",加牛奶"
    }
    override func cost() -> Double {
        super.cost() + 5.0
    }
}

class SugarDecorator: CoffeeDecorator {
    override func description() -> String {
        super.description() + ",加糖"
    }
    override func cost() -> Double {
        super.cost() + 3.0
    }
}

class VanillaDecorator: CoffeeDecorator {
    override func description() -> String {
        super.description() + ",香草风味"
    }
    override func cost() -> Double {
        super.cost() + 8.0
    }
}
  • 灵活组合

功能一层一层加

scss 复制代码
let plain = PlainCoffee()
print(plain.description()) // 简单咖啡
print(plain.cost())        // 10.0

// 组合 叠加
let milkCoffee = MilkDecorator(plain)
let sugerCoffee = SugarDecorator(milkCoffee)
let fancyCoffee = VanillaDecorator(sugerCoffee)

print(fancyCoffee.description())
// 简单咖啡,加牛奶,加糖,香草风味

print(fancyCoffee.cost())
// 26.0(10 + 5 + 3 + 8)
  • 可扩展性:

需要加其他功能?只需再写一个对应的装饰器,插入链中,其他代码零修改。

相关推荐
mayaairi13 分钟前
Vue2 组件通讯(四):v-model、scoped样式、mixins与plugins
前端·javascript·vue.js
梦曦i24 分钟前
@meng-xi/uni-router 未来展望:夯实基础、深化体验、探索前沿
前端·uni-app
Yeyu25 分钟前
AAOS AppCard 实践:怎么把自己的 App 塞进别人的卡片里
前端
IT_陈寒1 小时前
Vite静态资源路径这个大坑害我调了一下午
前端·人工智能·后端
狗哥哥1 小时前
分享下我的读书清单
前端
合天网安实验室1 小时前
Log4J2 FilteredObjectInputStream RCE 漏洞分析
前端·黑客
两点王爷2 小时前
使用 GeoServer 发布 SHP 数据并在前端页面加载显示
前端
lhldsg2 小时前
全民健身解决方案软件开发实战:从架构设计到部署指南
java·前端·数据库·小程序
四六的六2 小时前
让 AI 自己去点后台页面,它把我们的库存点没了
前端·人工智能·agent·个人开发·ai编程·ai产品·ai前端
两点王爷2 小时前
Java 与前端加载 MVT 数据:从服务端切片到浏览器渲染
java·前端·状态模式