黑马程序员技术交流社区

标题: java 设计模式之原型模式 [打印本页]

作者: 434510655    时间: 2013-2-21 11:00
标题: java 设计模式之原型模式
定义:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.
Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建
浅复制
  被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象。换言之,浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
浅复制
Mokey.JAVA
package desin.Prototype.lower;
import java.util.Date;

public class Mokey implements Cloneable {

private int height;
private int weight;
private Date birthDate;
private GoldRingdeStaff goldRingdeStaff;

public  Mokey(){
  birthDate= new Date();
}
public Date getBirthDate() {
  return birthDate;
}
public void setBirthDate(Date birthDate){
  this.birthDate =birthDate;
}
public int getHeight() {
  return height;
}
public void setHeight(int height) {
  this.height = height;
}
public int getWeight() {
  return weight;
}
public void setWeight(int weight) {
  this.weight = weight;
}

public Object clone(){
  Mokey mokey=null;
  try {
   mokey=(Mokey)super.clone();
  } catch(CloneNotSupportedException e) {
   // TODO 自动生成catch 块
   e.printStackTrace();
  }
  finally{
   returnmokey;
  }
}
public GoldRingdeStaff getGoldRingdeStaff(){
  return goldRingdeStaff;
}
public void setGoldRingdeStaff(GoldRingdeStaffgoldRingdeStaff) {
  this.goldRingdeStaff =goldRingdeStaff;
}
}
GoldRingdeStaff。JAVA
package desin.Prototype.lower;

public class GoldRingdeStaff {
private float height=100.0f;
private float weight=10.0f;
public float getHeight() {
  return height;
}
public void setHeight(float height) {
  this.height = height;
}
public float getWeight() {
  return weight;
}
public void setWeight(float weight) {
  this.weight = weight;
}
}
testClient.JAVA
package desin.Prototype.lower;

public class testClient {
private Mokey mokey= new Mokey();

public void change(){
  Mokey copymokey2;
   copymokey2=(Mokey)mokey.clone();
  System.out.println("monkeybirth date :"+mokey.getBirthDate());
  System.out.println("copymokey2birth date :"+copymokey2.getBirthDate());
  System.out.println("copymokey2==monkey :"+(copymokey2==mokey));
  System.out.println("copymokey2staff ==monkeystaff:"+(copymokey2.getGoldRingdeStaff()==mokey.getGoldRingdeStaff()));
}

public static void main(String[] args) {
  // TODO 自动生成方法存根
  testClient testClient= newtestClient();
  testClient.change();
}
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2