学习文章
原理图
说明
- 原型模式指的是从一个已有的对象复制并创建出新的对象
- 当一个类的实例之间存在差异,而这些差异仅是状态的若干组合,复制原型要比手工实例化更加方便
- 当一个类并不容易创建(比如有着复杂的组合对象),且复制已有的组合对象要比对副本修改更加容易,此时,可以考虑使用原型模式
源码
实现复制的过程中,要考虑到变量是值类型,还是关系类型,才能准确复制.
对象要实现NSCopying协议,或者自己实现类似的复制协议(为了实现纯净的swift代码,而不是继承NSObject,就需要自己实现类似NSCopying的结构)
BaseCopyObject.swift
import UIKit
class BaseCopyObject: NSObject, NSCopying {
required override init() {
}
/**
实现NSCopying协议
- parameter zone: zone description
- returns: 新复制的对象
*/
final func copyWithZone(zone : NSZone) -> AnyObject {
// dynamicType用以获取动态类型
let copy = self.dynamicType.init()
self.parametersCopyOperationWithBaseCopyObject(copy)
return copy
}
/**
参数复制操作,由子类重写
- parameter object: 克隆体
*/
func parametersCopyOperationWithBaseCopyObject(object : BaseCopyObject) {
}
}
Person.swift
import UIKit
class Person: BaseCopyObject {
var personname : String?
var age : String?
var dataArray : [AnyObject]?
var infoDic : [String : AnyObject]?
override func parametersCopyOperationWithBaseCopyObject(object: BaseCopyObject) {
let personObject = object as! Person
personObject.personname = self.personname
personObject.age = self.age
personObject.dataArray = self.dataArray
personObject.infoDic = self.infoDic
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let personOne = Person()
personOne.personname = "FrankLiu"
personOne.age = "26"
personOne.dataArray = ["1","2"]
personOne.infoDic = ["key1" : "value1","key2" : "value2"]
print("person = \(personOne), name = \(personOne.personname),age = \(personOne.age),dataArray = \(personOne.dataArray),infoDic = \(personOne.infoDic)")
let personTwo = personOne.copy()
personOne.personname = "HaHa"
personOne.age = "28"
personOne.dataArray = ["3","4"]
personOne.infoDic = ["key3" : "value3","key4" : "value4"]
print(personTwo,personTwo.personname,personTwo.age,personTwo.dataArray,personTwo.infoDic)
print("person = \(personOne), name = \(personOne.personname),age = \(personOne.age),dataArray = \(personOne.dataArray),infoDic = \(personOne.infoDic)")
}
}
输出
person = <PrototypePattern.Person: 0x7ffb31736a10>, name = Optional("FrankLiu"),age = Optional("26"),dataArray = Optional([1, 2]),infoDic = Optional(["key1": value1, "key2": value2])
<PrototypePattern.Person: 0x7ffb31738ae0> Optional("FrankLiu") Optional("26") Optional([1, 2]) Optional(["key1": value1, "key2": value2])
person = <PrototypePattern.Person: 0x7ffb31736a10>, name = Optional("HaHa"),age = Optional("28"),dataArray = Optional([3, 4]),infoDic = Optional(["key4": value4, "key3": value3]