享元模式
@author 李思文
@createTime 2020/01/14
**享元模式(Flyweight):**运用共享技术有效地支持大量细粒度的对象。
代码示例:
Flyweight.java
/**
* @ProjectName: designpattern
* @ClassName: Flyweight
* @Description: 它是所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用域外部状态。
* @Author: lisiwen
* @Date: 2020/1/14 9:00
**/
public interface Flyweight {
/**
* @Description 业务操作
* @Date 2020/1/14 9:02
* @param extrinsicstate
* @Return void
**/
void Operation(int extrinsicstate);
}
ConcreteFlyweight.java
/**
* @ProjectName: designpattern
* @ClassName: ConcreteFlyweight
* @Description: 继承Flyweight超类或实现Flyweight接口,并为内部装填增加存储空间
* @Author: lisiwen
* @Date: 2020/1/14 9:02
**/
public class ConcreteFlyweight implements Flyweight {
@Override
public void Operation(int extrinsicstate) {
System.out.println("具体Flyweight:" + extrinsicstate);
}
}
UnsharedConcreteFlyweight.java
/**
* @ProjectName: designpattern
* @ClassName: UnsharedConcreteFlyweight
* @Description: 指那些不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但它并不强制共享。
* @Author: lisiwen
* @Date: 2020/1/14 9:05
**/
public class UnsharedConcreteFlyweight implements Flyweight {
@Override
public void Operation(int extrinsicstate) {
System.out.println("不共享的具体Flyweight:" + extrinsicstate);
}
}
FlyweightFactory.java
/**
* @ProjectName: designpattern
* @ClassName: FlyweightFactory
* @Description: 是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建要给(如果不存在的话)
* @Author: lisiwen
* @Date: 2020/1/14 9:07
**/
public class FlyweightFactory {
private Hashtable flyweights = new Hashtable();
public FlyweightFactory() {
flyweights.put("X", new ConcreteFlyweight());
flyweights.put("Y", new ConcreteFlyweight());
flyweights.put("Z", new ConcreteFlyweight());
}
public Flyweight getFlyweight(String key) {
Flyweight flyweight = (Flyweight) flyweights.get(key);
return flyweight;
}
}
Main.java
/**
* @ProjectName: designpattern
* @ClassName: Main
* @Description: 客户端代码
* @Author: lisiwen
* @Date: 2020/1/14 9:11
**/
public class Main {
public static void main(String[] args) {
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.getFlyweight("X");
fx.Operation(--extrinsicstate);
Flyweight fy = f.getFlyweight("Y");
fy.Operation(--extrinsicstate);
Flyweight fz = f.getFlyweight("Z");
fz.Operation(--extrinsicstate);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(--extrinsicstate);
}
}
// 控制台输出
具体Flyweight:21
具体Flyweight:20
具体Flyweight:19
不共享的具体Flyweight:18
享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类实例来表示数据。如果能发现这些实例除了几个参数外基本都是相同的,有时就能够受大幅度的减少需要实例化的类的数量。如果能够把那些参数移到类实例的外面,在方法调用时将他们传递进来,就可以通过共享大服务的减少单个实例的数目。
享元模式的应用
如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用
还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时看可以考虑使用享元模式。
6