一,概念

  装饰者模式(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()
}
}

最新文章

  1. bzoj3223
  2. 如何方便的保存WinForm窗体控件的位置大小等等配置信息
  3. 《Entity Framework 6 Recipes》翻译系列 (1) -----第一章 开始使用实体框架之历史和框架简述
  4. Shader for sprite clipping
  5. 中文字符集编码Unicode ,gb2312 , cp936 ,GBK,GB18030
  6. oracle Form Builer:ID_NULL Built-in
  7. createElement
  8. wpa_cli和wpa_supplicant使用,配置无线AP名和密码,静态ip地址
  9. .net mvc Authorization Filter,Exception Filter与Action Filter
  10. Chapter 2 Open Book——1
  11. AMQP协议学习
  12. JAVA描述的简单ORM框架
  13. js取整并保留两位小数的方法
  14. [源码分析]StringBuilder
  15. H5_0003:JS禁用调试,禁用右键,监听F12事件的方法
  16. 如何查看Ubuntu版本,以及Linux内核版本??
  17. Access大数据高效分页语句
  18. org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or br
  19. mysql mapper中增删查改
  20. Java中的类与对象

热门文章

  1. Cannot delete or update a parent row: a foreign key constraint fails....
  2. 一、SQL基础知识点补充
  3. 图的最小生成树——Kruskal算法
  4. 倍增法求LCA
  5. PTA 02-线性结构3 Reversing Linked List (25分)
  6. 【shell】通过shell编写ping包及arp的监控并发送短信
  7. 七牛云一站式 SSL 证书服务上线,即刻使用最多可省 7 万
  8. dfs树上的边
  9. 洛谷——P1347 排序
  10. java面向对象day01