享元模式的出发点在于减少创建对象的数量,以减少内存占用和提高性能。防止存在大量对象从而导致内存溢出。
享元模式重视重用现有的同类对象,如果未找到匹配的对象,则创建新对象。如果找到匹配的对象,就直接返回对象。
依据上面所说,那么肯定要用到key-value的存储机制 因此使用hashmap进行存储。
应用的场景:在String中我们会发现如下判断是相等的
String str1 = "ABC";
String str2 = "ABC";
System.out.println(str1==str2);
第二个字符串创建时发现存在相同的字符串常量 就直接返回前一个创建的地址。所以他们的地址是相同的。
实例代码
代码介绍,使用两个对象表示棋盘上的棋子。
//享元类 棋的元素
public interface Chess {
void setColor(String color);
void display(Coordinate coordinate);
}
class ChessDisplay implements Chess{
private String color;
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public void display(Coordinate coordinate) {
System.out.println(color+"棋子的位置是"+coordinate.x+":"+coordinate.y);
}
}
因为位置是不一样的,所以抽离出来
public class Coordinate {
public int x;
public int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
享元工厂类
public class FlyWeightFactory {
private static HashMap<String,Chess> map = new HashMap<>();
public Chess getChess(String color){
Chess chess = map.get(color);
if(chess==null){
chess = new ChessDisplay();
chess.setColor(color);
map.put(color,chess);
}
return chess;
}
}
测试类
public class Client {
public static void main(String[] args) {
FlyWeightFactory flyWeightFactory = new FlyWeightFactory();
Chess black = flyWeightFactory.getChess("black");
Chess black1 = flyWeightFactory.getChess("black");
Chess white = flyWeightFactory.getChess("white");
Chess white1 = flyWeightFactory.getChess("white");
System.out.println(black.toString());
System.out.println(black1.toString());
System.out.println(white.toString());
System.out.println(white1.toString());
black.display(new Coordinate(2,4));
black1.display(new Coordinate(6,8));
white.display(new Coordinate(9,8));
white1.display(new Coordinate(9,10));
}
}
我们发现两颗黑棋的位置是一样的,两颗白棋的位置是一样的。