今日报告
完成了软件设计实验13
实验13:享元模式
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
要求用简单工厂模式和单例模式实现享元工厂类的设计。
GoPiece.java
public class GoPiece { private String color; public GoPiece(String color) { this.color = color; } public void display(int x, int y) { System.out.println("Displaying " + color + " piece at position (" + x + ", " + y + ")"); } }
GoPieceFactory.java
public class GoPieceFactory { private static GoPiece whitePiece; private static GoPiece blackPiece; private GoPieceFactory() { // 私有构造函数,防止外部实例化 } public static GoPiece getWhitePiece() { if (whitePiece == null) { whitePiece = new GoPiece("White"); } return whitePiece; } public static GoPiece getBlackPiece() { if (blackPiece == null) { blackPiece = new GoPiece("Black"); } return blackPiece; } }
GoGame.java
public class GoGame { public static void main(String[] args) { // 使用享元工厂获取白棋和黑棋对象 GoPiece whitePiece1 = GoPieceFactory.getWhitePiece(); GoPiece blackPiece1 = GoPieceFactory.getBlackPiece(); // 在不同位置显示多次 whitePiece1.display(2, 3); blackPiece1.display(4, 5); // 创建第二个白棋对象并在不同位置显示 GoPiece whitePiece2 = GoPieceFactory.getWhitePiece(); whitePiece2.display(6, 7); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南