享元模式在围棋游戏中的应用分析.doc
文本预览下载声明
享元模式在围棋游戏中的应用分析
摘要:本文应用对象的分析方法对围棋游戏从需求功能分析、对象职责分析、类图的设计以及代码设计几个方面进行阐述,说明了模式享元的使用实例,它有节约存储空间,提高系统性能的优点。
关键词:设计模式;UML
1.引言
Flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度.应用场合很多,本文将用一个实例说明这个模式的具体应用。
围棋系统的分析
围棋的功能说明
围棋中有黑白两种棋子,在程序中每个棋子的属性主要有坐标和颜色。在围棋系统中只需要记录棋盘上每个子的坐标颜色即可,然后通过围棋的算法来计算游戏的输赢。
对象极其职责分配
功能由factory对象、chess对象等合作实现,factory对象负责生产chess,chess对象负责显示和获取棋子,对象的协作图如图所示。
类图设计
根据以上的对象及其职责分析,可以做出类图设计如图所示。
围棋游戏的详细设计
围棋游戏的详细设计代码如下:
class IgoChessmanFactory {
private static IgoChessmanFactory instance = new IgoChessmanFactory();
private static Hashtable ht; //使用Hashtable来存储享元对象,充当享元池
private IgoChessmanFactory() {
ht = new Hashtable();
IgoChessman black,white;
black = new BlackIgoChessman();
ht.put(b,black);
white = new WhiteIgoChessman();
ht.put(w,white);
}
//返回享元工厂类的唯一实例
public static IgoChessmanFactory getInstance() {
return instance;
}
//通过key来获取存储在Hashtable中的享元对象
public static IgoChessman getIgoChessman(String color) {
return (IgoChessman)ht.get(color);
}
}
//围棋棋子类:抽象享元类
abstract class IgoChessman {
public abstract String getColor();
public void display(Coordinates coord){
System.out.println(棋子颜色: + this.getColor() + ,棋子位置: + coord.getX() + , + coord.getY() );
}
}
//白色棋子类:具体享元类
class WhiteIgoChessman extends IgoChessman {
public String getColor() {
return 白色;
}
}
//黑色棋子类:具体享元类
class BlackIgoChessman extends IgoChessman {
public String getColor() {
return 黑色;
}
}
//坐标类:外部状态类
class Coordinates {
private int x;
private int y;
public Coordinates(int x,int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return this.y;
}
public void setY(int y) {
this.y = y;
}
}
//测试程序
public class Chess {
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
IgoChessman black1,black2,black3,white1,white2;
IgoChessmanFactory factory;
//获取享元工厂对象
fact
显示全部