当前位置:网站首页>组合模式: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 方法,只是实现方式不同(容器是访问所有子结点,叶子是只访问当前)。并且,容器和叶子可以在需要的时候,都视作 “组件” 来使用。
边栏推荐
- The web project accesses static resources inside the reference jar
- 多租户技术
- CSDN 21 Days Learning Challenge - Polymorphism (05)
- 序列化技术ProtoBuf
- Singleton pattern base class
- 多元线性回归分析(Stata)
- Development environment variable record under win
- Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security
- ES复杂操作搜索
- LiveGBS操作日志页面快速的筛选上级平台的调用记录直播观看录像回看等操作
猜你喜欢
大连理工&鹏城&UAE提出用于伪装目标检测的混合尺度三重网络ZoomNet,性能SOTA!
「业务架构」TOGAF建模:组织分解图(组织映射)
LCD DRM驱动框架分析一
PPT | 「课件」企业中高层人员安全管理培训(118页)
"Data Strategy" Results-Driven Enterprise Data Strategy: Organization and Governance
【微服务架构】微服务与SOA架构(2)
Redis(三)——配置文件详解、发布和订阅、新数据类型
跨公网环境,路由策略,进行设备的访问
「首席工程师」首席(Principal )工程师修炼之道
腾讯云校园大使开始招募啦,内推名额和奖金等你来拿
随机推荐
3D rotating text animation js special effects
FastReport.Net 2022.2.17 Crack
兼容移动和PC的loading加载和toast消息插件
VBA: 采用Combox控件实现二级下拉菜单功能
高通 msm8953 LCD 休眠/唤醒 流程
数据库事务
[Azure Cloud] What is the difference between a service endpoint and a private link?point of view (1)
Techches Transformer the join wisdom source the author cao, visual basic model study
VBA: Inputbox Function and Inputbox Method
对话陈赐靓:哪吒要让高端产品大众化
CatchAdmin实战教程(四)Table组件之自定义基础页面
what is bsp in rtems
dedecms支持Word内容一键上传
ECCV 2022 | 视频理解新框架X-CLIP:仅用微调的成本,达到预训练的全能
LCD DRM component 框架分析
武功修炼:招式
bus event bus use
WebView2 通过 PuppeteerSharp 实现爬取 王者 壁纸 (案例版)
自动化测试及Selenium
Flutter实战-请求封装(五)之Isolate线程改造