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.