po3a  

[实验任务一]:围棋

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

实验要求:

1.提交类图;

2.提交源代码;

3.注意编程规范;

4.要求用简单工厂模式和单例模式实现享元工厂类的设计

1.类图

 

2.源代码

复制代码
Coordinates.java
package test13;
//外部状态类——坐标类
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;
    }
}

Chess.java
package test13;

abstract class Chess {
    public abstract String getColor();
    public void locate(Coordinates co) {
        System.out.println(this.getColor()+"棋的位置:"+co.getX()+","+co.getY());
    }
}

ChessFactory.java
package test13;

import java.util.Hashtable;

public class ChessFactory {
    private static ChessFactory instance=new ChessFactory();
    private static Hashtable ht;
    public ChessFactory() {
        ht=new Hashtable();
        Chess black,white;
        black=new BlackChess();
        ht.put("b", black);
        white=new WhiteChess();
        ht.put("w", white);
    }
    public static ChessFactory getInstance() {
        return instance;
    }
    public static Chess getChess(String color) {
        return (Chess)ht.get(color)
;    }
}

BlackChess.java
package test13;
public class BlackChess extends Chess{

    @Override
    public String getColor() {
        return "黑";
    }

}

WhiteChess.java
package test13;

public class WhiteChess extends Chess{

    @Override
    public String getColor() {
        // TODO 自动生成的方法存根
        return "白";
    }

}
Client.java
package test13;

public class Client {

    public static void main(String[] args) {
        Chess black1,black2,black3,white1,white2;
        ChessFactory factory;
        factory = ChessFactory.getInstance();
        black1 = ChessFactory.getChess("b");
        black2 = ChessFactory.getChess("b");
        black3 = ChessFactory.getChess("b");
        white1 = ChessFactory.getChess("w");
        white2 = ChessFactory.getChess("w");
        black1.locate(new Coordinates(1, 1));
        black2.locate(new Coordinates(-4, 6));
        black3.locate(new Coordinates(2, 4));
        white1.locate(new Coordinates(-2, 3));
        white2.locate(new Coordinates(3, 3));
    }
}
复制代码

 

posted on   po3a  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
 
点击右上角即可分享
微信分享提示