当前位置:网站首页>组合模式:Swift 实现
组合模式:Swift 实现
2022-08-10 10:12:00 【大头鑫】
组合模式 Composite
We want to make the client using the Container or Leafs in a same calling way, so we set the leaf and the container that implement the same interface (Component). And the Container contains some children. In this way we create a model like tree, the client can treat every node similarly.
为了使客户端能够使用相同的方式调用 “容器” 和 “叶子”,我们让容器和叶子都去实现同一个接口 “组件”。并且容器中包含有一些子的容器。通过这种方式,我们可以创建一个类似于一棵树的模型,客户端对每个结点使用相同的对待方式。
// interface
protocol Component {
func execute()
}
class Leaf: Component {
func execute() {
print("I'm leaf")
}
}
class SubLeaf: Leaf {
override func execute() {
print("I'm sub leaf")
}
}
// Composite
class Containner:Component {
private var children: [Component] = []
func add(c: Component) {
children.append(c)
}
func remove(c: Component) {
}
func execute() {
for item in children {
item.execute()
}
}
}
// We treat the leaf and the containner as the same type of node.
let leaf = Leaf()
let leafTwo = Leaf()
let subLeaf = SubLeaf()
let c = Containner()
c.add(c: leaf)
c.add(c: leafTwo)
let root = Containner()
root.add(c: c)
root.add(c: subLeaf)
c.execute()
root.execute()
如上图:
- root 持有 c 的引用,c 持有 leaf 和 leafTwo 的引用。root 和 c 是 Container 类型,leafTwo 是 Leaf 类型。
- 容器和叶子都遵守了 “组件” 协议,所以都应当有 execute 方法,只是实现方式不同(容器是访问所有子结点,叶子是只访问当前)。并且,容器和叶子可以在需要的时候,都视作 “组件” 来使用。
边栏推荐
- PPT | 「课件」企业中高层人员安全管理培训(118页)
- 91.(cesium之家)cesium火箭发射模拟
- leetcode:334. 递增的三元子序列
- [C language] Floating point number rounding
- LiveNVR操作日志页面快速筛选上级国标平台的调用记录直播观看录像回看等操作
- Text selection rounded style border-radius
- Redis (six) - transaction and lock mechanism of Redis6 (unfinished, to be supplemented)
- 【微服务架构】微服务与SOA架构(2)
- web项目访问引用jar内部的静态资源
- "Data Architecture": How can master data management (MDM) help my industry?
猜你喜欢
Redis(六)——Redis6的事务和锁机制(未完成,待补)
Flutter实战-请求封装(五)之Isolate线程改造
「业务架构」TOGAF建模:组织分解图(组织映射)
Redis6(一)——NoSQL数据库简介与Redis的安装
chart.js水平柱状图插件
ESP8266 Tutorial 2 - Burn AT Firmware
【STL】位图的介绍使用以及代码的模拟实现
「应用架构」六边型架构:三个原则和一个实现示例
MongoDB数据库笔记
14 high-frequency handwritten JS interview questions and answers to consolidate your JS foundation
随机推荐
多租户技术
VBA: 遍历文件抓取指定条件的数据
反射效率为什么低?
ZZULIOJ 1124: 两个有序数组合并
LeetCode Algorithm 914. 卡牌分组
Payment x Aggregation x Ledger Separation - The Way to Avoid Risk of "Erqing" on the Return Platform
解决ASP.NET Core在Task中使用IServiceProvider的问题
俄罗斯宣布临时禁止进口摩尔多瓦植物产品
Which is the strongest workflow engine for "Technology Selection"?Chief Architecture Helps You Pick
Load balancing principle analysis and source code interpretation
gin-gonic/gin使用详解
Dialogue with Chen Ciliang: Nezha wants to popularize high-end products
「第二部:容器和微服务架构」(1) 基于容器应用架构设计原则
vs2012创建WCF应用程序
Development environment variable record under win
大连理工&鹏城&UAE提出用于伪装目标检测的混合尺度三重网络ZoomNet,性能SOTA!
「业务架构」TAGAF建模:业务服务/信息图
VBA:获取指定数值在指定一维数组中的位置
Taro小程序跨端开发入门实战
Automated Testing and Selenium