設計模式prototype(原型模式)

來源:互聯網
上載者:User

原型介面:

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();}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.