裝飾器模式
裝飾器模式(Decorator Pattern)允許向一個現有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬于結構型模式,它是作為現有的類的一個包裝。
這種模式創建了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
/Users/liuyao/Desktop/IMG_7187.JPG
我們通過下面的實例來演示裝飾器模式的用法。其中,我們將把一個形狀裝飾上不同的顏色,同時又不改變形狀類。
介紹
意圖:動態地給一個對象添加一些額外的職責。就增加功能來說,裝飾器模式相比生成子類更為靈活。
主要解決:一般的,我們為了擴展一個類經常使用繼承方式實現,由于繼承為類引入靜態特征,并且隨著擴展功能的增多,子類會很膨脹。
何時使用:在不想增加很多子類的情況下擴展類。
如何解決:將具體功能職責劃分,同時繼承裝飾者模式。
關鍵代碼: 1、Component 類充當抽象角色,不應該具體實現。 2、修飾類引用和繼承 Component 類,具體擴展類重寫父類方法。
應用實例: 1、孫悟空有 72 變,當他變成"廟宇"后,他的根本還是一只猴子,但是他又有了廟宇的功能。 2、不論一幅畫有沒有畫框都可以掛在墻上,但是通常都是有畫框的,并且實際上是畫框被掛在墻上。在掛在墻上之前,畫可以被蒙上玻璃,裝到框子里;這時畫、玻璃和畫框形成了一個物體。
優點:裝飾類和被裝飾類可以獨立發展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式可以動態擴展一個實現類的功能。
缺點:多層裝飾比較復雜。
**使用場景: ** 1、擴展一個類的功能。 2、動態增加功能,動態撤銷。
注意事項: 可代替繼承。
實現
IMG_7187.JPG
//
// ViewController.swift
// 003_Decorator_Pattern
//
// Created by 劉耀 on 2017/8/26.
// Copyright ? 2017年 liuyao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// testA()
testB()
}
fileprivate func testA() {
let b = Boy(name: "Kingcos")
// 按順序裝飾
let tShirtA = TShirt(b)
let chineseTunicSuitA = ChineseTunicSuit(tShirtA)
chineseTunicSuitA.show()
let chineseTunicSuitB = ChineseTunicSuit(b)
let tShirtB = TShirt(chineseTunicSuitB)
tShirtB.show()
}
fileprivate func testB() {
let circle = Circle()
circle.draw()
let redCircle = RedShapeDecorator(circle)
redCircle.draw()
let rect = Rectangle()
let redRectangle = RedShapeDecorator(rect)
redRectangle.draw()
}
}
// ============================== 案例1 =================
// 協議
protocol Person {
func show()
}
//遵守協議
struct Boy: Person {
var name = ""
func show() {
print("\(name)")
}
}
// 飾物遵守協議
class Finery: Person {
var component: Person
init(_ component: Person) {
self.component = component
}
func show() {
component.show()
}
}
// 繼承
class TShirt: Finery {
override func show() {
print("T 恤", separator: "", terminator: " + ")
super.show()
}
}
class ChineseTunicSuit: Finery {
override func show() {
print("中山裝", separator: "", terminator: " + ")
super.show()
}
}
// ============================== 案例2 =================
// 1. 創建一個接口。
protocol Shape {
func draw()
}
// 2.創建實現接口的實體類。
struct Rectangle: Shape {
func draw() {
print("Shape: Rectangle")
}
}
struct Circle: Shape {
func draw() {
print("Shape: Circle")
}
}
// 3. 創建實現了 Shape 接口的抽象裝飾類。
class ShapeDecrator:Shape {
var decoratedShape: Shape
init(_ decoratedShape: Shape) {
self.decoratedShape = decoratedShape
}
func draw() {
decoratedShape.draw()
}
}
// 4. 創建擴展了 ShapeDecorator 類的實體裝飾類。
class RedShapeDecorator: ShapeDecrator {
override func draw() {
super.draw() //decoratedShape.draw()
setRedBorder(decoratedShape)
}
fileprivate func setRedBorder(_ decoratedShape: Shape) {
print("Border Color: Red")
}
}
// 5. 使用 RedShapeDecorator 來裝飾 Shape 對象。