概念
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.Prototype原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
UML
解决问题
它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口. 在iOS开发中,这种模式不常用.
UML分析
Prototype抽象原型(定义clone接口方法),ConcreteProtoType1,ConcreteProtoType2对Prototype抽象原型实现,并返回自身的副本.
案例
- BaseCopyObject
#import <Foundation/Foundation.h>
@interface BaseCopyObject : NSObject<NSCopying>
// 子类不要重载
- (id)copyWithZone:(NSZone *)zone;
// 子类去实现
- (void)copyOperationWithObject:(id)object;
@end
#import "BaseCopyObject.h"
@implementation BaseCopyObject
- (id)copyWithZone:(NSZone *)zone {
BaseCopyObject *copyObject = [[self class] allocWithZone:zone];
// 赋值操作
[self copyOperationWithObject:copyObject];
return copyObject;
}
- (void)copyOperationWithObject:(id)object {
}
@end
- StudentModel
#import <Foundation/Foundation.h>
#import "BaseCopyObject.h"
@interface StudentModel : BaseCopyObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@end
#import "StudentModel.h"
@implementation StudentModel
- (void)copyOperationWithObject:(StudentModel *)object
{
object.name = self.name;
object.age = self.age;
}
@end
- ClassModel
#import "BaseCopyObject.h"
@interface ClassModel : BaseCopyObject
@property (nonatomic, copy)NSString *className;
@property (nonatomic, strong)NSArray *students;
@end
#import "ClassModel.h"
@implementation ClassModel
- (void)copyOperationWithObject:(ClassModel *)object
{
object.className = self.className;
//浅拷贝
object.students = self.students;
//深拷贝
//object.students = [[NSArray alloc] initWithArray:self.students copyItems:YES];
}
@end
- ViewController
#import "ViewController.h"
#import "StudentModel.h"
#import "ClassModel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
StudentModel *stu1 = [StudentModel new];
stu1.name = @"张三";
StudentModel *stu2 = stu1.copy;
// classModel
ClassModel *class1 = [[ClassModel alloc] init];
class1.className = @"ban ji 1";
class1.students = @[stu1, stu2];
ClassModel *class2 = class1.copy;
NSLog(@"class1:%@----------class2:%@",class1,class2);
NSLog(@"class1.students:%@----------class2.students:%@",class1.students,class2.students);
}
@end
浅拷贝
深拷贝
浅拷贝&深拷贝区别
深拷贝就是内容拷贝,浅拷贝就是指针拷贝。
深拷贝就是拷贝出和原来仅仅是值一样,但是内存地址完全不一样的新的对象,创建后和原对象没有任何关系。浅拷贝就是拷贝指向原来对象的指针,使原对象的引用计数+1,可以理解为创建了一个指向原对象的新指针而已,并没有创建一个全新的对象.
Demo
网友评论