iOS设计模式之原型模式

What is the 原型模式?

原型设计模式是通过一个原型拷贝的方式快速创建一个新的对象。

拷贝分为两种:

  1. 浅拷贝(同一个地址,不同的指针)

  2. 深拷贝(不同的地址,完全的独立)

二者区别在于是否生成新的一个地址

这里写图片描述


这里写图片描述

When using the 原型模型?

  • 需要创建的对象应独立于其类型与创建方式。

  • 要实例化的类是在运行时决定的。

  • 不想要与产品层次相对应的工厂层次。

  • 不同类的实例间的差异仅仅是状态的若干组合。因此复制相应数量的原型比手工实例化更加方便。

  • 类不容易创建,比如每个组件可把其他组件作为子节点的组合对象。复制已有的组合对象并对副本进行修改会更加容易。

Example:

#import <Foundation/Foundation.h>

@interface MyClass : NSObject<NSCopying>

@end
#import "MyClass.h"

@implementation MyClass
-(id)copyWithZone:(NSZone *)zone{
    NSLog(@"调用copy方法");
    MyClass *myclass=[[[self class]allocWithZone:zone]init];
    return myclass;
}

@end
#import <Foundation/Foundation.h>
#import "MyClass.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
       NSString *string=@"dddd";
        NSString *stringCopy=[string copy];
        NSMutableString *stringMCopy=[string mutableCopy];
        NSLog(@"%p,%p,%p",string,stringCopy,stringMCopy);
        MyClass *class1=[[MyClass alloc]init];

        MyClass *class2=[class1 copy];
        MyClass *class3=class2;
        NSLog(@"class1:%p,class2:%p,class3:%p",class1,class2,class3);
}
    return 0;
}
2016-04-24 20:07:01.445 Copy[4184:193787] string:0x100001060,stringCopy:0x100001060,stringMCopy:0x100203930
2016-04-24 20:07:01.446 Copy[4184:193787] 调用copy方法
2016-04-24 20:07:01.446 Copy[4184:193787] class1:0x100303a80,class2:0x100305ba0,class3:0x100305ba0
Program ended with exit code: 0
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值