本次實驗屬於模仿型實驗,透過本次實驗學生將掌握以下內容:
1、理解享元模式的動機,掌握該模式的結構;
2、能夠利用享元模式解決實際問題。
[實驗任務一]:圍棋
設計一個圍棋軟體,在系統中只存在一個白棋物件和一個黑棋物件,但是它們可以在棋盤的不同位置顯示多次。
實驗要求:
1.提交類圖;
2.提交原始碼;
3.注意程式設計規範;
4.要求用簡單工廠模式和單例模式實現享元工廠類的設計。
1、類圖
原始碼
package org.example;
class BlackIgoChessman extends IgoChessman{
@Override
public String getColor() {
// TODO Auto-generated method stub
return "黑色";
}
}
package org.example;
public class Client {
public static void main(String[] args) {
IgoChessman black1,black2,black3,white1,white2;
IgoChessmanFactory factory;
factory = IgoChessmanFactory.getInstance();
black1 = factory.getIgoChessman("b");
black2 = factory.getIgoChessman("b");
black3 = factory.getIgoChessman("b");
System.out.println("判斷兩顆黑棋是否相同:"+(black1==black2));
white1 = factory.getIgoChessman("w");
white2 = factory.getIgoChessman("w");
System.out.println("判斷兩顆白棋是否相同:"+(white1==white2));
black1.locate(new Coordinates(1, 1));
black2.locate(new Coordinates(2, 4));
black3.locate(new Coordinates(2, 3));
white1.locate(new Coordinates(3, 5));
white2.locate(new Coordinates(2, 6));
}
}
package org.example;
public class Coordinates {
private int x;
private int y;
public Coordinates(int x,int y) {
// TODO Auto-generated constructor stub
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
package org.example;
public abstract class IgoChessman {
public abstract String getColor();
public void locate(Coordinates coord){
System.out.println("棋子顏色:"+this.getColor()+",棋子位置:"+coord.getX()+","+coord.getY());
}
}
package org.example;
import java.util.Hashtable;
public class IgoChessmanFactory {
private static IgoChessmanFactory instance = new IgoChessmanFactory();
private static Hashtable ht;
public IgoChessmanFactory() {
// TODO Auto-generated constructor stub
ht = new Hashtable();
IgoChessman black,white;
black = new BlackIgoChessman();
ht.put("b", black);
white = new WhiteIgoChessman();
ht.put("w", white);
}
public static IgoChessmanFactory getInstance(){
return instance;
}
public static IgoChessman getIgoChessman(String color){
return (IgoChessman)ht.get(color);
}
}
package org.example;
class WhiteIgoChessman extends IgoChessman{
@Override
public String getColor() {
// TODO Auto-generated method stub
return "白色";
}
}
3、執行截圖