Flyweight(享元模式)
import java.util.Hashtable; /** * 享元模式 * @author TMAC-J * 享元模式一般和工厂模式一起使用,但此处为了更好说明,只用享元模式 * 定义:享元模式针对于是一种以时间来切换空间的方式,其公用同一实例,线程池,string都是其应用 */ public class FlyweightPattern { public class Flyweight{ private Hashtable<String, Object> objs = new Hashtable<String, Object>(); public Object createObj(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ if(objs.get(className) == null){ Object obj = Class.forName(className).newInstance(); return obj; } else{ return objs.get(className); } } } public class A {} public class B{} public void test() throws InstantiationException, IllegalAccessException, ClassNotFoundException{ Flyweight flyweight = new Flyweight(); flyweight.createObj("A"); flyweight.createObj("B"); } }