设计模式:享元模式案例

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

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 方法来改变棋子的位置,这些位置信息作为外部状态在每次调用时传入。

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

相关推荐
b***666114 小时前
Spring Boot 整合 Apollo 配置中心实战
java·spring boot·后端
CoderYanger14 小时前
递归、搜索与回溯-综合练习:27.黄金矿工
java·算法·leetcode·深度优先·1024程序员节
vx_vxbs6614 小时前
【SSM高校普法系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
android·java·python·mysql·小程序·php·idea
张较瘦_14 小时前
Springboot3 | ResponseEntity 完全使用教程
java·springboot·开发
毕设源码-郭学长14 小时前
【开题答辩全过程】以 高校兼职系统为例,包含答辩的问题和答案
java·spring boot
黄嚯嚯14 小时前
Jackson 多态反序列化详解:基于字段自动选择子类的优雅方案
java
h***381814 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端
一只乔哇噻14 小时前
java后端工程师+AI大模型进修ing(研一版‖day57)
java·开发语言·人工智能·算法·语言模型
十五喵14 小时前
智慧物业|物业管理|基于SprinBoot+vue的智慧物业管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·智慧物业管理系统
Williams1014 小时前
Java POI/Excel工具:终结OOM、精度丢失和i18n三大难题
java·开发语言·excel