原型模式(prototype)

创建型模式

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

1、通过反射去实现。

2、循环赋值。

3、通过克隆去实现。

.........

克隆实现方法(类似与孙悟空吹毫毛):

类图:

代码:

1、孙悟空是只猴子:Monkey.java

public class Monkey {

    protected int height;

    protected int weight;

    protected Date birthday;

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

2、孙悟空的金箍棒:JinGuBan.java

public class JinGuBan implements Serializable {
    private float h= 100;
    private float w = 10;

    public void big(){
        this.h *=2;
        this.w *=2;
    }

    public void  small(){
        this.h /=2;
        this.w /=2;
    }
}

3、齐天大圣继承猴子类,并实现Cloneable和Serializable接口:QiTianDaSheng.java

public class QiTianDaSheng extends Monkey implements Cloneable,Serializable {

    public JinGuBan jinGuBan;

    public QiTianDaSheng(){
        this.birthday = new Date();
        this.jinGuBan = new JinGuBan();
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return this.deepClone();
    }

    private Object 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);

            QiTianDaSheng clone =   (QiTianDaSheng)ois.readObject();
            clone.setBirthday(new Date());
            return clone;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

测试:

public class App 
{
    public static void main(String[] args) {
        QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();

        try {
            QiTianDaSheng clone = (QiTianDaSheng)qiTianDaSheng.clone();
            //复制出新的悟空
            System.out.println(qiTianDaSheng ==clone );
            //j金箍棒也是新的
            System.out.println(qiTianDaSheng.jinGuBan==clone.jinGuBan);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

 输出:

false
false

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值