实验13:享元模式

发布时间 2024-01-09 15:10:38作者: wardream

 


[实验任务一]:围棋

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

实验要求:

1.  提交类图;

 

 

2.  提交源代码;

package test;

 

public class BlackPiece extends Piece{

    @Override

    public String getColor() {

        // TODO Auto-generated method stub

        return "黑棋";

    }

 

}

 

 

 

package test;

 

public class WhitePiece extends Piece{

 

    @Override

    public String getColor() {

        // TODO Auto-generated method stub

        return "白棋";

    }

 

}

 

 

 

 

package test;

 

public abstract class Piece {

 

    public abstract String getColor();

    public void locate(Location lo) {

 

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

    }

 

}

 

 

 

 

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;

        }

    }

}

 

 

 

 

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;

    }

 

}

 

 

 

 

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.注意编程规范;

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