享元(Flyweight)模式的定义:运用共享技术来有効地支持大量细粒度对象的复用。它通过共享已经存在的又橡来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
1.优点
- 相同对象只要保存一份,这降低了系统中对象的数量,从而降低了系统中细粒度对象给内存带来的压力。
2.缺点
- 为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。
- 读取享元模式的外部状态会使得运行时间稍微变长。
3.代码示例
3.1 抽象享元角色
代码语言:javascript复制public interface Flyweight {
/**
* 功能描述:
* 〈享元操作〉
*
* @params : [state]
* @return : void
* @author : cwl
* @date : 2019/6/25 9:14
*/
void operation(UnsharedConcreteFlyweight state);
}
3.2 具体的享元角色
代码语言:javascript复制public class ConcreteFlyweight implements Flyweight {
private String key;
ConcreteFlyweight(String key) {
this.key=key;
System.out.println("具体享元" key "被创建!");
}
@Override
public void operation(UnsharedConcreteFlyweight state) {
System.out.print("具体享元" key "被调用,");
System.out.println("非享元信息是:" state.getInfo());
}
}
3.3 非享元角色-用于被共享
代码语言:javascript复制public class UnsharedConcreteFlyweight {
private String info;
UnsharedConcreteFlyweight(String info) {
this.info=info;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info=info;
}
}
3.4 创建防止重复的享元工厂
代码语言:javascript复制public class FlyweightFactory {
private HashMap<String, Flyweight> flyweights=new HashMap<String, Flyweight>();
public Flyweight getFlyweight(String key) {
Flyweight flyweight=(Flyweight)flyweights.get(key);
if(flyweight != null) {
System.out.println("具体享元" key "已经存在,被成功获取!");
} else {
flyweight=new ConcreteFlyweight(key);
flyweights.put(key, flyweight);
}
return flyweight;
}
}
3.5 测试用例
代码语言:javascript复制public class FlyweightPattern {
public static void main(String[] args) {
FlyweightFactory factory=new FlyweightFactory();
Flyweight f01=factory.getFlyweight("a");
Flyweight f02=factory.getFlyweight("a");
Flyweight f03=factory.getFlyweight("a");
Flyweight f11=factory.getFlyweight("b");
Flyweight f12=factory.getFlyweight("b");
f01.operation(new UnsharedConcreteFlyweight("第1次调用a。"));
f02.operation(new UnsharedConcreteFlyweight("第2次调用a。"));
f03.operation(new UnsharedConcreteFlyweight("第3次调用a。"));
f11.operation(new UnsharedConcreteFlyweight("第1次调用b。"));
f12.operation(new UnsharedConcreteFlyweight("第2次调用b。"));
}
}