设计模式-原型模式

设计模式-原型模式


用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。

当我们在需要同一个类的大量对象的时候,重复使用new会消耗大量性能,这个时候使用原型模式是一个好的选择。

@Data
@AllArgsConstructor
public class Resume implements Cloneable {

    private String name;
    private int age;
    private Position position;

    @Override
    protected Resume clone() throws CloneNotSupportedException {
        Resume resume = (Resume)super.clone();
        resume.setPosition(new Position(this.position.getCompany(), this.position.getTitle()));
        return resume;
    }

    @Data
    @AllArgsConstructor
    public static class Position{
        private String company;
        private String title;
    }
}

原型模式需要目标类实现clone方法,特别注意的是深浅拷贝的问题。

需要新的实例的时候只需要调用clone方法就好了

public class CloneResume {
    public static void main(String[] args) throws Exception {
        Resume resume = new Resume("Bob", 18, new Resume.Position("APPLE", "Developer"));
        Resume resumeNew = resume.clone();
        resume.getPosition().setTitle("CTO");
        System.out.println(resume.toString());
        System.out.println(resumeNew.toString());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值