享元模式

📢 本文由 gemini-3-flash-preview 翻譯

Flyweight Pattern 物件結構型模式

意圖

運用共享技術有效地支援大量細粒度的物件。

結構

享元模式

其中:

  • Flyweight 描述一個介面,通過這個介面 Flyweight 可以接受並作用於外部狀態。

  • ConcreteFlyweight 實作 Flyweight 介面,並為內部狀態 (如果有) 增加儲存空間。ConcreteFlyweight 物件必須是可共享的。它所儲存的狀態必須是內部的,即它必須獨立於 ConcreteFlyweight 物件的場景。

  • 並非所有的 Flyweight 子類別都需要被共享。Flyweight 介面使共享成為可能,但它並不強制共享。在 Flyweight 物件結構的某些層次,UnsharedConcreteFlyweight 物件通常將 ConcreteFlyweight 物件作為子節點。

  • FlyweightFactory 建立並管理 Flyweight 物件;確保合理地共享 Flyweight,當使用者請求一個 Flyweight 時,FlyweightFactory 物件提供一個已建立的執行個體,或者在不存在時建立一個執行個體。

  • Client 維持一個對 Flyweight 的參照;計算或儲存一個或多個 Flyweight 的外部狀態。

適用性

Flyweight 模式適用於:

  • 一個應用程式使用了大量的物件。
  • 完全由於使用大量的物件,造成很大的儲存開銷。
  • 物件的大多數狀態都可變為外部狀態。
  • 如果刪除物件的外部狀態,那麼可以用相對較少的共享物件取代很多組物件。
  • 應用程式不依賴於物件識別。由於 Flyweight 物件可以被共享,所以對於概念上明顯有別的物件,識別測試將傳回真值。

範例 1

現要開發一個網路圍棋程式,允許多個玩家連線下棋。由於只有一台伺服器,為節省記憶體空間,採用享元模式實作該程式,類別圖如下:

享元模式-範例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.ArrayList;

enum PieceColor {BLACK, WHITE} // 棋子顏色

class PiecePods{ // 棋子位置
    private int x;
    private int y;

    public PiecePods(int a, int b){
        x = a;
        y = b;
    }

    public int getX(){
        return x;
    }

    public int getY() {
        return y;
    }
}

abstract class Piece{ // 棋子定義
    protected PieceColor m_color; // 顏色
    protected PiecePods m_pos; // 位置

    public Piece(PieceColor color, PiecePods pos){
        this.m_color = color;
        this.m_pos = pos;
    }

    public abstract void draw();
}

class BlackPiece extends Piece{
    public BlackPiece(PieceColor color, PiecePods pos){
        super(color, pos);
    }

    @Override
    public void draw(){
        System.out.println("Draw a black piece");
    }
}

class WhitePiece extends Piece{
    public WhitePiece(PieceColor color, PiecePods pos){
        super(color, pos);
    }

    @Override
    public void draw(){
        System.out.println("Draw a white piece");
    }
}

class PieceBoard{ // 棋盤上已有的棋子
    private static final ArrayList<Piece> m_arrayPiece = new ArrayList<>();
    private String m_blackName; // 黑方名稱
    private String m_whiteName; // 白方名稱

    public PieceBoard(String black, String white){
        m_blackName = black;
        m_whiteName = white;
    }

    // 一步棋,在棋盤上放一顆棋子
    public void setPiece(PieceColor color, PiecePods pos){
        Piece piece = null;

        if(color == PieceColor.BLACK){ // 放黑子
            piece = new BlackPiece(color, pos);
            System.out.println(m_blackName + pos.getX() + pos.getY());
            piece.draw();
        }else{ // 放白子
            piece = new WhitePiece(color, pos);
            System.out.println(m_whiteName + pos.getX() + pos.getY());
            piece.draw();
        }
        m_arrayPiece.add(piece);
    }
}

範例 2

五子棋

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class FlyWeightPattern {
    public static void main(String[] args) {
        PieceFactory factory = new PieceFactory();

        Piece wp1 = factory.getPiece(0);
        wp1.draw(2023, 0527);
    }
}

class PieceFactory{
    private Piece[] pieces = {new WhitePiece(), new BlackPiece()};

    public Piece getPiece(int key){
        if(key == 0) return pieces[0];
        else return pieces[1];
    }
}

abstract class Piece{
    protected String color;

    public abstract void draw(int x, int y);
}

class WhitePiece extends Piece{
    public WhitePiece(){
        this.color = "white";
    }

    @Override
    public void draw(int x, int y){
        System.out.println("draw a " + this.color + " piece x: " + x + " y: " + y);
    }
}

class BlackPiece extends Piece{
    public BlackPiece(){
        this.color = "Black";
    }

    @Override
    public void draw(int x, int y){
        System.out.println("draw a " + this.color + " piece x: " + x + " y: " + y);
    }
}

範例 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class FlyWeightPattern {
    public static void main(String[] args) {
        ShapeFactory sf = new ShapeFactory();

        Random r = new Random();
        String[] colors = {"red", "blue", "green", "white", "black"};

        for (int i = 0; i < 10; i++) {
            int x = r.nextInt(colors.length);
            Shape s = sf.getShape(colors[x]);
            s.draw(r.nextInt(2023), r.nextInt(527));
        }
    }
}

class ShapeFactory{
    private Map<String, Shape> map = new HashMap<>();

    public Shape getShape(String key){
        if (!map.containsKey(key)) {
            map.put(key, new Circle(key));
            System.out.println("create new circle, color: " + key);
        }
        return map.get(key);
    }
}

abstract class Shape{
    protected String color;

    public abstract void draw(int x, int y);
}

class Circle extends Shape{
    public Circle(String color){
        this.color = color;
    }

    @Override
    public void draw(int x, int y) {
        System.out.println("draw a " + this.color + " circle x: " + x + " y: " + y);
    }
}