Objective-C 原型模式 -- 简单介绍和使用

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

Prototype原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。

它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。

 
说直白点就是如果有一个对象很复杂, 重新创建要花费很多的代码或者代价
这个时候可以考虑使用原型模式, 当要创建新实例时通过既有的实例复制一份,再修改不一样的地方值
 
什么时候考虑使用原型模式呢?
#1 有很多相关的类, 其行为略有不同, 而且主要差异在于内部属性, 如名称/图像等.
#2 需要使用组合(树型)对象作为其他东西的基础, 例如, 使用组合对象作为组件来构建另一个组合对象.
 
下面用代码说明如何使用
 
先创建一个Protocol
 1 #import <Foundation/Foundation.h>
 2 
 3 @protocol PrototypeCopyProtocol <NSObject>
 4 
 5 @required
 6 
 7 /**
 8  复制自己
 9 
10  @return 返回一个拷贝的对象
11  */
12 - (id)clone;
13 
14 @end

创建对象模型

Student.h

 1 #import <Foundation/Foundation.h>
 2 #import "PrototypeCopyProtocol.h"
 3 
 4 @interface Student : NSObject <PrototypeCopyProtocol>
 5 
 6 @property (nonatomic, strong) NSString *name;
 7 @property (nonatomic, strong) NSString *age;
 8 @property (nonatomic, strong) NSString *score;
 9 @property (nonatomic, strong) NSString *address;
10 
11 #pragma mark - PrototypeCopyProtocol method
12 - (id)clone;
13 
14 @end

Student.m

 1 #import "Student.h"
 2 
 3 @implementation Student
 4 
 5 - (id)clone {
 6     
 7     Student *stu = [[[self class] alloc] init];
 8     
 9     stu.name    = self.name;
10     stu.age     = self.age;
11     stu.score   = self.score;
12     stu.address = self.address;
13     
14     return stu;
15 }
16 
17 @end

下面是Controller中使用:

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     
 4     //创建第一个学生实例
 5     Student *stu1 = [[Student alloc] init];
 6     
 7     stu1.name  = @"Jackey";
 8     stu1.age   = @"18";
 9     stu1.score = @"90";
10     stu1.score = @"重庆";
11     
12     //创建第二个学生实例
13     Student *stu2 = [stu1 clone];
14     
15     stu2.name = @"Franky";
16     
17 }
原文地址:https://www.cnblogs.com/zhouxihi/p/6034154.html