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());
	}
}

猜你喜欢

转载自blog.csdn.net/kingSolider/article/details/84994003
今日推荐