用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.
Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节。
工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
- public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
} - public class Stu {
private String name;
private int scores;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScores() {
return scores;
}
public void setScores(int scores) {
this.scores = scores;
}
@Override
public String toString() {
return "Stu [name=" + name + ", scores=" + scores + "]";
}
} -
package prototype;
public class Prototype implements Cloneable {
private Stu stu;
private User user;
public User getUser() {
return user;
}public void setUser(User user) {
this.user = user;
}
public Stu getStu() {
return stu;
}public void setStu(Stu stu) {
this.stu = stu;
}@Override
protected Object clone() {
// TODO Auto-generated method stub
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}}
-
public class ConcretePrototype extends Prototype{
public ConcretePrototype(Object object) {
// TODO Auto-generated constructor stub
if(object instanceof User){
setUser((User)object);
}else {
setStu((Stu) object);
}
}}
-
package prototype;
public class TestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
User user= new User();
user.setAge(44);
user.setName("tttt");
Stu stu = new Stu();
stu.setName("Stu");
stu.setScores(200);
Prototype prototype = new ConcretePrototype(user);
Prototype prototype2 = (Prototype) prototype.clone();
//克隆后不是两个不同的对象
System.out.println(prototype==prototype2);
System.out.println(prototype.getUser());
System.out.println(prototype2.getUser());
prototype2.getUser().setAge(666);
System.out.println(prototype.getUser());
System.out.println(prototype2.getUser());
System.out.println("======================");
Prototype prototypeStu = new ConcretePrototype(stu);
Prototype prototype2Stu = (Prototype) prototypeStu.clone();
System.out.println(prototypeStu.getStu());
System.out.println(prototype2Stu.getStu());
}}

被折叠的 条评论
为什么被折叠?



