13、享元模式
享元模式
1、定义
享元模式(FlyWeight),运用共享技术有效的支持大量细粒度的对象。
2、结构图
单纯享元模式所涉及到的角色如下:
● 抽象享元(Flyweight)角色 :给出一个抽象接口,以规定出所有具体享元角色需要实现的方法。
● 具体享元(ConcreteFlyweight)角色:实现抽象享元角色所规定出的接口。如果有内蕴状态的话,必须负责为内蕴状态提供存储空间。
● 享元工厂(FlyweightFactory)角色 :本角色负责创建和管理享元角色。本角色必须保证享元对象可以被系统适当地共享。当一个客户端对象调用一个享元对象的时候,享元工厂角色会检查系统中是否已经有一个符合要求的享元对象。如果已经有了,享元工厂角色就应当提供这个已有的享元对象;如果系统中没有一个适当的享元对象的话,享元工厂角色就应当创建一个合适的享元对象。
3、代码
(1)抽象享元
public interface IFlyweight {
public void operate(String state);
}
(2)具体享元
public class ConcreteFlyweight implements IFlyweight {
private Character intrinsicState = null;
public ConcreteFlyweight(Character intrinsicState) {
super();
this.intrinsicState = intrinsicState;
}
@Override
public void operate(String state) {
System.out.println("Intrinsic State = " + this.intrinsicState);
System.out.println("Extrinsic State = " + state);
}
}
(3)享元工厂/**
* 享元类工厂
* @author qiang
*
*/
public class FlyweightFactory {
private static Map<Character, IFlyweight> flyweightMap = new HashMap<Character, IFlyweight>();
public static IFlyweight getFlyweight(Character state){
IFlyweight f = flyweightMap.get(state);
if(f != null){
return f;
}else{
f = new ConcreteFlyweight(state);
flyweightMap.put(state, f);
return f;
}
}
}
(4)客户端public class Client {
public static void main(String[] args) {
IFlyweight flyweight1 = FlyweightFactory.getFlyweight(new Character('a'));
flyweight1.operate("first call");
IFlyweight flyweight2 = FlyweightFactory.getFlyweight(new Character('b'));
flyweight2.operate("second call");
IFlyweight flyweight3 = FlyweightFactory.getFlyweight(new Character('a'));
flyweight3.operate("third call");
}
}
4、总结
享元模式的有点在于可以极大减少内存中对象的数量,使得相同的或者相似的对象在内存中只保留一份。
享元模式的外部状态相对独立,而且不影响内存的状态,从而使得享元对象可以再不同的环境中使用。