原型模式

场景

通过new产生一个对象时需要非常繁琐的数据准备或访问权限,则可以使用原型模式。

效果

原型模式就是java中的克隆技术。克隆类似于new,但是又不同于new,new创建的对象属性采用的是默认值。克隆出的对象的属性值完全和原型对象相同,并且克隆出来的新对象的改变不会影响到原型对象。

浅克隆

package com.amberweather.prototype;

import java.util.Date;

/**
 * 一个java bean
 * 
 * @author Administrator
 *
 */
public class Sheep implements Cloneable {
    private String name;
    private Date birthday;
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object obj = super.clone();     //直接调用Object的clone方法
        return obj;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public Sheep(String name, Date birthday) {
        super();
        this.name = name;
        this.birthday = birthday;
    }

}
package com.amberweather.prototype;
/**
 * 测试原型模式
 * 潜克隆
 * 
 */
import java.util.Date;

public class Client {
    public static void main(String[] args) throws Exception{
        Sheep s1 = new Sheep("small sheep",new Date(12121212121L));
        System.out.println(s1);
        System.out.println(s1.getName());
        System.out.println(s1.getBirthday());
        
        System.out.println();
        
        Sheep s2 = (Sheep) s1.clone();
        System.out.println(s2);
        System.out.println(s2.getName());
        System.out.println(s2.getBirthday());
    }
}
原型模式_第1张图片
image.png

深克隆

package com.amberweather.prototype;

import java.util.Date;

/**
 * 一个java bean
 * 
 * @author Administrator
 *
 */
public class Sheep implements Cloneable {
    private String name;
    private Date birthday;
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object obj = super.clone();     //直接调用Object的clone方法
                s.birthday = this.birthday.clone()
        return obj;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public Sheep(String name, Date birthday) {
        super();
        this.name = name;
        this.birthday = birthday;
    }

}

注:深克隆也可以在浅克隆的基础上通过序列化来实现

你可能感兴趣的:(原型模式)