2024/11/12

软件设计 实验13:享元模式

设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。

 

 

public 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;
    }
}

public abstract class IgoChessman {
    public abstract String getColor();
    public void locate(Coordinates coord){
        System.out.println("棋子颜色:"+this.getColor()+",棋子位置:"+coord.getX()+","+coord.getY());
    }
}

public class BlackIgoChessman extends IgoChessman{
    @Override
    public String getColor() {
        return "黑";
    }
}

public class WhiteIgoChessman extends IgoChessman{
    @Override
    public String getColor() {
        return "白";
    }
}

public 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 App
{
    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(2,2));
        black2.locate(new Coordinates(3,4));
        black3.locate(new Coordinates(2,3));
        white1.locate(new Coordinates(6,4));
        white2.locate(new Coordinates(4,5));
    }
}

 

posted @ 2024-11-12 08:54  伐木工熊大  阅读(7)  评论(0)    收藏  举报