一.什麼是原型模式
原型模式就是從從一個對象創建再另外一個可定製對象,並且不需要知道創建的細節
二.原型模式怎麼寫
1.我們先來看看原型模式的UMLl類圖
2.我們根據類圖來寫一寫原型模式
public abstract class Prototype {
public String name;
public abstract void setName(String name);
public abstract String getName();
public abstract Prototype clonePro();
}
public class ConcretePrototype extends Prototype {
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public ConcretePrototype clonePro() {
ConcretePrototype concretePrototype=new ConcretePrototype();
concretePrototype.setName(this.name);
return concretePrototype;
}
}
客戶端調用
public class Client {
public static void main(String[] args) {
Prototype prototype=new ConcretePrototype();
prototype.setName("小明");
System.out.println("對象:"+prototype+"對象屬性:"+prototype.getName());
Prototype clonePrototype=prototype.clonePro();
System.out.println("對象:"+clonePrototype+"對象屬性:"+clonePrototype.getName());
}
}
我們將打印結果展示出來:
對象:com.seven.prototype.ConcretePrototype@15db9742對象屬性:小明
對象:com.seven.prototype.ConcretePrototype@6d06d69c對象屬性:小明
這樣我們就克隆了原始的對象
三.深拷貝和淺拷貝
通過上面的例子,我相信都會寫原型模式了,在來說說深淺拷貝的問題,首先我們要了解這個概念。
淺拷貝:如果是基本數據類型,直接複製,如果是引用數據類型則賦值地址。也就是淺拷貝中,如果拷貝對象的引用數據類型的裏面數據改變了,則都會改變,
深拷貝:如果是引用數據的拷貝,則重新創建,各種獨立,修改時不影響其他的克隆對象
1.我們通過Cloneable 來實現淺拷貝
/**
* @author Seven 通過Cloneable淺拷貝
*
*/
public class Prototype implements Cloneable {
private class MyPrototype implements Serializable
{
}
private String name;
public MyPrototype MyPrototype=new MyPrototype();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Prototype clone() throws CloneNotSupportedException {
Object obj = null;
try {
obj = super.clone();
return (Prototype) obj;
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
System.out.println("不支持克隆方法!");
return null;
}
}
}
2.我們通過序列化實現深拷貝
public class Prototype implements Serializable{
private class MyPrototype implements Serializable
{
}
private String name;
public MyPrototype MyPrototype=new MyPrototype();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/** 深拷貝
* @return
* @throws Exception
*/
public Prototype deepClone() throws Exception {
// 將對象寫入流中,
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(byteos);
oos.writeObject(this);
// 將對象取出來
ByteArrayInputStream bi = new ByteArrayInputStream(byteos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bi);
return (Prototype) ois.readObject();
}
}
下面是打印
淺拷貝對象:com.seven.prototype.clone.Prototype@15db9742屬性:小淺,com.seven.prototype.clone.PrototypeMyPrototype@6d06d69c
深拷貝對象:com.seven.prototype.clone.Prototype@4e25154f,屬性:小深,com.seven.prototype.clone.PrototypeMyPrototype@7699a589
我們可以通過打印看出來,深淺拷貝的差別也就是對引用對象拷貝的差別
四.總結
本文介紹了什麼是原型模式以及原型模式的寫法,深淺拷貝的區別以及實現方式,如果本文對你有用,可以點個贊,如果有不正之處,歡迎留下你的評論,謝謝!