美文网首页
原型模式

原型模式

作者: 麋晓鹿 | 来源:发表于2018-04-11 01:07 被阅读9次

    定义

    通过复制来创建新的对象,就叫做原型模式。

    使用情况

    1.类之间差异小,个别属性的不同
    2.要实例化的类是在运行时决定的

    实现

    浅复制,深复制
    浅复制,只复制指针,指针指向的内存地址一样
    深复制,复制指针和指针指向的对象

    自定义对象想要实现复制,需要实现NSCopying协议及方法

    - (id)copyWithZone:(nullable NSZone *)zone
    

    创建Student对象,并实现NSCoping协议

    @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
    
    

    实现拷贝的方法

    - (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;
    }
    

    调用

        Student *stu = [[Student alloc] init];
        stu.name = @"张三";
        stu.age = 12;
        stu.phone = @"21123123";
        stu.address = @"北京";
    
        Student *stu2 = [stu copy];
    
    

    相关文章

      网友评论

          本文标题:原型模式

          本文链接:https://www.haomeiwen.com/subject/tciohftx.html