设计模式之享元模式
什么是享元模式:
以共享的方式高效的支持大量的细粒度对象。通过复用内存中已存在的对象,降低系统创建对象实例的性能消耗。
享元模式由于其共享的特性,可以在任何池中操作,例如,线程池,数据库连接池。
Strig 类的设计也是享元模式
我们以下棋为例每个围棋的棋子都是一个对象,没个对象都有一些
相同的属性:(这些称为内部状态可以共享)
- 颜色
- 大小
- 形状
不同的属性:(这些称为外部状态不可以共享)
- 位置
享元模式怎么用
- FlyWeightFactory:(享元工厂类)用来管理和创建享元对象。
- FlyWeight (享元类) 通常是一个接口或抽象类,申明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态。
- ConcreteFlyweight (具体的享元类)为内部状态提供成员变量进行存储。
- unsharedFlyWeight(不能共享的享元类)不能共享的子类。
import java.util.HashMap;
import java.util.Map;
/**
* 享元工厂类
*/
public class FlyWeightFactory {
// 享元池
private static Map<String, FlyWeight> map = new HashMap<String, FlyWeight>();
public static FlyWeight getFlyweight(String color) {
if (map.get(color) != null) {
return map.get(color);
} else {
FlyWeight flyWeight = new ConcreteFlyWeight(color);
map.put(color, flyWeight);
return flyWeight;
}
}
}
/**
* 享元类
*/
public interface FlyWeight {
String getColor();
void display(UnsharedFlyweight un);
}
/**
* 不能共享的类,表示外部状态
*/
public class UnsharedFlyweight {
private int x,y;
public UnsharedFlyweight(int x, int y) {
super();
this.x = x;
this.y = y;
}
/**
* @return the x
*/
public int getX() {
return x;
}
/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @return the y
*/
public int getY() {
return y;
}
/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
}
package FlyWeight;
public class ConcreteFlyWeight implements FlyWeight{
private String color;
public ConcreteFlyWeight(String color) {
super();
this.color = color;
}
@Override
public String getColor() {
return color;
}
@Override
public void display(UnsharedFlyweight un) {
System.out.println("棋子的颜色:"+getColor());
System.out.println("棋子的位置"+un.getX()+":"+un.getY());
}
}
package FlyWeight;
public class Client {
public static void main(String[] args) {
FlyWeight flyWeight = FlyWeightFactory.getFlyweight("黑色");
FlyWeight flyWeight1 = FlyWeightFactory.getFlyweight("黑色");
System.out.println(flyWeight);
System.out.println(flyWeight1);
System.out.println("增加外部处理");
flyWeight.display(new UnsharedFlyweight(10, 19));
flyWeight1.display(new UnsharedFlyweight(10, 20));
}
}
//FlyWeight.ConcreteFlyWeight@2a139a55
//FlyWeight.ConcreteFlyWeight@2a139a55
//增加外部处理
//棋子的颜色:黑色
//棋子的位置10:19
//棋子的颜色:黑色
//棋子的位置10:20
//两个棋子共用一个对象,独立外部状态
为什么要用享元模式
享元模式的优点:
- 极大减少了内存中对象的数量,
- 相同或者相似对象内存中只有一份,极大的节约资源,提高系统性能,
- 外部状态相对独立,不影响内部状态。
享元模式的缺点:
- 模式较复杂,使程序逻辑复杂化
- 为了节省内存,共享内存状态,分离外部状态,读取外部状态的时间变长,用时间换取了空间。