结构型模式有七种:
享元模式
运用共享技术有效的支持大量细粒度对象,也就是说在一个系统中如果有多个相同的对象,那么只共享一份就可以了,不必每个都去实例化一个对象。
如果一个应用使用了大量的对象,这些对象造成了很大的系统开销就应该考虑使用享元模式
角色
抽象享元角色:此角色是所有的具体享元类的超类,为这些类规定出需要实现的公共接口或抽象类。
具体享元(ConcreteFlyweight)角色:实现抽象享元角色所规定的接口。如果有内部状态的话,必须负责为内部状态提供存储空间。
复合享元(UnsharableFlyweight)角色:复合享元角色所代表的对象是不可以共享的,但是一个复合享元对象可以分解成为多个本身是单纯享元对象的组合。
享元工厂(FlyweightFactoiy)角色:本角色负责创建和管理享元角色。本角色必须保证享元对象可以被系统适当地共享。
代码实现
package com.sun.flyweight;
/**
* 抽象享元角色
* @author work
*
*/
public abstract class FlyWeight {
public abstract void operaction(int i);
}
package com.sun.flyweight;
/**
* 具体享元角色
* @author work
*/
public class ConcreteFlyWeight extends FlyWeight{
@Override
public void operaction(int i) {
// TODO Auto-generated method stub
System.out.println("具体。。。。。。。。"+i);
}
}
package com.sun.flyweight;
/**
* 复合享元角色
* @author work
*
*/
public class UnShareFlyWeight extends FlyWeight{
@Override
public void operaction(int i) {
// TODO Auto-generated method stub
System.out.println("不共享具体.........."+i);
}
}
package com.sun.flyweight;
import java.util.Hashtable;
/**
* 工厂
* @author work
*/
public class FlyWeightFactory {
private Hashtable flyHashtable = new Hashtable();
public FlyWeightFactory() {
// TODO Auto-generated constructor stub
flyHashtable.put("X", new ConcreteFlyWeight());
flyHashtable.put("Y", new ConcreteFlyWeight());
flyHashtable.put("Z", new ConcreteFlyWeight());
}
public FlyWeight getFlyWeight(String key) {
return (FlyWeight) flyHashtable.get(key);
}
}
/**
* 客户端
* @author work
*/
public class Client {
public static void main(String[] args) {
int ex =22;
FlyWeightFactory f = new FlyWeightFactory();
FlyWeight f1 = f.getFlyWeight("X");
f1.operaction(--ex);
FlyWeight f2 = f.getFlyWeight("Y");
f2.operaction(--ex);
FlyWeight f3 = f.getFlyWeight("Z");
f3.operaction(--ex);
UnShareFlyWeight u1 = new UnShareFlyWeight();
u1.operaction(--ex);
}
}
在享元模式的实现中,我们通过工厂类来“缓存”已经创建好的对象。 从而达到对象复用的效果。