实验十三

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

实验要求:

1.提交类图;

2.提交源代码;

3.注意编程规范;

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

类图

public class BlackChess implements ChessPiece{
    public void display(int x, int y) {
        System.out.println("黑棋显示在位置 (" + x + ", " + y + ")");
    }
}
import java.util.Scanner;

public class ChessFactory {
    static public int color=1;
    static public int x;
    static public int y;
    public static void getChessPiece() {
        while(true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入棋子颜色:1.黑色 2.白色");
            color=sc.nextInt();
            if(color!=1&&color!=2) {
                System.out.println("感谢您的使用");
                break;
            }
            System.out.print("请输入横坐标");
            x=sc.nextInt();
            System.out.print("请输入纵坐标");
            y=sc.nextInt();
            if(color==1) {
                BlackChess black =new BlackChess();
                black.display(x,y);
            }
            else if(color==2){
                WhiteChess white =new WhiteChess();
                white.display(x, y);
            }
        }
    }

}
public interface ChessPiece {
    void display(int x, int y);
}
public class Client {
    public static void main(String[] args) {
        ChessFactory chess = new ChessFactory();
        chess.getChessPiece();
    }
}
public class WhiteChess implements ChessPiece{
    public void display(int x, int y) {
        System.out.println("白棋显示在位置 (" + x + ", " + y + ")");
    }
}

 

posted @ 2023-11-14 14:32  霍普金斯大学丁真  阅读(14)  评论(0)    收藏  举报