软件实验设计13

实验13:享元模式

[实验任务一]:围棋

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

1.BlackPiece.java

package test;

public class BlackPiece extends Piece{
    @Override
    public String getColor() {
        // TODO Auto-generated method stub
        return "黑棋";
    }

}

 2.Client.java

package test;

public class Client {

    public static void main(String[]args) {
        Piece b1,b2,b3,w1,w2,w3;
        PieceFactory pf;
        pf=PieceFactory.getInstance();
        b1=pf.getPiece("黑棋");
        b2=pf.getPiece("黑棋");
        System.out.println("判断两颗黑棋是否相同:"+(b1==b2));

        w1=pf.getPiece("白棋");
        w2=pf.getPiece("白棋");
        System.out.println("判断两颗白棋是否相同:"+(w1==w2));
        b1.locate(new Location("1","2"));
        b2.locate(new Location("3","2"));
        w1.locate(new Location("10","2"));
        w2.locate(new Location("1","21"));
    }
}

  3.Location.java

package test;

public class Location {

    private String x;
    private String y;
    public Location(String x,String y) {
        // TODO Auto-generated constructor stub
        this.x=x;
        this.y=y;
    }
    public String getX() {
        return x;
    }
    public String getY() {
        return y;
    }
    public void setX(String x) {
        this.x=x;
    }
    public void setY(String y) {
        this.y=y;
    }

}

  4.Piece.java

package test;

public abstract class Piece {

    public abstract String getColor();
    public void locate(Location lo) {

        System.out.println(this.getColor()+" "+lo.getX()+","+lo.getY());
    }

}

  5.PieceFactory.java

package test;

public class PieceFactory {

    private static PieceFactory instance=new PieceFactory();
    private static Piece wp=new WhitePiece();
    private static Piece bp=new BlackPiece();
    public PieceFactory() {
        // TODO Auto-generated constructor stub
        //instance=new PieceFatory();
        //Piece wp=new WhitePiece();
        //Piece bp=new BlackPiece();
    }
    public static PieceFactory getInstance() {
        return instance;
    }

    public static Piece getPiece(String color) {
        if(color.equals("白棋")) {
            return wp;
        }else {
            return bp;
        }
    }
}

  6.WhitePiece.java

package test;

public class WhitePiece extends Piece{

    @Override
    public String getColor() {
        // TODO Auto-generated method stub
        return "白棋";
    }

}

  

posted @ 2022-10-18 16:08  Lindseyyip  阅读(30)  评论(0)    收藏  举报