prototype -对象创建模型

     1.意图
              用原型实例指定创建对象的种类并且通过拷贝这些原型创建新对象
     2.参与者
       Prototype,ConcretePrototype,client

     3.结构

代码:

public abstract class Prototype implements Cloneable {
	public Object clone() {
	      Object clone = null;
	      try {
	         clone = super.clone();
	      } catch (CloneNotSupportedException e) {
	         e.printStackTrace();
	      }
	      return clone;
	   }
}


public class PrototypeA extends Prototype {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

public class PrototypeB extends Prototype {
	public int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}


public class PrototypeC extends Prototype {
	private long l;

	public long getL() {
		return l;
	}

	public void setL(long l) {
		this.l = l;
	}
    public long square(){
    	return l*l;
    } 
}

public class PrototypeManager {
   private Map<String,Prototype> objectMap = new Hashtable<String,Prototype>();
   private static PrototypeManager prototypeManager = new PrototypeManager();
   public static PrototypeManager getManager(){
	   return prototypeManager;
   }
   private PrototypeManager(){
	   objectMap.put("A", new PrototypeA());
	   objectMap.put("B", new PrototypeB());
   }
   public void register(Prototype o,String falg){
	   objectMap.put(falg, o);
   }
   public Object getObject(String falg){
	   Prototype o = objectMap.get(falg);
	   if(o == null){
		   throw new RuntimeException("不存在对应的原型");
	   }
	   return o.clone();
   }
}

public class Client {
	public static void main(String[] args) {
		PrototypeB b = (PrototypeB) PrototypeManager.getManager().getObject("B");
	    b.setAge(1);
	    System.out.println(b.getAge());
	    PrototypeManager.getManager().register(new PrototypeC(), "C");
	    PrototypeC c = (PrototypeC) PrototypeManager.getManager().getObject("C");
	    c.setL(5);
	    System.out.println(c.square());
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值