iOS设计模式--原型模式

一:原理实质
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

你可能感兴趣的:(设计模式)