原型模式 Prototype Pattern
1.『深複製』VS『淺複製』
深複製:若物件中有的屬性為其他物件的參考,則會複製一個新的物件
淺複製:若物件中有的屬性為其他物件的參考,則複製時該屬性會指向原物件的同個參考
2.原型模式的實現
Swift中實現NSCopying即為原型模式,需實現當中的copy()
方法
class BusinessCard:NSCopying{//實現Swift NSCopying介面
init(name:String,age:String,company:Company) {
self.name = name
self.age = age
self.company = company
}
var name:String
var age:String
var company:Company
func printDetails() {
print("公司 \(company.companyName) 公司地址 \(company.location) 姓名 \(name) 年齡 \(age) ")
}
//實現prototype原型模式的copy方法
func copy(with zone: NSZone? = nil) -> Any {
return BusinessCard(name: self.name, age: self.age, company: self.company.copy() as! Company)
}
}
class Company:NSCopying{
init(companyName:String,location:String) {
self.companyName = companyName
self.location = location
}
var companyName:String
var location:String
func copy(with zone: NSZone? = nil) -> Any {
return Company(companyName: self.companyName,location: self.location)
}
}
var businessCard1 = BusinessCard(name: "allen", age: "27", company: Company(companyName: "雄獅", location: "內湖"))
businessCard1.printDetails()
var businessCard2 = businessCard1.copy() as! BusinessCard
businessCard2.printDetails()
//變更複製內容
businessCard2.age = "8"
businessCard2.company = Company(companyName: "CMoney", location: "新埔")
businessCard2.printDetails()
執行結果
3.參考資料
Prototype Pattern (原型模式) in Swift (Reference type vs. Value type) 的不同