/**
* 享元模式
*/
public class Main {
public static void main(String[] args) {
ICat cat1 = FlyweighFactory.getFlyweight("cat1");
ICat cat2 = FlyweighFactory.getFlyweight("cat2");
System.out.println(cat1 == cat2);
ICat cat3 = FlyweighFactory.getFlyweight("cat2");
System.out.println(cat2 == cat3);
}
}
public interface ICat {
void run();
}
public class Cat implements ICat {
@Override
public void run() {
System.out.println("running");
}
}
public class FlyweighFactory {
private static Map<String,ICat> flyweights = new HashMap<String,ICat>();
public static ICat getFlyweight(String key) {
if(!flyweights.containsKey(key)){
flyweights.put(key,new Cat());
}
return flyweights.get(key);
}
}
用法:
这个设计模式平时用的太多了,看代码很明白了,一个Map里如果有这个元素,就取出来用,没有的话就新建一个,然后放进去,下次就直接取出来用。
实际中例子也很多,比如缓存就是最典型的享元模式的应用,缓存命中就拿出来用,没有命中去数据库里查出结果,把结果放到缓存池里,下次就可以命中了。
说重点,大家觉不觉得这和单例模式有点像,对的,这就是一个扩展的单例模式,是多例模式。。。只不过这种多例还能动态添加。