结构型模式 - 享元模式 (Flyweight Pattern)

发布于:2025-02-27 ⋅ 阅读:(20) ⋅ 点赞:(0)

结构型模式 - 享元模式 (Flyweight Pattern)

享元模式是一种结构型设计模式,它通过共享对象来减少内存使用和提高性能,尤其适用于存在大量细粒度对象且这些对象有部分状态可共享的场景。


举个经典案例, 下围棋, 黑子和白子可以用享元,每一颗棋子除了放置的位置之外,只有颜色区分.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 享元接口,定义棋子的放置方法
interface ChessPieceFlyweight {
    String getColor();
}

// 具体享元类,代表黑子和白子
class ConcreteChessPiece implements ChessPieceFlyweight {
    private String color;

    public ConcreteChessPiece(String color) {
        this.color = color;
    }

    @Override
    public String getColor() {
        return color;
    }
}

// 享元工厂类,负责创建和管理享元对象
class ChessPieceFactory {
    private static final Map<String, ChessPieceFlyweight> flyweights = new HashMap<>();

    public static ChessPieceFlyweight getChessPiece(String color) {
        ChessPieceFlyweight flyweight = flyweights.get(color);
        if (flyweight == null) {
            flyweight = new ConcreteChessPiece(color);
            flyweights.put(color, flyweight);
        }
        return flyweight;
    }
}

// 表示棋盘上的位置
class Position {
    private int x;
    private int y;

    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

// 记录棋子及其位置的类
class PlacedChessPiece {
    private ChessPieceFlyweight piece;
    private Position position;

    public PlacedChessPiece(ChessPieceFlyweight piece, Position position) {
        this.piece = piece;
        this.position = position;
    }

    public ChessPieceFlyweight getPiece() {
        return piece;
    }

    public Position getPosition() {
        return position;
    }

    @Override
    public String toString() {
        return piece.getColor() + " 棋子放置在位置 " + position;
    }
}

// 客户端代码
public class GoGameExample {
    public static void main(String[] args) {
        // 存储所有已放置的棋子
        List<PlacedChessPiece> placedPieces = new ArrayList<>();

        // 获取黑子和白子对象
        ChessPieceFlyweight blackPiece = ChessPieceFactory.getChessPiece("黑色");
        ChessPieceFlyweight whitePiece = ChessPieceFactory.getChessPiece("白色");

        // 放置黑子
        Position blackPos1 = new Position(1, 2);
        Position blackPos2 = new Position(3, 4);
        placedPieces.add(new PlacedChessPiece(blackPiece, blackPos1));
        placedPieces.add(new PlacedChessPiece(blackPiece, blackPos2));

        // 放置白子
        Position whitePos1 = new Position(2, 3);
        Position whitePos2 = new Position(4, 5);
        placedPieces.add(new PlacedChessPiece(whitePiece, whitePos1));
        placedPieces.add(new PlacedChessPiece(whitePiece, whitePos2));

        // 输出所有已放置的棋子及其位置
        for (PlacedChessPiece placedPiece : placedPieces) {
            System.out.println(placedPiece);
        }
    }
}