設計模式-(14)裝飾者模式 (swift版)

來源:互聯網
上載者:User

標籤:uml圖   使用   highlight   void   功能   額外   load   setborder   elf   

一,概念

  裝飾者模式(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()    }}

 

設計模式-(14)裝飾者模式 (swift版)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.