设计模式:享元模式案例

让我们以游戏开发中的棋类游戏(例如国际象棋)为例来展示享元模式的代码实现。在这个例子中,棋子的类型是内部状态,而棋子的位置是外部状态。

Java 代码示例

java 复制代码
import java.util.HashMap;
import java.util.Map;

// 享元接口
interface ChessPieceFlyweight {
    void move(int x, int y); // 外部状态:位置
    String getColor(); // 内部状态:颜色
}

// 具体享元类
class ConcreteChessPiece implements ChessPieceFlyweight {
    private final String color; // 内部状态

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

    @Override
    public void move(int x, int y) {
        System.out.printf("Moving %s piece to (%d,%d).\n", color, x, y);
    }

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

// 享元工厂
class ChessPieceFactory {
    private static final Map<String, ChessPieceFlyweight> pieces = new HashMap<>();

    public static ChessPieceFlyweight getChessPiece(String color) {
        if (!pieces.containsKey(color)) {
            ChessPieceFlyweight piece = new ConcreteChessPiece(color);
            pieces.put(color, piece);
        }
        return pieces.get(color);
    }
}

// 客户端代码
public class FlyweightExample {
    public static void main(String[] args) {
        ChessPieceFlyweight whitePiece = ChessPieceFactory.getChessPiece("White");
        ChessPieceFlyweight blackPiece = ChessPieceFactory.getChessPiece("Black");

        // 棋子被多次移动到不同位置,但对象是共享的
        whitePiece.move(1, 2);
        blackPiece.move(2, 3);
        whitePiece.move(4, 5);
        // ... 其他棋子移动操作
    }
}

在这个例子中,ChessPieceFlyweight 接口定义了棋子的外部状态方法 move 和内部状态方法 getColorConcreteChessPiece 类实现了这个接口,并持有内部状态 color,它在棋子的生命周期中是不变的。

ChessPieceFactory 类是享元工厂,它确保同一颜色的棋子只创建一次,并在之后的请求中返回已创建的实例。这样,即使在棋盘上有多个同色棋子,实际上它们都是由同一个享元实例代表的。

客户端代码通过享元工厂获取棋子实例,并多次调用 move 方法来改变棋子的位置,这些位置信息作为外部状态在每次调用时传入。

这个例子展示了享元模式如何在需要大量相似对象的情况下减少内存消耗,通过共享实例来避免重复创建相同或相似的对象。

相关推荐
费费开心一点3 小时前
Java程序设计学习笔记
java·笔记·学习
vvilkim5 小时前
深入理解设计模式:状态模式(State Pattern)
ui·设计模式·状态模式
BD_Marathon7 小时前
MyBatis:配置文件完成增删改查_添加
java·mybatis
程序员JerrySUN7 小时前
深度理解 KVM:Linux 内核系统学习的重要角度
java·linux·学习
编程小白gogogo8 小时前
Student后台管理系统查询接口
java·spring·mybatis
007php0078 小时前
使用LNMP一键安装包安装PHP、Nginx、Redis、Swoole、OPcache
java·开发语言·redis·python·nginx·php·swoole
Mr_Xuhhh9 小时前
Qt窗口(2)-工具栏
java·c语言·开发语言·数据库·c++·qt·算法
续亮~10 小时前
基于Spring AI Alibaba的智能知识助手系统:从零到一的RAG实战开发
java·人工智能·spring·springaialibaba
giao源10 小时前
Spring Boot 整合 Shiro 实现单用户与多用户认证授权指南
java·spring boot·后端·安全性测试
饕餮争锋10 小时前
设计模式笔记_结构型_装饰器模式
笔记·设计模式·装饰器模式