设计模式之原型模式

import java.util.HashMap;

interface Prototype extends Cloneable {

public void setName(String name);

}

class ConcretePrototype implements Prototype {
private String name;

public String getName() {
return this.name;
}

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

public ConcretePrototype() {
this.name = " this is propotype!";
}

/**
* * 覆写clone方法 *
*
* @return Object
*/
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
System.out.println(" PrototypeRam is not ConcretePrototype");
}
return o;
}
}

class PrototypeManager {

/** * 关于HashMap和HashTable的区别参考其他blog */
private HashMap hm = null;

private static PrototypeManager prototypeManager = null;

private PrototypeManager() {
hm = new HashMap();
}

public static synchronized PrototypeManager getPrototypeManager() {
if (prototypeManager == null) {
prototypeManager = new PrototypeManager();
}
return prototypeManager;
}

/**
* * 注册 *
*
* @param name
* String *
* @param prototype
* Object
*/
public void register(String name, Object prototype) {
hm.put(name, prototype);
}

/**
* * 解除注册 *
*
* @param name
* String
*/
public void unRegister(String name) {
hm.remove(name);
}

/**
* * 获得原型实例 *
*
* @param name
* String *
* @return Object
*/
public Object getPrototype(String name) {
Object o = null;
if (hm.containsKey(name)) {
o = hm.get(name);
} else {
try {
/** * 自动查找原型管理器里不存在的类,并动态生成他 */
o = Class.forName(name).newInstance();
this.register(name, o);
} catch (Exception e) {
System.out.println("class " + name + " don't define "
+ e.getMessage());
e.printStackTrace();
}
}
return o;
}
}

/**
* * *
* <p>
* Title:
* </p> * *
* <p>
* Description: 客户端使用prototype模式
* </p> * *
* <p>
* Copyright: Copyright (c) 2008
* </p> * *
*
* @author meconsea *
* @version 1.0
*/
public class PrototypeDemo {
PrototypeManager pm = null;

public PrototypeDemo() {
pm = PrototypeManager.getPrototypeManager();
}

public static void main(String args[]) {
PrototypeDemo pc = new PrototypeDemo();
String className = null;
className = "ConcretePrototype";
ConcretePrototype pr = null;
pr = (ConcretePrototype) (pc.pm.getPrototype(className));
if (pr != null) {
ConcretePrototype[] pram;
System.out.println("For loop before ConcretePrototype name == "
+ pr.getName());
pram = new ConcretePrototype[10];
for (int i = 0; i < 10; i++) {
/** * 生成一批克隆的对象,并比较他们和原型的不同 */
pram[i] = (ConcretePrototype) pr.clone();
System.out.println("ConcretePrototype name == "
+ pram[i].getName());
pram[i].setName(pram[i].getName() + i);
System.out.println("clone changes after " + pram[i].getName()
+ " old " + pr.getName());
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值