Uml图:
//抽象原型
public interface Prototype {
public Object cloneMe() throws CloneNotSupportedException;
}
//具体原型:
public class Cubic implements Prototype,Cloneable {
double length,width,height;
public Cubic(double a,double b,double c) {
length=a;
width=b;
height=c;
}
@Override
public Object cloneMe() throws CloneNotSupportedException {
Cubic object=(Cubic) clone();//调用从Object类继承的clone()方法;
return object;
}
}
import java.io.*;
public class Goat implements Prototype, Serializable {
StringBuffer color;
public StringBuffer getColor() {
return color;
}
public void setColor(StringBuffer color) {
this.color = color;
}
@Override
public Object cloneMe() throws CloneNotSupportedException {
Object object = null;
try {
ByteArrayOutputStream outOne = new ByteArrayOutputStream();
ObjectOutputStream outTwo = new ObjectOutputStream(outOne);
outTwo.writeObject(this);// 将原型吸入对象输出流
ByteArrayInputStream inOne = new ByteArrayInputStream(outOne
.toByteArray());
ObjectInputStream inTwo = new ObjectInputStream(inOne);
object = inTwo.readObject();// 创建新对象:原型复制品
} catch (Exception e) {
System.out.println(e);
}
return object;
}
}
//模式使用:
public class Application {
public static void main(String[] args) {
Cubic cubic = new Cubic(12, 20, 66);
System.out.println("cubic的长、宽和高:");
System.out.println(cubic.length + "," + cubic.width + ","
+ cubic.height);
try {
Cubic cubicopy = (Cubic) cubic.cloneMe();
System.out.println("cubicopy的长、宽和高:");
System.out.println(cubicopy.length + "," + cubicopy.width + ","
+ cubicopy.height);
} catch (Exception e) {
}
Goat goat = new Goat();
goat.setColor(new StringBuffer("白色的山羊"));
System.out.println("goat 是" + goat.getColor());
try {
Goat goatCopyGoat = (Goat) goat.cloneMe();
System.out.println("goatCopy是" + goatCopyGoat.getColor());
System.out.println("goatCopy将自己的颜色改变成黑色");
goatCopyGoat.setColor(new StringBuffer("黑色的山羊"));
System.out.println("goat仍然是" + goat.getColor());
System.out.println("goatCopy是" + goatCopyGoat.getColor());
} catch (Exception e) {
// TODO: handle exception
}
}
}