设计模式之原型模式 Prototype Mode:Swift 实现

Prototype 原型模式

When we want to clone the instance itself, it may create some dependencies between the client and the original class, it will make the code be more complex. So we use “prototype” to compound the clone operation into the original class itself. And the clone operation will be easily.

当我们想要完全复制一个对象它本身时,很可能会在调用者和源类之间产生一些复杂当耦合关系。所以我们使用“原型”模式,将对象克隆操作整合在对象当源类之中。这样一来,克隆操作由特定的类自身决定,调用变得简洁。

在这里插入图片描述

// Prototype
protocol StorePrototype{
    func clone() -> Store
}

// Concrete Prototype
class Store: StorePrototype {
    var area: [Int] = [0, 0]
    init(store: StorePrototype) {
        if let s = store as? Store {
            self.area = s.area
        }
    }
    init() {}
    func clone() -> Store {
        return Store(store: self)
    }
}

// Sub Concrete Prototype
class BookStore: Store {
    var bookSelfCount = 0
    init(bookStore: StorePrototype) {
        super.init(store: bookStore)
        if let s = bookStore as? BookStore {
            self.bookSelfCount = s.bookSelfCount
        }
    }
    override init() {
        super.init()
    }
    override func clone() -> Store {
        return BookStore(bookStore: self)
    }
    
}

// Sub Concrete Prototype
class FlowerStore: Store {
    var flowers = ["Sun Flower", "Rose", "Lily"]
    init(flowerStore: StorePrototype) {
        super.init(store: flowerStore)
        if let s = flowerStore as? FlowerStore {
            self.flowers = s.flowers
        }
    }
    override init() {
        super.init()
    }
    override func clone() -> Store {
        return FlowerStore(flowerStore: self)
    }
}

let store = Store()
let obj = FlowerStore()

let copyStore = store.clone()
let copyObj = obj.clone()        
// Now it did the deep copy. It copy the whole instance "store" to "copyStore", and copy the whole instace "obj" to copyObj.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值