享元模式

发布时间 2024-01-03 17:30:11作者: Men!

实验13:享元模式

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

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

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

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

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

类图

 源代码

public interface Piece
{
    public String getType();
 
    public void put(int x, int y);
}
 
public class BlackPiece implements Piece
{
    private String type;
 
    public BlackPiece(String type)
    {
        this.type = type;
    }
 
    @Override
    public String getType()
    {
        return this.type;
    }
 
    @Override
    public void put(int x, int y)
    {
        System.out.println("放置了一个:" + this.type + " 坐标为 x:" + x + " y:" + y);
    }
}
 
 
public class WhitePiece implements Piece
{
    private String type;
 
    public WhitePiece(String type)
    {
        this.type = type;
    }
 
    @Override
    public String getType()
    {
        return this.type;
    }
 
    @Override
    public void put(int x, int y)
    {
        System.out.println("放置了一个:" + this.type + " 坐标为 x:" + x + " y:" + y);
    }
}
 
public class PieceFactory
{
    private static Piece blackPiece;
    private static Piece whitePiece;
 
    public Piece getPiece(String shape)
    {
        if ("黑棋".equalsIgnoreCase(shape))
        {
            if (blackPiece == null)
            {
                blackPiece = new BlackPiece(shape);
                System.out.println("创建了一个黑棋");
            }
            return blackPiece;
        } else
        {
            if (whitePiece == null)
            {
                whitePiece = new WhitePiece(shape);
                System.out.println("创建了一个白棋");
            }
            return whitePiece;
        }
    }
}
 
public class Client
{
    public static void main(String[] args)
    {
        PieceFactory pieceFactory = new PieceFactory();
        // 创建一些棋子并放置
        Piece blackPiece1 = pieceFactory.getPiece("黑棋");
        blackPiece1.put(1, 2);
 
        Piece whitePiece1 = pieceFactory.getPiece("白棋");
        whitePiece1.put(3, 4);
 
        Piece blackPiece2 = pieceFactory.getPiece("黑棋");
        blackPiece2.put(5, 6);
 
        Piece blackPiece3 = pieceFactory.getPiece("黑棋");
        blackPiece3.put(1, 1);
 
        Piece whitePiece2 = pieceFactory.getPiece("白棋");
        whitePiece2.put(3, 3);
 
        Piece whitePiece3 = pieceFactory.getPiece("白棋");
        whitePiece3.put(4, 4);
 
        Piece blackPiece4 = pieceFactory.getPiece("黑棋");
        blackPiece4.put(2, 2);
    }
}