享元模式的理解

享元模式的出發點在於減少創建對象的數量,以減少內存佔用和提高性能。防止存在大量對象從而導致內存溢出。

享元模式重視重用現有的同類對象,如果未找到匹配的對象,則創建新對象。如果找到匹配的對象,就直接返回對象。

依據上面所說,那麼肯定要用到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));

    }
}

我們發現兩顆黑棋的位置是一樣的,兩顆白棋的位置是一樣的。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章