场景:
内存属于稀缺资源,不要随便浪费。如果有很多个完全相同或相似的对象,我们可以通过享元模式,节省内存。
核心:
享元模式以共享的方式高效地支持大量细粒度对象的重用。
享元对象能做到共享的关键是区分了内部状态和外部状态。
内部状态:可以共享,不会随便环境变化而变化
外部状态:不可以共享,会随环境变化而变化。
享元模式实现:
FlyweightFactory享元工厂类
创建并管理享元对象,享元池一般设计成键值对
FlyWeight抽象享元类
通常是一个接口或抽象类,声明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态。
ConcreteFlyWeight具体享元类
为内部状态提供成员变量进行存储
UnsharedConcreteFlyWeight非共享享元类
不能被共享的子类可以设计为非共享享元类
享元模式的使用一般要工厂模式搭配起来。
/FlyWeight抽象享元类 interface ChessFlyWeight{ void setColor(String color); String getColor(); void disPlay(Coordinate coo); } //UnsharedConcreteFlyWeight非共享享元类 class Coordinate{ privateintx,y; public Coordinate(int x,int y){ super(); this.x = x; this.y = y; } publicint getX() { returnx; } publicvoid setX(int x) { this.x = x; } publicint getY() { returny; } publicvoid setY(int y) { this.y = y; } } //ConcreteFlyWeight具体享元类 class CoocreteChess implements ChessFlyWeight{
private String color;
public CoocreteChess(String color){ super(); this.color = color; } publicvoid setColor(String color) { this.color = color;
} public String getColor() {
returncolor; }
publicvoid disPlay(Coordinate coo) { System.out.println("棋子颜色"+color); System.out.println("棋子位置"+coo.getX()+"--"+coo.getY()); } } //享FlyweightFactory享元工厂类 class ChessFlyWeightFactory{ //享元池 privatestatic Map<String,ChessFlyWeight> map = new HashMap<String, ChessFlyWeight>();
publicstatic ChessFlyWeight getChess(String color){ if(map.get(color)!=null){ returnmap.get(color); }else{ ChessFlyWeight cfw = new CoocreteChess(color); map.put(color, cfw); return cfw; } } } publicclass Client { publicstaticvoid main(String[] args) { ChessFlyWeight cf1= ChessFlyWeightFactory.getChess("黑色"); ChessFlyWeight cf2= ChessFlyWeightFactory.getChess("黑色"); System.out.println(cf1); System.out.println(cf2); System.out.println("增加外部状态的位置!"); cf1.disPlay(new Coordinate(12, 12)); cf2.disPlay(new Coordinate(12, 13));
} } |
优点:
极大减少了内存对象的数量
相同或相似对象内存中只存一份,极大节约资源,提高系统性能
外部状态相对独立,不影响内部状态
缺点:
模式较复杂,使逻辑复杂化
为了节省内存,共享了内存状态,分离出外部状态,而读取外部状态使运行时间变长。用时间换取空间。