场景
如果有很多个完全相同或相似的对象,我们可以通过享元模式,节省内存。
核心
- 享元模式以共享的方式高效地支持大量细粒度对象的重用
- 享元对象能做到共享的关键是区分了内部状态和外部状态
1 内部状态:可以共享,不会随环境变化而变化
2 外部状态:不可以共享,会随环境而变化
围棋举例
- 围棋有多个属性
内部状态属性:颜色、形状、大小
外部状态:位置
享元模式实现
- FlyweightFactory
创建并管理享元对象,享元池一般设计成键值对 - FlyWeight抽象享元类
通常是一个接口或者抽象类,申明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态 - ConcreateFlyWeight具体享元类
为内部状态提供成员变量进行存储 - UnsharedConcreateFlyWeight非共享享元类
UML
image.png代码实现
package com.amberweather.flyweight;
/**
* 享元类
* @author HT
*
*/
public interface ChessFlyweight {
void setColor(String c);
String getColor();
void dispaly(Coordinate c);
}
class ConcreateChess implements ChessFlyweight{
private String color;
public ConcreateChess(String color) {
super();
this.color = color;
}
@Override
public void setColor(String c) {
this.color = c;
}
@Override
public String getColor() {
return color;
}
@Override
public void dispaly(Coordinate c) {
System.out.println("棋子颜色"+color);
System.out.println("棋子位置:"+c.getX()+","+c.getY());
}
}
package com.amberweather.flyweight;
/**
*
* 外部状态 UnsharedConcreateFlyWeight
* @author Administrator
*
*/
public class Coordinate {
private int x,y;
public Coordinate(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
package com.amberweather.flyweight;
import java.util.HashMap;
import java.util.Map;
/**
* 享元工厂
* @author HT
*
*/
public class ChessFlyWeightFactory {
private static Map<String,ChessFlyweight> map = new HashMap<>();
public static ChessFlyweight getChess(String color){
if (map.get(color) != null){
return map.get(color);
}else{
ChessFlyweight cfw = new ConcreateChess(color);
map.put(color, cfw);
return cfw;
}
}
}
package com.amberweather.flyweight;
public class Client {
public static void main(String[] args) {
ChessFlyweight chess1 =ChessFlyWeightFactory.getChess("黑色");
ChessFlyweight chess2 =ChessFlyWeightFactory.getChess("黑色");
System.out.println(chess1);
System.out.println(chess1);
System.out.println("增加外部状态的处理==========");
System.out.println("chess1----" );
chess1.dispaly(new Coordinate(20,20));
System.out.println("chess2----" );
chess2.dispaly(new Coordinate(30,20));
}
}
应用场景
- 可以在任何“池”中操作
比如:线性池、数据库链接池 - String类的设计也是享元模式
网友评论