定义
运用共享技术有效的支持大量细粒度的对象。
UML
/**
* Flyweight接口使共享称为可能,但不强制共享,所有有2种实现类。
*
*/
public interface Flyweight {
/**
* 示例操作:传入外部状态
* @param extrinsicState
*/
public void operation(String extrinsicState);
}
class ConcreteFlyweight implements Flyweight{
/**
* 内部状态
*/
private String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
@Override
public void operation(String extrinsicState) {
//具体的业务逻辑
}
}
/**
* 不需要共享的享元对象的实现,并不是所有的Flyweight对象都需要共享。
*/
class UnsharedConcreteFlyweight implements Flyweight{
/**
* 描述对象的状态
*/
private String allState;
@Override
public void operation(String extrinsicState) {
//具体的功能处理
}
}
/**
* Client不能直接创建共享的享元实例,必须通过享元工厂创建
*/
class FlyweightFactory{
private Map<String,Flyweight> flyweightMap = new HashMap();
public Flyweight getFlyweight(String key){
Flyweight f = flyweightMap.get(key);
if(f == null){
f = new ConcreteFlyweight(key);
flyweightMap.put(key,f);
}
return f;
}
}
Flyweight:抽象的享元角色,同时定义了对象的外部状态和内部状态。外部状态不共享,内部状态共享。
ConcreteFlyweight:具体的享元产品类。
UnsharedConcreteFlyweight:不共享的角色,不会出现在FlyweightFactory里。
FlyweightFactory:享元工厂。构建一个池用于共享ConcreteFlyweight。
特点
1、系统底层类开发,例如数据库连接池,里面是创建好的连接对象,避免重复创建,可以重复利用。除了线程池,还有其他的池技术,例如字符串常量池、缓冲池。
2、避免内存浪费,提高内存使用效率。
应用示例
/**
* Integer.valueOf(x)。如果x在-128~127之间,就是使用的享元模式
*/
public class Flyweight {
public static void main(String[] args) {
Integer x = Integer.valueOf(127);
Integer y = new Integer(127);
Integer z = Integer.valueOf(127);
Integer w = new Integer(127);
System.out.println(x.equals(y)); //true
System.out.println(x == y);//false
System.out.println(w == x); //false
System.out.println(w == y); //false
System.out.println(x == z); //true
}
}
Integer.valueOf(x)方法,先判断值x是否已经在缓存中,如果不在,创建新的Integer,如果在,从缓存中取。