通过new产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式。
-就是java中的克隆技术,以某个对象为原型,复制出新的对象。显然,新的对象具备原型对象的特点 -优势有:效率高(直接克隆,避免了重新执行构造过程步骤)。
-克隆类似于new ,但是不同于new。new创建新的对象属性采用的是默认值。克隆出的 对象的属性值完全和原型对象相同。并且克隆出的新对象改变不会影响原型对象。然后, 再修改克隆对象的值。
实现
- Cloneable接口和clone方法
/**
* 原型模式
*/
public class Sheep implements Cloneable{
private String sname;
private Date birthday;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Sheep() {
}
public Sheep(String sname, Date birthday) {
this.sname = sname;
this.birthday = birthday;
}
}
//---------------------------
public class PrototypePatternTest {
public static void prototypePatternTest01() {
System.out.println("----------------------------原型模式演示开始------------------------------------");
System.out.println("--------------------创建一个原型------------------------");
Sheep sheep1 = new Sheep("原型",new Date());
System.out.println(sheep1);
System.out.println(sheep1.getBirthday());
System.out.println( sheep1.getSname());
System.out.println("--------------------拷贝这个原型------------------------");
Sheep sheep2 = null;
try {
sheep2 = (Sheep) sheep1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println("--------------------打印------------------------");
System.out.println(sheep2);
System.out.println(sheep2.getBirthday());
System.out.println( sheep2.getSname());
System.out.println("----------------------------原型模式演示结束------------------------------------");
}
}