用途
享元模式是一种结构型模式。
结构
图-享元模式结构图
Flyweight : 它是所有具体享元类的超类或接口,通过这个接口,Flyweight 可以接受并作用于外部状态。
abstract class Flyweight {
public abstract void Operation(int extrinsicstates);
}
public abstract void Operation(int extrinsicstates);
}
ConcreteFlyweight : 是继承 Flyweight 超类或实现 Flyweight 接口,并为内部状态增加存储空间。
class ConcreteFlyweight extends Flyweight {
@Override
public void Operation(int extrinsicstates) {
System.out.println("共享的Flyweight : " + extrinsicstates);
}
}
@Override
public void Operation(int extrinsicstates) {
System.out.println("共享的Flyweight : " + extrinsicstates);
}
}
UnsharedConcreteFlyweight : 指那些不需要共享的 Flyweight 子类,因为 Flyweight 接口共享成为可能,但它并不强制共享。
class UnsharedConcreteFlyweight extends Flyweight {
@Override
public void Operation(int extrinsicstates) {
System.out.println("不共享的Flyweight : " + extrinsicstates);
}
}
@Override
public void Operation(int extrinsicstates) {
System.out.println("不共享的Flyweight : " + extrinsicstates);
}
}
FlywightFactory :是一个享元工厂,用来创建并管理 Flyweight 对象。它主要是用来确保合理地共享 Flyweight ,当用户请求一个 Flyweight 时, FlyweightFactory 对象提供一个已创建的实例或创建一个(如果对象不存在的话)。
class FlywightFactory {
private Hashtable<String, Flyweight> flyweights = new Hashtable<String, Flyweight>();
public FlywightFactory() {
flyweights.put("X", new ConcreteFlyweight());
flyweights.put("Y", new ConcreteFlyweight());
flyweights.put("Z", new ConcreteFlyweight());
}
public Flyweight GetFlyweight(String key) {
return ((Flyweight)flyweights.get(key));
}
}
private Hashtable<String, Flyweight> flyweights = new Hashtable<String, Flyweight>();
public FlywightFactory() {
flyweights.put("X", new ConcreteFlyweight());
flyweights.put("Y", new ConcreteFlyweight());
flyweights.put("Z", new ConcreteFlyweight());
}
public Flyweight GetFlyweight(String key) {
return ((Flyweight)flyweights.get(key));
}
}
测试代码
public class FlyweightPattern {
public static void main(String[] args) {
int extrinsicstates = 1;
FlywightFactory factory = new FlywightFactory();
Flyweight fx = factory.GetFlyweight("X");
fx.Operation(extrinsicstates);
Flyweight fy = factory.GetFlyweight("Y");
fy.Operation(++extrinsicstates);
Flyweight fz = factory.GetFlyweight("Z");
fz.Operation(++extrinsicstates);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(++extrinsicstates);
}
}
public static void main(String[] args) {
int extrinsicstates = 1;
FlywightFactory factory = new FlywightFactory();
Flyweight fx = factory.GetFlyweight("X");
fx.Operation(extrinsicstates);
Flyweight fy = factory.GetFlyweight("Y");
fy.Operation(++extrinsicstates);
Flyweight fz = factory.GetFlyweight("Z");
fz.Operation(++extrinsicstates);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(++extrinsicstates);
}
}
运行结果
共享的Flyweight : 1
共享的Flyweight : 2
共享的Flyweight : 3
不共享的Flyweight : 4
共享的Flyweight : 2
共享的Flyweight : 3
不共享的Flyweight : 4