问题描述:
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
类图:
Java代码:
1 //Coordinates.java 2 package shiyan13; 3 //外部状态类——坐标类 4 class Coordinates { 5 6 private int x; 7 private int y; 8 9 public Coordinates(int x,int y) { 10 // TODO Auto-generated constructor stub 11 this.x = x; 12 this.y = y; 13 } 14 15 public int getX() { 16 return x; 17 } 18 19 public void setX(int x) { 20 this.x = x; 21 } 22 23 public int getY() { 24 return y; 25 } 26 27 public void setY(int y) { 28 this.y = y; 29 } 30 } 31 //Chess.java 32 package shiyan13; 33 34 abstract class Chess { 35 public abstract String getColor(); 36 public void locate(Coordinates co) { 37 System.out.println(this.getColor()+"棋的位置:"+co.getX()+","+co.getY()); 38 } 39 } 40 //ChessFactory.java 41 package shiyan13; 42 43 import java.util.Hashtable; 44 45 public class ChessFactory { 46 private static ChessFactory instance=new ChessFactory(); 47 private static Hashtable ht; 48 public ChessFactory() { 49 ht=new Hashtable(); 50 Chess black,white; 51 black=new BlackChess(); 52 ht.put("b", black); 53 white=new WhiteChess(); 54 ht.put("w", white); 55 } 56 public static ChessFactory getInstance() { 57 return instance; 58 } 59 public static Chess getChess(String color) { 60 return (Chess)ht.get(color) 61 ; } 62 } 63 //BlackChess.java 64 package shiyan13; 65 public class BlackChess extends Chess{ 66 67 @Override 68 public String getColor() { 69 // TODO 自动生成的方法存根 70 return "黑"; 71 } 72 73 } 74 //WhiteChess.java 75 package shiyan13; 76 77 public class WhiteChess extends Chess{ 78 79 @Override 80 public String getColor() { 81 // TODO 自动生成的方法存根 82 return "白"; 83 } 84 85 } 86 //Client.java 87 package shiyan13; 88 89 public class Client { 90 91 public static void main(String[] args) { 92 Chess black1,black2,black3,white1,white2; 93 ChessFactory factory; 94 factory = ChessFactory.getInstance(); 95 black1 = ChessFactory.getChess("b"); 96 black2 = ChessFactory.getChess("b"); 97 black3 = ChessFactory.getChess("b"); 98 white1 = ChessFactory.getChess("w"); 99 white2 = ChessFactory.getChess("w"); 100 black1.locate(new Coordinates(5, 5)); 101 black2.locate(new Coordinates(-3, 4)); 102 black3.locate(new Coordinates(3, 1)); 103 white1.locate(new Coordinates(-1, 5)); 104 white2.locate(new Coordinates(2, 4)); 105 } 106 }
运行结果: