美文网首页
iOS设计模式-装饰模式- Swift

iOS设计模式-装饰模式- Swift

作者: velue | 来源:发表于2019-03-01 21:49 被阅读0次

装饰模式

  • 1、装饰模式-定义
    动态地给一个对象添加一些额外的职责。

  • 2、装饰模式-场景
    需要透明且动态地扩展类的功能时。

  • 3、装饰模式-角色划分
    4个核心角色
    角色一:抽象组件
    角色二:具体组件
    角色三:抽象装饰者
    角色四:具体装饰者

  • 4、装饰模式-案例分析
    Decorator

    • 案例:给iPhoneX装手机壳,那么要装什么样的手机壳,可以通过装饰模式来实现
      • 角色一:抽象组件->MobilePhone(手机)
      • 角色二:具体组件->iPhoneX
      • 角色三:抽象装饰者->MobilePhoneShell
      • 角色四:具体装饰者,分别有质量好的手机膜和质量差的手机壳
        质量好的手机壳拥有耐磨、防水、防尘等等功能,那么我们将三种功能分别命名为:
        耐磨:wearproof()
        防水:waterproof()
        防尘:dustproof()
        GoodShell
        质量差的手机壳就逊色多了只有耐磨功能,命名为:
        耐磨:wearproof()
        PoorShell

角色一:抽象组件->MobilePhone(手机)


//
//  MobilePhone.swift
//  装饰模式-Swift
//

import Foundation

//角色一:抽象组件->MobilePhone(手机)
protocol MobilePhone {
    
    func shell()
}

角色二:具体组件->iPhoneX

//
//  iPhoneX.swift
//  装饰模式-Swift
//


import UIKit

//角色二:具体组件->iPhoneX
class iPhoneX: MobilePhone {

    func shell() {
        print("iPhone")
    }
}

角色三:抽象装饰者->MobilePhoneShell

//
//  MobilePhoneShell.swift
//  装饰模式-Swift


import UIKit

//角色三:抽象装饰者->MobilePhoneShell
//特点一:继承(实现)抽象组件
//特点二:持有抽象组件引用
class MobilePhoneShell:MobilePhone {
    
    private var mobile:MobilePhone
    
    init(mobile:MobilePhone) {
        self.mobile = mobile
    }
    
    func shell() {
        self.mobile.shell()
    }
}

角色四:具体装饰者

//
//  GoodShell.swift
//  装饰模式-Swift


import UIKit


//角色四:具体装饰者
class GoodShell: MobilePhoneShell {

    override init(mobile: MobilePhone) {
        super.init(mobile: mobile)
    }
    
    func wearproof() {
        print("耐磨功能")
    }
    
    func waterproof() {
        print("防水功能")
    }
    
    func dustproof() {
        print("防尘功能")
    }
}

具体装饰者

//
//  PoorShell.swift
//  装饰模式-Swift


import UIKit

//具体装饰者
class PoorShell: MobilePhoneShell {

    override init(mobile: MobilePhone) {
        super.init(mobile: mobile)
    }
    
    func wearproof() {
        print("耐磨功能")
    }
}

调用实现:

        let phone = iPhoneX()
        phone.shell()
        
        //好的装饰
        let good = GoodShell(mobile: phone)
        good.shell()//对象
        good.dustproof()
        good.waterproof()
        good.wearproof()
        
        //坏的装饰
        let poor = PoorShell(mobile: phone)
        poor.shell()//对象
        poor.wearproof()


相关文章

网友评论

      本文标题:iOS设计模式-装饰模式- Swift

      本文链接:https://www.haomeiwen.com/subject/eprneqtx.html