随笔 - 0, 文章 - 3, 评论 - 0, 引用 - 0
数据加载中……

设计模式之原型模式(Prototype)

原型模式就是通过一个对象创建另一个对象,简单的理解就是复制一个对象,至于复制的细节不需要去了解
而Java使用Cloneable接口的Clone方法实现对象复制,所以要实现Cloneable接口
实例:
/**
 * yangxh_520@yahoo.com.cn
 * @author mymy5
 * 2007.09.18
 */
(1)抽象类AbstractClassClone ()    实现Cloneable接口

package cn.yxh.shejimoshi.Prototype;

public  class AbstractClassClone implements Cloneable{
 String spoonName;

 public String getSpoonName() {
  return spoonName;
 }

 public void setSpoonName(String spoonName) {
  this.spoonName = spoonName;
 }
 public Object clone() throws CloneNotSupportedException
 {
  Object object = null;
  object = super.clone();
  //Cloneable  object = new AbstractClassClone(); 生成clone对象的另外一种方法 return object
  return object;
 }
}
(2)抽象类的实现AbstractClassCloneImpl

package cn.yxh.shejimoshi.Prototype;

public class AbstractClassCloneImpl extends AbstractClassClone {
 public AbstractClassCloneImpl(){
  this.setSpoonName("工厂模式--原型(prototype)");
 }
}
(3)工厂类FactoryForClone

package cn.yxh.shejimoshi.Prototype;

public class FactoryForClone {
 public AbstractClassClone getInstance(){
  return new AbstractClassCloneImpl();
 }
}

(4)测试类Test

package cn.yxh.shejimoshi.Prototype;

public class Test {

 public static void main(String[] args) throws CloneNotSupportedException {
  FactoryForClone factory = new FactoryForClone();
  AbstractClassClone test = factory.getInstance();
  AbstractClassCloneImpl test2 = (AbstractClassCloneImpl)test.clone();
  System.out.println(test2.spoonName);
  }
 }

}


posted on 2007-09-18 09:42 杨显华 阅读(121) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: