通过共享的方式减少对象的创建
// 享元类
package flyweight;
import java.util.HashMap;
import java.util.Map;
public class FlyWeight {
private static final Map<String, String> POOL = new HashMap<String, String>();
public static String getVal(String aaa) {
if (POOL.containsKey(aaa)) {
System.out.println("共享对象");
return POOL.get("aaa");
} else {
String string = new String( aaa + "Val");
System.out.println("新建对象");
POOL.put(aaa, string); //aaaVal 可以是个自定义类 aaaVal是为了演示随便写的
return string;
}
}
}
// 测试类
package flyweight;
public class Client {
public static void main(String[] args) {
FlyWeight.getVal("aaa");// 新建对象
FlyWeight.getVal("bbb");// 新建对象
FlyWeight.getVal("aaa");// 共享对象
FlyWeight.getVal("ccc");// 新建对象
}
}
网友评论