每日总结

 

 

实验13:享元模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解享元模式的动机,掌握该模式的结构;

2、能够利用享元模式解决实际问题。

 

[实验任务一]:围棋

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

实验要求:

1. 提交类图;

 

2.提交源代码;

public class BlackPiece extends Piece{

    @Override

    public String getColor() {

        // TODO Auto-generated method stub

        return "黑棋";

    }

 

}

 

 

 

 

public class WhitePiece extends Piece{

 

    @Override

    public String getColor() {

        // TODO Auto-generated method stub

        return "白棋";

    }

 

}

 

 

 

 

 

public abstract class Piece {

 

    public abstract String getColor();

    public void locate(Location lo) {

 

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

    }

 

}

 

 

 

 

 

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;

        }

    }

}

 

 

 

 

 

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;

    }

 

}

 

 

 

 

 

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.要求用简单工厂模式和单例模式实现享元工厂类的设计

 

 

posted @ 2024-11-21 23:11  *太¥^白%  阅读(28)  评论(0)    收藏  举报