iOS设计模式--原型模式
2016-03-08 20:53
429 查看
一:原理实质
1 原型模式 :用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
2 原型模式实质:其实就是从一个对象在创建另外一个可定制的对象,而且不需要知道任何创建的细节。
二 copy 与mutableCopy的实质
浅拷贝:直接复制数组指针
具体代码:
Animal.h
Animal.m
main.m
运行结果:
代码下载地址:http://pan.baidu.com/s/1dDRmypr
1 原型模式 :用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
2 原型模式实质:其实就是从一个对象在创建另外一个可定制的对象,而且不需要知道任何创建的细节。
二 copy 与mutableCopy的实质
浅拷贝:直接复制数组指针
具体代码:
Animal.h
// // Animal.h // 原型模式demo // // Created by Apple on 16/3/8. // Copyright © 2016年 liuYuGang. All rights reserved. // #import <Foundation/Foundation.h> @interface Animal : NSObject<NSCopying,NSMutableCopying> @property(nonatomic,copy)NSMutableString *name; @property (nonatomic,copy)NSString *desciption; @property (nonatomic,assign)CGFloat weight; -(instancetype)initWithName:(NSMutableString *)name desciption:(NSString *)des weight:(CGFloat) weight; @end
Animal.m
// // Animal.m // 原型模式demo // // Created by Apple on 16/3/8. // Copyright © 2016年 liuYuGang. All rights reserved. // #import "Animal.h" @implementation Animal -(instancetype)initWithName:(NSMutableString *)name desciption:(NSString *)des weight:(CGFloat) weight{ if (self = [super init]) { self.name = name; self.desciption =des; self.weight = weight; } return self; } -(id)copyWithZone:(NSZone *)zone{ Animal *animal = [[self class]allocWithZone:zone]; animal.name = [self.name mutableCopy]; animal.desciption = [self.desciption copy]; animal.weight = self.weight; return animal; } -(id)mutableCopyWithZone:(NSZone *)zone{ Animal *animal = [[self class]allocWithZone:zone]; animal.name = [self.name mutableCopy]; animal.desciption = [self.desciption copy]; animal.weight = self.weight; return animal; } @end
main.m
// // main.m // 原型模式demo // // Created by Apple on 16/3/8. // Copyright © 2016年 liuYuGang. All rights reserved. // #import <Foundation/Foundation.h> #import "Animal.h" int main(int argc, const char * argv[]) { NSMutableString *n = [NSMutableString stringWithFormat:@"��"]; Animal *animl = [[Animal alloc]initWithName:n desciption:@"这是一只猫" weight:12.0]; Animal *animal1 = [animl copy]; NSLog(@"name=%@",animal1.name); Animal *animal2 = [animl mutableCopy]; NSLog(@"descirption=%@",animal2.desciption); return 0; }
运行结果:
代码下载地址:http://pan.baidu.com/s/1dDRmypr
相关文章推荐
- iOS多线程之线程状态
- iOS进阶——沙盒及沙盒路径、简单文件的写入
- cordova for ios: Unable to simultaneously satisfy constraints.
- iOS7.0 iphone5边界黑框的问题
- 关于 iOS屏幕像素小数位显示偏差
- IOS开发中用到的三方库冲突的解决办法
- ios 属性与成员变量的区别
- ios 真机调试时出现CopyPngFile error解决方法
- iOS数据持久化存储
- AMD R9 280x tri-x vapor-x OC 刷新BIOS来节能降温
- iOS9项目打包上线
- iOS开发高价集成支付宝
- 支付宝集成
- IOS开发调用系统相机和打开闪光灯
- iOS开发之AFNetworking3.0.4的使用
- iOS缓存使用的框架
- iOS开发之BLOCK应用
- iOS 日期的表示
- iOS 设计模式之工厂模式
- iOS crash符号表还原