当前位置: 首页 > news >正文

设计模式:享元模式案例

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

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;}@Overridepublic void move(int x, int y) {System.out.printf("Moving %s piece to (%d,%d).\n", color, x, y);}@Overridepublic 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 方法来改变棋子的位置,这些位置信息作为外部状态在每次调用时传入。

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

http://www.lryc.cn/news/333736.html

相关文章:

  • pandas(day5)
  • 如何注册midjourney账号
  • 探索数据结构:特殊的双向队列
  • 16_I2C库函数
  • 十八、Rust gRPC 多 proto 演示
  • 【Linux】Linux64位环境下编译32位报错skipping incompatible的解决办法
  • vue指令v-model
  • CentOS安装MySQL数据库
  • 从B2B转向B2B2C模式:工业品牌史丹利百得的转型历程
  • Redis群集模式和rsync远程同步
  • JAVA—抽象—定义抽象类Converter及其子类WeightConverter
  • 面对复杂多变的网络攻击,企业应如何守护网络安全
  • 计算机网络练习-计算机网络概述与性能指标
  • vite vue3 ts import.meta在vscode中报错
  • Java synchronized(详细)
  • 算法设计与分析实验报告python实现(排序算法、三壶谜题、交替放置的碟子、带锁的门)
  • 实训问题总结——ajax用get可以成功调用controller方法,用POST就出404错误
  • 1、认识MySQL存储引擎吗?
  • 微信小程序媒体查询
  • 前端(动态雪景背景+动态蝴蝶)
  • 软考-系统集成项目管理中级-新一代信息技术
  • 【卷积神经网络进展】
  • yarn的安装和使用
  • Golang | Leetcode Golang题解之第10题正则表达式匹配
  • 【Leetcode】top 100 图论
  • 【沈阳航空航天大学】 <C++ 类与对象计分作业>
  • Vue3 自定义指令Custom Directives
  • 蓝桥杯 【日期统计】【01串的熵】
  • CSP201409T5拼图
  • mongoDB 优化(2)索引