11.13(2)

软件设计                  石家庄铁道大学信息学院

 

实验13:享元模式

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

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

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

 

[实验任务一]:围棋

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

实验要求:

1. 提交类图;

 

2.提交源代码;

package 享元模式;

 

import java.util.*;

 

//坐标类:外部状态类

class Coordinates{

private int x;

private int y;

public Coordinates(int x,int y){

this.x=x;

this.y=y;

}

 

public int getX() {

return x;

}

 

public void setX(int x) {

this.x = x;

}

 

public int getY() {

return y;

}

 

public void setY(int y) {

this.y = y;

}

}

 

 

//围棋棋子类:抽象享元类

abstract class IgoChessman{

public abstract String getColor();

public void locate(Coordinates coord){

System.out.println("棋子颜色:"+this.getColor()+",棋子位置:"+coord.getX()+","+coord.getY());

}

}

 

//黑色棋子类:具体享元类

class BlackIgoChessman extends IgoChessman{

public String getColor(){

return "黑色";

}

}

 

//白色棋子类:具体享元类

class WhiteIgoChessman extends IgoChessman{

public String getColor(){

return "白色";

}

}

 

//围棋棋子工厂类:享元工厂类

class IgoChessmanFactory{

private static IgoChessmanFactory instance = new IgoChessmanFactory();

private static Hashtable hashtable;

 

private IgoChessmanFactory(){

hashtable = new Hashtable();

IgoChessman black,white;

black = new BlackIgoChessman();

hashtable.put("b", black);

white = new WhiteIgoChessman();

hashtable.put("w",white);

}

public static IgoChessmanFactory getInstance(){

return instance;

}

public static IgoChessman getIgoChessman(String color){

return (IgoChessman) hashtable.get(color);

}

}

 

package 享元模式;

 

public class Client {

public static void main(String[] args) {

IgoChessman black1,black2,black3,white1,white2;

black1 = IgoChessmanFactory.getIgoChessman("b");

black2 = IgoChessmanFactory.getIgoChessman("b");

black3 = IgoChessmanFactory.getIgoChessman("b");

System.out.println("判断两颗黑棋是否相同:"+(black1==black2));

white1 = IgoChessmanFactory.getIgoChessman("w");

white2 = IgoChessmanFactory.getIgoChessman("w");

System.out.println("判断两颗白棋是否相同:"+(white1==white2));

black1.locate(new Coordinates(1,2));

black2.locate(new Coordinates(3,4));

black3.locate(new Coordinates(1,3));

white1.locate(new Coordinates(2,4));

white2.locate(new Coordinates(2,5));

 

}

}

3. 注意编程规范;

 

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

 

 

posted @   权衡  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示