享元模式(Flyweight Pattern):
运用共享技术有效地支持大量细粒度的对象。(Use sharing to support large numbers offine-grained objects efficiently.)
享元模式核心:
享元模式的优缺点:
优点:
缺点
享元模式开发中应用的场景:
享元模式实现:
案例:比如围棋软件设计,每个围棋棋子都是一个对象,有如下属性:颜色
形状,大小,(这些是可以共享的)称之为:内部状态。而围棋的位置(这些不可以共享)称之为:外部状态。该过程可分为以下5步:
步骤1:定义抽象享元类
/**
* 享元类
*/
public interface ChessFlyWeight {
void setColor(String c);
String getColor();
void display(Coordinate c);
}
步骤2:定义具体享元类
/**
* 具体享元类
*/
class ConcreteChess implements ChessFlyWeight {
private String color;
public ConcreteChess(String color) {
super();
this.color = color;
}
@Override
public void display(Coordinate c) {
System.out.println("棋子颜色:"+color);
System.out.println("棋子位置:"+c.getX()+"----"+c.getY());
}
@Override
public String getColor() {
return color;
}
@Override
public void setColor(String c) {
this.color = c;
}
}
步骤3:定义非共享享元类
/**
* 外部状态 UnSharedConcreteFlyWeight
*/
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;
}
}
步骤4:定义享元工厂类
/**
* 享元工厂类
*/
public class ChessFlyWeightFactory {
//享元池
private static Map<String,ChessFlyWeight> map = new HashMap<String, ChessFlyWeight>();
public static ChessFlyWeight getChess(String color){
if(map.get(color)!=null){
return map.get(color);
}else{
ChessFlyWeight cfw = new ConcreteChess(color);
map.put(color, cfw);
return cfw;
}
}
}
步骤5:测试
public class Client {
public static void main(String[] args) {
ChessFlyWeight chess1 = ChessFlyWeightFactory.getChess("黑色");
ChessFlyWeight chess2 = ChessFlyWeightFactory.getChess("黑色");
System.out.println(chess1);
System.out.println(chess2);
System.out.println("增加外部状态的处理===========");
chess1.display(new Coordinate(10, 10));
chess2.display(new Coordinate(20, 20));
}
}
如果想了解更多设计模式,可点击:设计模式概述 以及 23种设计模式的介绍