定義
通過復(fù)制來創(chuàng)建新的對象,就叫做原型模式。
使用情況
1.類之間差異小,個別屬性的不同
2.要實(shí)例化的類是在運(yùn)行時決定的
實(shí)現(xiàn)
淺復(fù)制,深復(fù)制
淺復(fù)制,只復(fù)制指針,指針指向的內(nèi)存地址一樣
深復(fù)制,復(fù)制指針和指針指向的對象
自定義對象想要實(shí)現(xiàn)復(fù)制,需要實(shí)現(xiàn)NSCopying協(xié)議及方法
- (id)copyWithZone:(nullable NSZone *)zone
創(chuàng)建Student對象,并實(shí)現(xiàn)NSCoping協(xié)議
@interface Student : NSObject <NSCopying>
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) int age;
@property (copy, nonatomic) NSString *phone;
@property (copy, nonatomic) NSString *address;
@end
實(shí)現(xiàn)拷貝的方法
- (id)copyWithZone:(nullable NSZone *)zone{
Student *stu = [[Student class] allocWithZone:zone];
stu.name = self.name;
stu.age = self.age;
stu.phone = self.phone;
stu.address = self.address;
return stu;
}
調(diào)用
Student *stu = [[Student alloc] init];
stu.name = @"張三";
stu.age = 12;
stu.phone = @"21123123";
stu.address = @"北京";
Student *stu2 = [stu copy];