iOS设计模式--原型模式

一:原理实质
1 原型模式 :用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
2 原型模式实质:其实就是从一个对象在创建另外一个可定制的对象,而且不需要知道任何创建的细节。
二 copy 与mutableCopy的实质
浅拷贝:直接复制数组指针

具体代码:

Animal.h

//
//  Animal.h
//  原型模式demo
//
//  Created by Apple on 16/3/8.
//  Copyright © 2016年 liuYuGang. All rights reserved.
//

#import 

@interface Animal : NSObject
@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 
#import "Animal.h"

int main(int argc, const char * argv[]) {
    NSMutableString *n = [NSMutableString stringWithFormat:@"

你可能感兴趣的:(iOS设计模式--原型模式)