原型介面:
package prototype;public interface Prototype {public Object cloneMe() throws CloneNotSupportedException;}
淺拷貝實現:
package prototype;//立方體public class Cubic implements Prototype,Cloneable{double length,width,height;Cubic(double length, double width, double height) {this.length = length;this.width = width;this.height = height;}//以淺拷貝的方式實現(Object類中的clone是淺拷貝)@Overridepublic Object cloneMe() throws CloneNotSupportedException {Cubic object=(Cubic)clone();//Object的clone()方法return object;}}
深拷貝實現:
package prototype;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;//山羊public class Goat implements Prototype,Serializable {StringBuffer color;public StringBuffer getColor() {return color;}public void setColor(StringBuffer color) {this.color = color;}//以深度拷貝方式實現@Overridepublic 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 (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}return object;}}
測試:
package prototype;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 cubicCopy=(Cubic) cubic.cloneMe();System.out.println("cubicCopy 的長 、寬、高:");System.out.println(cubicCopy.length+","+cubicCopy.width+","+cubicCopy.height);} catch (CloneNotSupportedException e) {e.printStackTrace();}Goat goat=new Goat();goat.setColor(new StringBuffer("白顏色的山羊"));System.out.println("goat是"+goat.getColor());try {Goat goatCopy=(Goat) goat.cloneMe();System.out.println("goatCopy是"+goatCopy.getColor());System.out.println("顏色變為黑色");goatCopy.setColor(new StringBuffer("黑顏色的山羊"));System.out.println("goat是"+goat.getColor());System.out.println("goatCopy是"+goatCopy.getColor());} catch (CloneNotSupportedException e) {e.printStackTrace();}}}