原型类:DTO、VO、POJO、Entity
数据库表中查询出来的对象会赋值给DTO,把DTO中的值赋值给VO再把VO 中的值传到view中去,会经过一个复制(要把DTO 中的么一个属性的值都赋值给VO中的每一个属性的值属性名称相同,属性类型相同)的过程。
Apache的BeanUtils会提供一个复制功能,是使用反射去实现的(就是原型模式的实现)
Java推荐clone去实现原型模式,反射性能比较低,颗粒不是简单的对象复制,而是把对象中所有额属性值赋值给一个新的对象的属性。
Spring中 scope = "prototype"也是原型模型。将对象中配置的依赖关系,再每次使用对象之前都会创建一个新的对象,并且会将依赖关系完整的赋值给新创建的对象,Spring中的原型模式大部分都是用反射实现的。Spring 中默认scope="singleton",默认作用域是单例的。
浅克隆的原型模式:
public class CloneTarget extends Prototype {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Prototype implements Cloneable{
public String name;
CloneTarget target = null;
// @Override
// protected Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
}
public class CloneTest {
public static void main(String[] args) {
CloneTarget p = new CloneTarget();
p.name = "Tom";
// p.list = new ArrayList<CloneTarget>();
// p.list.add(new CloneTarget());
p.target = new CloneTarget();
System.out.println(p.target);
try {
Prototype obj = (Prototype)p.clone();
System.out.println(obj.target);
// System.out.println(obj.list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
深克隆的原型模式:
public class Monkey {
public int height;
public int weoght;
public Date birthday;
}
public class QiTianDaSheng extends Monkey implements Cloneable, Serializable {
public JinGuBang jinGuBang;
public QiTianDaSheng(){
//只是初始化
this.birthday = new Date();
this.jinGuBang = new JinGuBang();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Object deepClone(){
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
QiTianDaSheng copy = (QiTianDaSheng)ois.readObject();
copy.birthday = new Date();
return copy;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
public class JinGuBang implements Serializable {
private float h = 100;
private float d = 10;
public void big(){
this.d *= 2;
this.h *= 2;
}
public void small(){
this.d /= 2;
this.h /= 2;
}
}
public class TestDeep {
public static void main(String[] args) {
QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();
try {
QiTianDaSheng clone = (QiTianDaSheng)qiTianDaSheng.deepClone();
System.out.println(qiTianDaSheng.jinGuBang == clone.jinGuBang);
} catch (Exception e) {
e.printStackTrace();
}
}
}