装饰模式

作者: 架构师的一小步 | 来源:发表于2019-03-24 17:33 被阅读0次
装饰模式-定义

动态地给一个对象添加一些额外的职责

装饰模式-场景

需要透明且动态地扩展类的功能时

装饰模式-角色划分

\color{red}{4个核心角色}
角色一:抽象组件
角色二:具体组件
角色三:抽象装饰者
角色四:具体装饰者

装饰模式-案例分析

Decorator
案例:妹子手机壳?iPhoneX->9688
角色一:抽象组件->MobilePhone(手机)

//
//  MobilePhone.swift
//  Dream_20180727_Decorator
//
//  Created by Dream on 2018/7/27.
//  Copyright © 2018年 Tz. All rights reserved.
//

import Foundation
protocol MobilePhone {
    func shell()
}

角色二:具体组件->iPhoneX


//
//  IPhoneX.swift
//  Dream_20180727_Decorator
//
//  Created by Dream on 2018/7/27.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//具体组件->苹果手机
class IPhoneX: MobilePhone {

    func shell() {
        print("苹果手机")
    }
    
}

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

//
//  MobilePhoneShell.swift
//  Dream_20180727_Decorator
//
//  Created by Dream on 2018/7/27.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//抽象装饰者
//特点一:继承(实现)抽象组件
//特点二:持有抽象组件引用
class MobilePhoneShell: MobilePhone {

    private var mobile:MobilePhone
    
    init(mobile:MobilePhone) {
        self.mobile = mobile
    }
    
    func shell() {
        self.mobile.shell()
    }
    
}

角色四:具体装饰者

//
//  GoodShell.swift
//  Dream_20180727_Decorator
//
//  Created by Dream on 2018/7/27.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//具体装饰者->好的手机壳
class GoodShell: MobilePhoneShell {
    
    override init(mobile: MobilePhone) {
        super.init(mobile: mobile)
    }

    func wearproof(){
        print("耐磨功能")
    }
    
    func waterproof(){
        print("防水功能")
    }
    
    func dustproof(){
        print("防尘功能");
    }
    
}

质量好的手机壳:耐磨、防水、防尘…(300)
耐磨:wearproof()
防水:waterproof()
防尘:dustproof()

GoodShell
质量差的手机壳:耐磨(50)
耐磨:wearproof()

//
//  PoorShell.swift
//  Dream_20180727_Decorator
//
//  Created by Dream on 2018/7/27.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

//具体装饰者->好的手机壳
class PoorShell: MobilePhoneShell {
    
    override init(mobile: MobilePhone) {
        super.init(mobile: mobile)
    }

    func wearproof(){
        print("耐磨功能")
    }
    
}

调用

//
//  ViewController.swift
//  Dream_20180727_Decorator
//
//  Created by Dream on 2018/7/27.
//  Copyright © 2018年 Tz. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        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()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

相关文章

网友评论

    本文标题:装饰模式

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