11.7日报

完成设计模式实验十三,以下为实验内容:

实验13:享元模式

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

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

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

 
   

 

 

[实验任务一]:围棋

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

实验要求:

1.  提交类图;

 

2.  提交源代码;

  1. // 享元接口
    interface GoStone {
        void display(int x, int y);
    }

    // 白棋享元
    class WhiteGoStone implements GoStone {
        private String color;

        public WhiteGoStone() {
            this.color = "White";
        }

        @Override
        public void display(int x, int y) {
            System.out.println("White stone at (" + x + ", " + y + ")");
        }
    }

    // 黑棋享元
    class BlackGoStone implements GoStone {
        private String color;

        public BlackGoStone() {
            this.color = "Black";
        }

        @Override
        public void display(int x, int y) {
            System.out.println("Black stone at (" + x + ", " + y + ")");
        }
    }

    // 享元工厂(单例模式 + 简单工厂模式)
    class GoStoneFactory {
        private static GoStoneFactory instance = new GoStoneFactory();
        private GoStone whiteStone;
        private GoStone blackStone;

        private GoStoneFactory() {
            whiteStone = new WhiteGoStone();
            blackStone = new BlackGoStone();
        }

        public static GoStoneFactory getInstance() {
            return instance;
        }

        public GoStone getStone(String color) {
            if ("White".equals(color)) {
                return whiteStone;
            } else if ("Black".equals(color)) {
                return blackStone;
            }
            return null;
        }
    }

    // 棋盘类
    class GoBoard {
        public void placeStone(int x, int y, String color) {
            GoStone stone = GoStoneFactory.getInstance().getStone(color);
            stone.display(x, y);
        }
    }

    // 客户端代码
    public class Client {
        public static void main(String[] args) {
            GoBoard board = new GoBoard();
            board.placeStone(1, 1, "White");
            board.placeStone(2, 2, "Black");
            board.placeStone(3, 3, "White");
            // 黑棋和白棋对象只会各创建一次,之后会重复使用
       
    }
    }

 

3.注意编程规范;

posted @ 2024-11-27 10:36  Code13  阅读(9)  评论(0)    收藏  举报