简介
享元(Flyweight)模式的定义:运用共享技术来有効地支持大量细粒度对象的复用。它通过共享已经存在的又橡来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
享元模式的结构与实现
享元模式中存在以下两种状态:
内部状态,即不会随着环境的改变而改变的可共享部分;
外部状态,指随环境改变而改变的不可以共享的部分。享元模式的实现要领就是区分应用中的这两种状态,并将外部状态外部化。下面来分析其基本结构和实现方法。
享元模式结构图如下:
角色
享元模式的主要角色有如下。
抽象享元角色(Flyweight):是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入。
具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口。
非享元(Unsharable Flyweight)角色:是不可以共享的外部状态,它以参数的形式注入具体享元的相关方法中。
享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。
简单实现
1.创建抽象享元角色(Flyweight)
public interface Flyweight {
public void operation(UnsharedConcreteFlyweight unsharedConcreteFlyweight);
}
2.创建具体享元(Concrete Flyweight)角色
public class ConcreteFlyweight implements Flyweight {
private String key;
public ConcreteFlyweight(String key) {
this.key = key;
System.out.println("具体享元"+key+"被创建!");
}
@Override
public void operation(UnsharedConcreteFlyweight unsharedConcreteFlyweight) {
System.out.println("具体享元"+key+"被调用!");
System.out.println("非享元信息:" + unsharedConcreteFlyweight.getInfo());
}
}
3.创建非享元(Unsharable Flyweight)角色
public class UnsharedConcreteFlyweight {
private String info;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public UnsharedConcreteFlyweight(String info) {
this.info = info;
}
}
4.创建享元工厂(Flyweight Factory)角色
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;
}
}
5.Client(Main验证)
public class FlyweightMain {
public static void main(String[] args) {
FlyweightFactory flyweightFactory = new FlyweightFactory();
Flyweight f1 = flyweightFactory.getFlyweight("1");
Flyweight f2 = flyweightFactory.getFlyweight("1");
Flyweight f3 = flyweightFactory.getFlyweight("2");
Flyweight f4 = flyweightFactory.getFlyweight("3");
Flyweight f5 = flyweightFactory.getFlyweight("2");
Flyweight f6 = flyweightFactory.getFlyweight("3");
f1.operation(new UnsharedConcreteFlyweight("1 first"));
f2.operation(new UnsharedConcreteFlyweight("1 second"));
f3.operation(new UnsharedConcreteFlyweight("2 first"));
f4.operation(new UnsharedConcreteFlyweight("3 first"));
f5.operation(new UnsharedConcreteFlyweight("2 second"));
f6.operation(new UnsharedConcreteFlyweight("3 second"));
}
}