构造型模式之Prototype(原型)模式

1.如果你期望根据给定的例子创建一个对象,可使用Prototype(原型)模式
2.区分Shallow Clone&Deep Clone
Shallow Clone: 对基本类型的成员变量进行值的复制,对引用类型的成员变量只复制引用,不复制引用的对象.
Deep Clone: 对基本类型的成员变量进行值的复制,对引用类型的成员变量也进行引用对象的复制.
参考:http://blog.csdn.net/shootyou/article/details/3945221
3.举例

//第一个原型类:clone()方法包括了Shallow Clone与Deep Clone的实现
public class FirstPrototype implements Cloneable{
    private String name;
    private SecondPrototype secondPrototype;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public SecondPrototype getSecondPrototype() {
        return secondPrototype;
    }
    public void setSecondPrototype(SecondPrototype secondPrototype) {
        this.secondPrototype = secondPrototype;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        //Shallow Clone
        //return super.clone();
        //Deep Clone
        FirstPrototype clone = (FirstPrototype) super.clone();
        clone.setSecondPrototype((SecondPrototype) secondPrototype.clone());
        return clone;
    }

}
//第二个原型类:该类没有引用类型的成员变量
public class SecondPrototype implements Cloneable{
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }
}
//测试类
public class Test {
    public static void main(String[] args){
        SecondPrototype sp0 = new SecondPrototype();
        sp0.setAge(0);
        FirstPrototype fp0 = new FirstPrototype();
        fp0.setName("fp0");
        fp0.setSecondPrototype(sp0);

        System.out.println(fp0.getName());
        System.out.println(fp0.getSecondPrototype().getAge());

        try {
            FirstPrototype fp1 = (FirstPrototype) fp0.clone();
            fp1.setName("fp1");
            fp1.getSecondPrototype().setAge(1);
            System.out.println("clone: " + fp1.getName());
            System.out.println("clone: " + fp1.getSecondPrototype().getAge());
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(fp0.getName());
        System.out.println(fp0.getSecondPrototype().getAge());

    }
}
//Shallow Clone结果
fp0
0
clone: fp1
clone: 1
fp0
1
//Deep Clone结果
fp0
0
clone: fp1
clone: 1
fp0
0

4.总结:Prototype(原型)模式不通过实例化类来创建一个新的未初始化的实例,而是通过复制一个现有对象来生成新的对象。该模式要注意Shallow Clone与Deep Clone的区别,否则会造成原来实例化对象数据被修改而造成逻辑错误。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值