设计模式系统回顾(5)原型模式

根据一个对象,创建出和原型一样的对象

1.浅克隆

public interface IPrototype {
    IPrototype clone();//克隆方法
}
public class ShallowPrototype implements IPrototype {
    private String name;

    private int age;

    private List<String> phoneList;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<String> getPhoneList() {
        return phoneList;
    }

    public void setPhoneList(List<String> phoneList) {
        this.phoneList = phoneList;
    }

    @Override
    public IPrototype clone() {
        ShallowPrototype shallowPrototype = new ShallowPrototype();
        shallowPrototype.setAge(this.age);
        shallowPrototype.setName(this.name);
      //属于引用类型,phonelist值改变两个对象的值都会改变
        shallowPrototype.setPhoneList(this.phoneList);
        return shallowPrototype;
    }
}

2.深克隆

public class DeepPrototype implements Cloneable, Serializable {
    private String name;
    private int age;
    private List<String> phoneList;
	public String getName() {
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<String> getPhoneList() {
        return phoneList;
    }

    public void setPhoneList(List<String> phoneList) {
        this.phoneList = phoneList;
    }

    public Object clone(){
        return this.deepClone();
    }

    public DeepPrototype deepClone(){
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);

            DeepPrototype clone = (DeepPrototype)ois.readObject();

            return clone;
        }catch (Exception e){
            System.out.println("深克隆异常");
            e.printStackTrace();
        }
       return null;
    }
}

使用场景:
创建一个非常复杂的对象
优点:
创建一个对象比较复杂时,使用原型对象通常效率会更高也更方便快捷
缺点
1.每个对象都需要单独实现克隆的方法。
2.深克隆和浅克隆需要灵活应用,否则可能会导致业务出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值