软件实验设计13
实验13:享元模式
[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
1.BlackPiece.java
1 2 3 4 5 6 7 8 9 10 | package test; public class BlackPiece extends Piece{ @Override public String getColor() { // TODO Auto-generated method stub return "黑棋" ; } } |
2.Client.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package test; public class Client { public static void main(String[]args) { Piece b1,b2,b3,w1,w2,w3; PieceFactory pf; pf=PieceFactory.getInstance(); b1=pf.getPiece( "黑棋" ); b2=pf.getPiece( "黑棋" ); System.out.println( "判断两颗黑棋是否相同:" +(b1==b2)); w1=pf.getPiece( "白棋" ); w2=pf.getPiece( "白棋" ); System.out.println( "判断两颗白棋是否相同:" +(w1==w2)); b1.locate( new Location( "1" , "2" )); b2.locate( new Location( "3" , "2" )); w1.locate( new Location( "10" , "2" )); w2.locate( new Location( "1" , "21" )); } } |
3.Location.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package test; public class Location { private String x; private String y; public Location(String x,String y) { // TODO Auto-generated constructor stub this .x=x; this .y=y; } public String getX() { return x; } public String getY() { return y; } public void setX(String x) { this .x=x; } public void setY(String y) { this .y=y; } } |
4.Piece.java
1 2 3 4 5 6 7 8 9 10 11 | package test; public abstract class Piece { public abstract String getColor(); public void locate(Location lo) { System.out.println( this .getColor()+ " " +lo.getX()+ "," +lo.getY()); } } |
5.PieceFactory.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package test; public class PieceFactory { private static PieceFactory instance= new PieceFactory(); private static Piece wp= new WhitePiece(); private static Piece bp= new BlackPiece(); public PieceFactory() { // TODO Auto-generated constructor stub //instance=new PieceFatory(); //Piece wp=new WhitePiece(); //Piece bp=new BlackPiece(); } public static PieceFactory getInstance() { return instance; } public static Piece getPiece(String color) { if (color.equals( "白棋" )) { return wp; } else { return bp; } } } |
6.WhitePiece.java
1 2 3 4 5 6 7 8 9 10 11 | package test; public class WhitePiece extends Piece{ @Override public String getColor() { // TODO Auto-generated method stub return "白棋" ; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术