原型模式(Prototype)
是指使用原型实例指定创建对象的种类,并通过复制(cloning)这个原型创建新的对象。也就是提供一个快速复制对象的快捷方式。
当然这里的复制指的是深复制,复制的是对象。
OCdemo
@protocol ProtocolType <NSObject>
- (id)clone;
@end
@interface PrototypeModel : NSObject<NSCopying,ProtocolType>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSUInteger age;
-(void)display;
@end
********************************
@implementation PrototypeModel
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
PrototypeModel * p = [[[self class] alloc]init];
p.name = self.name;
p.age = self.age;
return p;
}
- (id)clone {
return [self copy];
}
-(void)display
{
NSLog(@"姓名:%@",_name);
NSLog(@"年纪:%lu",(unsigned long)_age);
}
@end
********************************
//非原型创建,创建的过程是一个耗费cpu的过程 想象一下 足够大的数据量下都进行创建 系统性能会如何呢?而且如果对变量设置 基本上都是一样代码 造成代码冗余。
PrototypeModel * p = [[PrototypeModel alloc]init];
p.name = @"name1";
p.age = 1;
[p display];
PrototypeModel * p1 = [[PrototypeModel alloc]init];
p1.name = @"name1";
p1.age = 1;
[p1 display];
//原型模式
PrototypeModel * p00 =[[PrototypeModel alloc]init];
p00.name = @"name1";
p00.age = 1;
[p00 display];
PrototypeModel * p01= [p00 clone];
[p01 display];
########
swiftDemo
//简单拷贝
设计模式我们在代码中经常会用到,那就是NSCopying协议
protocol SProtocolType {
static func clone() ->SProtocolType
}
class SPrototypeModel: NSObject,SProtocolType,NSCopying {
var name = ""
func clone() -> SProtocolType {
let p = SPrototypeModel()
p.name = name;
return p
}
func disPlay() {
print("name: \(name)")
}
}
//登记拷贝 实际上就是在简单拷贝的基础之上对这些clone对象进行管理
class CloneManager: NSObject {
static let sharedManager = CloneManager()
private var mapper: [String: Cloning] = [String: Cloning]()
private override init() {
super.init()
}
func store(prototype: Cloning, for identifier: String) {
mapper[identifier] = prototype
}
func prototype(for identifier: String) -> Cloning? {
return mapper[identifier]
}
func remove(with identifier: String) {
mapper[identifier] = nil
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
let clone = author.clone()
CloneManager.sharedManager.store(clone, "CloneInstance")
let storedClone = CloneManager.sharedManager.prototype(for: "CloneInstance")
if clone == storedClone {
print("Store success")
}
if clone != author {
print("You create a copy instance of author")
}
CloneManager.sharedManager.remove(with: "CloneInstance")
assert( CloneManager.sharedManager.prototype(for: "CloneInstance") == nil )
}
}
网友评论