scala设计模式--观察者模式

观察者模式

/**
  * 封装消息
  *
  * @param oder
  * @param num
  * @param weapon
  */
case class Message(oder: String, num: Int, weapon: String)

/**
  * 被观察者(上级) 拥有注册,移除,通知的方法
  */
trait Leader {
  def registerSoldier(s: Soldier)

  def removeSoldier(s: Soldier)

  def notifySoldier: Unit
}

/**
  * 被观察者(班长)
  */
class Monitor extends Leader {
  private var mess: Message = _
  private val soldiers = new util.ArrayList[Soldier]()

  def receiveOrder(mess: Message) = {
    this.mess = mess; notifySoldier
  }

  override def registerSoldier(s: Soldier): Unit = {
    soldiers.add(s)
  }

  override def removeSoldier(s: Soldier): Unit = {
    soldiers.remove(s)
  }

  override def notifySoldier: Unit = {
    import scala.collection.JavaConversions._
    soldiers.map(x=>{
      x.message=this.mess
      x.toDO()
    })
  }
}
/**
  * 士兵 特质
  */
trait Soldier {

  val soldierId:String
  var message: Message = _
  
  def toDO(): Unit = {
    println(soldierId+"收到信息:")
    println("敌人数量:" + message.num)
    println("敌人装备:" + message.weapon)
    println("命令:" + message.oder)
    println("-------------------->")
  }
}

/**
  * 士兵实体类1,2,3
  */
class Soldier1 extends Soldier{
  override val soldierId: String = "9527"
}
class Soldier2 extends Soldier{
  override val soldierId: String = "9528"
}
class Soldier3 extends Soldier{
  override val soldierId: String = "9529"
}

/**
  * 客户端
  */

object Client22 {
  def main(args: Array[String]): Unit = {

    val monitor = new Monitor
    val soldier1 = new Soldier1
    val soldier2 = new Soldier2
    val soldier3 = new Soldier3

    monitor.registerSoldier(soldier1)
    monitor.registerSoldier(soldier2)
    monitor.registerSoldier(soldier3)

    monitor.receiveOrder(Message("冲锋!!", 13, "大刀"))

    println("<========打扫战场======移除9527==========================>")

    monitor.removeSoldier(soldier1)
    monitor.receiveOrder(Message("9527挂了",0,""))


  }
}

执行结果

9527收到信息:
敌人数量:13
敌人装备:大刀
命令:冲锋!!
-------------------->
9528收到信息:
敌人数量:13
敌人装备:大刀
命令:冲锋!!
-------------------->
9529收到信息:
敌人数量:13
敌人装备:大刀
命令:冲锋!!
-------------------->
<========打扫战场======移除9527==========================>
9528收到信息:
敌人数量:0
敌人装备:
命令:9527挂了
-------------------->
9529收到信息:
敌人数量:0
敌人装备:
命令:9527挂了
-------------------->

Process finished with exit code 0

你可能感兴趣的:(设计模式--scala)