A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 434510655 初级黑马   /  2013-2-21 11:00  /  1001 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

定义:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.
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();
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马