享元模式本质就是池化思想,让对象实现共用,java 字符串常量池的实现就是享元模式
第一步,建立抽象类
public abstract class FlyWeight {
final String name;
public FlyWeight(String name) {
this.name = name;
}
abstract void doSomthing();
}
实现抽象类
public class ConcreteFlysWeight extends FlyWeight{
public ConcreteFlysWeight(String name) {
super(name);
}
@Override
void doSomthing() {
}
}
抽象类里面放置容器hashmap 装载对象
public class FlyWeightFactory {
private static Map<String,FlyWeight> pool=new HashMap<>();
public static FlyWeight getFlyWeight(String key){
FlyWeight flyWeight = pool.get(key);
if (flyWeight == null) {
ConcreteFlysWeight weight = new ConcreteFlysWeight(key);
pool.put(key, weight);
System.err.println("往池子里新增对象");
}else{
System.err.println("从池子里拿出对象");
}
return flyWeight;
}
}
场景测试类
public class Client {
public static void main(String[] args) {
FlyWeightFactory.getFlyWeight("hello");
FlyWeightFactory.getFlyWeight("hello");
}
}
网友评论