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))


}

你可能感兴趣的:(scala实现设计模式之享元模式)