设计模式-(14)装饰者模式 (swift版)
2024-08-30 16:35:21
一,概念
装饰者模式(Decorator):动态地为一个对象添加一些额外的职责,若要扩展一个对象的功能,装饰者提供了比继承更有弹性的替代方案。
多组合,少继承
二,UML图
抽象构件类(Component):给出一个抽象的接口,用以规范准备接收附加责任的对象
具体构件类(ConcreteComponent):定义一个具体的准备接受附加责任的类,其必须实现Component接口。
装饰者类(Decorator):持有一个构件(Conponent)对象的实例,并定义一个和抽象构件一致的接口。
具体装饰者类(Concrete Decoratator):定义给构件对象“贴上”附加责任。
三,使用案例
protocol Component {
func display() -> Void;
} class ComponentDecorator: Component { var component: Component
var border: String? init(component: Component) {
self.component = component
} func display() {
component.display()
}
}
class ListView: Component { var name: String = "listView" func display() {
print(name)
}
} class BoxView: Component { var name: String = "boxView" func display() {
print(name)
}
}
class BlackBoder: ComponentDecorator { override init(component: Component) {
super.init(component: component)
border = "black"
} override func display() {
setBorder()
super.display()
} func setBorder() {
print("this border is \(border ?? "default")")
} } class YellowBoder: ComponentDecorator { override init(component: Component) {
super.init(component: component)
border = "yellow"
} override func display() {
setBorder()
super.display()
} func setBorder() {
print("this border is \(border ?? "default")")
} }
用户端:
class ViewController: UIViewController { override func viewDidLoad() {
super.viewDidLoad()
let component = ListView()
let componentB = YellowBoder(component: component)
componentB.display()
}
}
最新文章
- bzoj3223
- 如何方便的保存WinForm窗体控件的位置大小等等配置信息
- 《Entity Framework 6 Recipes》翻译系列 (1) -----第一章 开始使用实体框架之历史和框架简述
- Shader for sprite clipping
- 中文字符集编码Unicode ,gb2312 , cp936 ,GBK,GB18030
- oracle Form Builer:ID_NULL Built-in
- createElement
- wpa_cli和wpa_supplicant使用,配置无线AP名和密码,静态ip地址
- .net mvc Authorization Filter,Exception Filter与Action Filter
- Chapter 2 Open Book——1
- AMQP协议学习
- JAVA描述的简单ORM框架
- js取整并保留两位小数的方法
- [源码分析]StringBuilder
- H5_0003:JS禁用调试,禁用右键,监听F12事件的方法
- 如何查看Ubuntu版本,以及Linux内核版本??
- Access大数据高效分页语句
- org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or br
- mysql mapper中增删查改
- Java中的类与对象