设计模式(六)Prototype Pattern 原型模式

通过new产生一个对象非常繁琐,可以使用原型模式

原型模式实现:

——Cloneable接口和clone方法

——Prototype模式实现起来最困难的地方是实现内存的复制和操作,Java中提供了clone方法省了大部分事情

案例:多利羊的克隆

package com.littlepage.PrototypePattern;

public class Sheep implements Cloneable{
    String name;
    int date;
    public Sheep(String name, int date) {
        super();
        this.name = name;
        this.date = date;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object obj=super.clone();
        return obj;
    }
    
}

1.继承Cloneable接口

2.重写clone方法

测试,不同只羊,相同属性

浅克隆

package com.littlepage.PrototypePattern;

public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep s=new Sheep("molly",2019);
        Sheep ss=(Sheep)s.clone();
        System.out.println(s);
        System.out.println(ss);
    }
}

 

浅拷贝和深拷贝

浅拷贝,只拷贝一层,不会把对象中引用的对象进行拷贝

深拷贝,拷贝深层

初学java的时候应该学过,这里不提太多

 

深克隆

package com.littlepage.PrototypePattern;

import java.util.Date;

public class Sheep implements Cloneable{
    String name;
    Date date;
    public Sheep(String name, Date date) {
        super();
        this.name = name;
        this.date = date;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object obj=super.clone();
        Sheep s=(Sheep)obj;
        s.date=(Date)this.date.clone();
        return obj;
    }
    
}

 

posted @ 2018-12-05 02:14  SteveYu  阅读(195)  评论(0编辑  收藏  举报