设计模式--享元模式

实验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);
    }
}

运行效果

 

 

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值