設計模式之原型模式
阿新 • • 發佈:2020-08-06
第一種克隆模式(淺克隆)
/** * @作者 five-five * @建立時間 2020/8/6 */ public class Demo01 implements Cloneable{ private int id=0; private String student="123132"; public void setId(int id) { this.id = id; } public void setStudent(String student) { this.student = student; }public int getId() { return id; } public String getStudent() { return student; } @Override protected Object clone() throws CloneNotSupportedException { //都是基本型別直接使用預設的clone方法即可 return super.clone(); } }
2.深克隆模式
import java.io.*; /** * @作者 five-five * @建立時間 2020/8/6*/ public class Demo02 implements Serializable, Cloneable { private int id=11; private String name="1231321"; private Demo01 demo01=new Demo01(); public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public voidsetDemo01(Demo01 demo01) { this.demo01 = demo01; } public int getId() { return id; } public String getName() { return name; } public Demo01 getDemo01() { return demo01; } @Override protected Object clone() throws CloneNotSupportedException { //第一種方式(比較死板) Object obj = null; obj = super.clone(); Demo02 demo02 = (Demo02) obj; //對引用型別的單獨處理 demo02.demo01 = (Demo01) demo01.clone(); return obj; } /** * <p>使用IO的方式克隆</p> * * @return */ public Object deepProtoCloneByIO() { //建立流物件 ByteArrayInputStream bis = null; ByteArrayOutputStream bos = null; ObjectInputStream ois = null; ObjectOutputStream oos = null; try { //序列化 bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(this);//當前這個物件以物件流的方式輸出 //反序列化 bis = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bis); Demo02 o = (Demo02) ois.readObject(); return o; } catch (Exception e) { e.printStackTrace(); } return null; } }
測試程式碼:
/** * @作者 five-five * @建立時間 2020/8/6 */ public class Client { public static void main(String[] args) throws Exception { Demo01 demo01=new Demo01(); Demo02 demo02=new Demo02(); Object clone = demo01.clone(); Demo02 clone1 = (Demo02)demo02.clone(); System.out.println(demo01.hashCode()); System.out.println(demo02.hashCode()); System.out.println(demo02.getDemo01().hashCode()); System.out.println(clone.hashCode()); System.out.println(clone1.getDemo01().hashCode()); } }
測試結果如圖: