1:原型模式可以理解为克隆
java里面提供了一个借口cloneable,实现这个接口就意味这个类可以被克隆!
现在我已经迫不急待的克隆出多个我来了,一个在上学,一个在家里面多好啊!
开始吧
package cn.tsp2c.ljz.prototypepattern;
public class Person implements Cloneable{
private double height;
private double weight;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public Person(double height,double weight){
this.height = height;
this.weight = weight;
}
public Object close(Person p){
return (Object)p;
}
public Object close(){
Person p = new Person(height,weight);
return (Object)p;
}
}
package cn.tsp2c.ljz.prototypepattern;
public class Main {
public static void main(String[] args) {
Person p = new Person(165,52);
Person p2 = (Person)p.close(p);
System.out.println("第一个人身高"+p.getHeight());
System.out.println("第二个人身高"+p2.getHeight());
}
}
输出的结果都一样,可知克隆成功
java里面提供了一个借口cloneable,实现这个接口就意味这个类可以被克隆!
现在我已经迫不急待的克隆出多个我来了,一个在上学,一个在家里面多好啊!
开始吧
package cn.tsp2c.ljz.prototypepattern;
public class Person implements Cloneable{
private double height;
private double weight;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public Person(double height,double weight){
this.height = height;
this.weight = weight;
}
public Object close(Person p){
return (Object)p;
}
public Object close(){
Person p = new Person(height,weight);
return (Object)p;
}
}
package cn.tsp2c.ljz.prototypepattern;
public class Main {
public static void main(String[] args) {
Person p = new Person(165,52);
Person p2 = (Person)p.close(p);
System.out.println("第一个人身高"+p.getHeight());
System.out.println("第二个人身高"+p2.getHeight());
}
}
输出的结果都一样,可知克隆成功