原型设计模式(Prototype Pattern)
用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。 使用:当构造函数的赋值逻辑非常多,创建对象成本大的时候。 两种实现方式
通过clone()不过会出现浅拷贝的情况,需要自己手动进行再次深拷贝(clone不会调用构造方法,直接复制) 通过序列化的方式
代码示例
public class WeekReport implements Cloneable , Serializable {
private int id;
private String emp;
private Date date;
@Override
public Object clone ( ) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ;
ObjectOutputStream objectOutputStream = new ObjectOutputStream ( byteArrayOutputStream) ;
objectOutputStream. writeObject ( this ) ;
objectOutputStream. close ( ) ;
byte [ ] bytes = byteArrayOutputStream. toByteArray ( ) ;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( bytes) ;
ObjectInputStream objectInputStream = new ObjectInputStream ( byteArrayInputStream) ;
Object o = objectInputStream. readObject ( ) ;
objectInputStream. close ( ) ;
return o;
} catch ( Exception e) {
throw new RuntimeException ( ) ;
}
}
public int getId ( ) {
return id;
}
public void setId ( int id) {
this . id = id;
}
public String getEmp ( ) {
return emp;
}
public void setEmp ( String emp) {
this . emp = emp;
}
public Date getDate ( ) {
return date;
}
public void setDate ( Date date) {
this . date = date;
}
@Override
public String toString ( ) {
return "WeekReport{" +
"id=" + id +
", emp='" + emp + '\'' +
", date=" + date +
'}' ;
}
}
原理管理
public class PrototypeManager {
private Map < String , PrototypeDemo > allObjectMap = new HashMap < > ( ) ;
public void putObject ( String key , PrototypeDemo obj) {
this . allObjectMap. put ( key, obj) ;
}
public PrototypeDemo getObject ( String key) {
PrototypeDemo prototypeDemo = this . allObjectMap. get ( key) ;
if ( prototypeDemo != null ) {
try {
prototypeDemo = prototypeDemo. clone ( ) ;
} catch ( CloneNotSupportedException e) {
e. printStackTrace ( ) ;
}
}
return prototypeDemo;
}
}