軟體設計模式————(享元模式)

财神给你送元宝發表於2024-11-21

[實驗任務一]:圍棋

設計一個圍棋軟體,在系統中只存在一個白棋物件和一個黑棋物件,但是它們可以在棋盤的不同位置顯示多次。

實驗要求:

1.提交類圖;

2.提交原始碼;

import java.util.*;

//座標類:外部狀態類
class Coordinates{
    private int x;
    private int y;
    public Coordinates(int x,int y){
        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;
    }
}


//圍棋棋子類:抽象享元類
abstract class IgoChessman{
    public abstract String getColor();
    public void locate(Coordinates coord){
        System.out.println("棋子顏色:"+this.getColor()+",棋子位置:"+coord.getX()+","+coord.getY());
    }
}

//黑色棋子類:具體享元類
class BlackIgoChessman extends IgoChessman{
    public String getColor(){
        return "黑色";
    }
}

//白色棋子類:具體享元類
class WhiteIgoChessman extends IgoChessman{
    public String getColor(){
        return "白色";
    }
}

//圍棋棋子工廠類:享元工廠類
class IgoChessmanFactory{
    private static IgoChessmanFactory instance = new IgoChessmanFactory();
    private static Hashtable hashtable;

    private IgoChessmanFactory(){
        hashtable = new Hashtable();
        IgoChessman black,white;
        black = new BlackIgoChessman();
        hashtable.put("b", black);
        white = new WhiteIgoChessman();
        hashtable.put("w",white);
    }
    public static IgoChessmanFactory getInstance(){
        return instance;
    }
    public static IgoChessman getIgoChessman(String color){
        return (IgoChessman) hashtable.get(color);
    }
}

public class Client {
    public static void main(String[] args) {
        IgoChessman black1,black2,black3,white1,white2;
        black1 = IgoChessmanFactory.getIgoChessman("b");
        black2 = IgoChessmanFactory.getIgoChessman("b");
        black3 = IgoChessmanFactory.getIgoChessman("b");
        System.out.println("判斷兩顆黑棋是否相同:"+(black1==black2));
        white1 = IgoChessmanFactory.getIgoChessman("w");
        white2 = IgoChessmanFactory.getIgoChessman("w");
        System.out.println("判斷兩顆白棋是否相同:"+(white1==white2));
        black1.locate(new Coordinates(1,2));
        black2.locate(new Coordinates(3,4));
        black3.locate(new Coordinates(1,3));
        white1.locate(new Coordinates(2,4));
        white2.locate(new Coordinates(2,5));

    }
}

3.注意程式設計規範;

4.要求用簡單工廠模式和單例模式實現享元工廠類的設計

相關文章