创建型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
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