码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-11-05 23:25:48      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:修改   比较   add   require   种类   复制   atom   interface   细节   

先借鉴百科对原型模式的介绍:

定义:

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

解决什么问题:

它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。
 
说直白点就是如果有一个对象很复杂, 重新创建要花费很多的代码或者代价
这个时候可以考虑使用原型模式, 当要创建新实例时通过既有的实例复制一份,再修改不一样的地方值
 
下面用代码说明如何使用
 
先创建一个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 }

 

 

 

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

标签:修改   比较   add   require   种类   复制   atom   interface   细节   

原文地址:http://www.cnblogs.com/zhouxihi/p/6034154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!