scala实现享元模式

package com.linewell.modeldesgin.flyweight

import scala.collection.mutable

/**
* 享元模式
* Created by ctao on 2015/8/29.
*/

/**
* 坐标样例类
* @param x x坐标
* @param y y坐标
*/
case class Coordinates(x: Int, y: Int)

/**
* 抽象享元类
*/
abstract class IgoChessman {
/**
* 获得棋子的颜色
* @return 棋子颜色
*/
def color(): String

/**
* 展示方法
* @param coordinates 坐标样例类
*/
def display(coordinates: Coordinates): Unit = {
/**
* 如果没有颜色就打印没有颜色
*/
if (color() == "没有该颜色的棋子"){
println(color())
}else{
println("棋子颜色:" + color() + "棋子位置:" + coordinates.x + "," + coordinates.y)
}

}
}

/**
* 黑色棋子
*/
object BlackIgoChessman extends IgoChessman {
override def color() = "黑色"
}

/**
* 白色棋子
*/
object WhiteIgoChessman extends IgoChessman {
override def color() = "白色"
}

/**
* 享元工厂类
*/
object IgoChessmanFactory {
/**
* 存放享元对象的HashMap
*/
private val hm = new mutable.HashMap[String, IgoChessman] {}
/**
* 黑色棋子
*/
val black: IgoChessman = BlackIgoChessman
/**
* 白色棋子
*/
val white: IgoChessman = WhiteIgoChessman
hm.put("b", black)
hm.put("w", white)

/**
* 获取棋子
* @param color 颜色
* @return 棋子
*/
def getIgoChessman(color: String): IgoChessman = hm.getOrElse(color, new IgoChessman {
override def color(): String = "没有该颜色的棋子"
})
}

package com.linewell.modeldesgin.flyweight

/**
* 测试客户端
* Created by ctao on 2015/8/29.
*/
object Client extends App {
/**
* 享元工厂
*/
val factory = IgoChessmanFactory
/**
* 黑色棋子1
*/
val black1 = factory.getIgoChessman("b")
/**
* 黑色棋子2
*/
val black2 = factory.getIgoChessman("b")
/**
* 黑色棋子3
*/
val black3 = factory.getIgoChessman("b")
black1.display(Coordinates(1, 2))
black2.display(Coordinates(1, 4))
black3.display(Coordinates(1, 3))

println("判断棋子是否相同:" + black1.eq(black2))


val white1 = factory.getIgoChessman("w")
val white2 = factory.getIgoChessman("w")
white1.display(Coordinates(0,0))
white2.display(Coordinates(1,1))
println("判断棋子是否相同:" + white1.eq(white2))

val error = factory.getIgoChessman("c")
/**
* 错误的请求
*/
error.display(Coordinates(1, 0))


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值