scalaは設計モードの観察者モードを実現する

17910 ワード

package com.linewell.modeldesgin.observer

import scala.collection.mutable.ArrayBuffer

/**  *        * Created by ctao on 2015/9/2.  *        */ abstract class Observer(var name: String) {
    /**  *          */  def help(): Unit

    /**  *         * @param allControlCenter      */  def beAttacked(allControlCenter: AllControlCenter): Unit
}

/**  *        * @param name     */ class Player(name: String) extends Observer(name) {

    /**  *       */  override def help(): Unit = println(s"${name}")

    /**  *  * @param allControlCenter      */  override def beAttacked(allControlCenter: AllControlCenter): Unit = {
        println(s"${name}   ")
        allControlCenter.notifyObserver(name)
    }
}


/**  *  * @param allyName       */ abstract class AllControlCenter(allyName: String) {

    /**  *        */  protected var players = new ArrayBuffer[Observer]()


    /**  *        * @param observer      */  def join(observer: Observer):Unit = observer match {
        case o if players.exists(_.eq(o)) => println(s"${o.name}   ${allyName}  ")
        case o: Observer => println(s"${o.name}  ${allyName}  ")
            players += observer
        case _ => println("  ")
    }

    /**  *        * @param observer      */  def quit(observer: Observer):Unit = observer match {
        case o if players.exists(o.eq(_)) => println(s"${o.name}  ${allyName}  ")
            players -= observer
        case o if !players.exists(_.eq(o)) => println(s"${o.name}   ${allyName}  ")
        case _ => println("  ")
    }

    /**  *       * @param oName        */  def notifyObserver(oName: String): Unit
}

/**  *        * @param name      */ class ConcreteAllyControlCenter(name: String) extends AllControlCenter(name) {
    override def notifyObserver(oName: String): Unit = oName match {
        case o if players.exists(_.name == o) => println(s"${name}${oName}    ")
            players.filterNot(_.name == oName).foreach(_.help())
        case _ => println(s"$oName${name}")
    }

}


package com.linewell.modeldesgin.observer

/**  *        * Created by ctao on 2015/9/2.  */ object Client extends App {
    /**  *     */  val acc: AllControlCenter = new ConcreteAllyControlCenter("justSo")

    /**  *        */  val play1: Observer = new Player("a")
    val play2: Observer = new Player("b")
    val play3: Observer = new Player("c")
    val play4: Observer = new Player("d")
    val play5: Observer = new Player("e")
    /**  *  *     */  acc.join(play1)
    acc.join(play2)
    acc.join(play3)
    acc.join(play3)
    acc.join(play4)
    acc.join(play5)
    acc.quit(play1)
    acc.quit(play1)

    play1.beAttacked(acc)
}