①UML设计
②定义及使用场景:利用共享的方式解决大量创建销毁导致额外开销
③示例:
/**
* 构建享元角色接口
*/
public interface Flyweight{
void action();
}
/**
* 构建具体享元类
*/
public class ConcreteFlyweight implements Flyweight{
@Override
public void action(){
System.out.println("享元模式");
}
}
/**
* 构建享元工厂
*/
public class FactoryFlyweight{
static Map<String,Flyweight> flyweightMap = Maps.newConcurrentMap();//共享池
public static Flyweight getFlyweight(String key){
Flyweight flyweight = flyweightMap.get(key);//根据key先去共享池中查找是否已有需要的对象
if(null == flyweight){
flyweightMap.put(key,new ConcreteFlyweight());//没有需要的对象就重新创建一个,并保存到共享池中
}
return flyweightMap.get(key);
}
public static int getSize(){
return flyweightMap.size();
}
}
public class Test{
public static void main(String args[]){
Flyweight fw1 = FactoryFlyweight.getFlyweight("1");
fw1.action();
Flyweight fw2 = FactoryFlyweight.getFlyweight("2");
fw2.action();
Flyweight fw3 = FactoryFlyweight.getFlyweight("1");
fw3.action();
System.out.println(FactoryFlyweight.getSize());//实际值保存了两个对象,所以为2
}}