加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala中的策略更可取:对象或特征

发布时间:2020-12-16 10:02:37 所属栏目:安全 来源:网络整理
导读:我通常使用特征来实现策略(一些不需要附带字段的动作).最近我发现可以根据对象定义相同的功能.它们可能直接扩展功能特性或扩展一些特性,除了apply()之外还定义了特殊方法 示例代码: /* strategy realization via traits */package object Traitness { trait
我通常使用特征来实现策略(一些不需要附带字段的动作).最近我发现可以根据对象定义相同的功能.它们可能直接扩展功能特性或扩展一些特性,除了apply()之外还定义了特殊方法

示例代码:

/* strategy realization via traits */
package object Traitness {
  trait Strategy {
    def performAction() : Unit = ()
  }
  abstract class Usage {_ : Strategy =>
  def doWork() =
    this.performAction()
  }

  // defining strategies
  trait SayA extends Strategy {
    override def performAction() = {
      println("A")
      super.performAction()
    }
  }

  trait SayB extends Strategy {
    override def performAction() = {
      println("B")
      super.performAction()
    }
  }

  trait SayC extends Strategy {
    override def performAction() = {
      println("C")
      super.performAction()
    }
  }

  //using strategies
  class SimpleStrategy extends Usage with SayA
  def reverSEOrder() = new Usage with SayC with SayA
  object fullUsage extends Usage with SayA with SayB with SayC

  //run-time checking
  val check1 : Boolean = (new SimpleStrategy).isInstanceOf[SayB]
  val check2 : Boolean = reverSEOrder().isInstanceOf[SayB]
  val check3 : Boolean = fullUsage.isInstanceOf[SayB]

  //compile-time checking
  def proclaim(x : SayB) = println("SayB")
}

/* strategy realization via function objects */
package object Valueness {
  trait Strategy extends Function0[Unit]

  class Usage(val strategies : List[Strategy]) {
    def doWork() = for (s <- strategies)
      s()
  }

  //defining strategies
  object SayA extends Strategy {
    override def apply() = {
      println("A")
    }
  }

  object SayB extends Strategy {
    override def apply() = {
      println("B")
    }
  }

  object SayC extends Strategy {
    override def apply() = {
      println("C")
    }
  }

  //using strategies
  class SimpleStrategy extends Usage(SayA :: Nil)
  def reverSEOrder() = new Usage(SayB :: SayA :: Nil)
  val fullUsage = new Usage(SayA :: SayB :: SayC :: Nil)

  //run-time checking
  def check(strategy : Strategy,usage : Usage) = usage.strategies contains strategy
  val check1 : Boolean = check(SayB,new SimpleStrategy)
  val check2 : Boolean = check(SayB,reverSEOrder())
  val check3 : Boolean = check(SayB,fullUsage)

  //no compile-time checking available
}

我应该选择哪一个?

解决方法

在您描述的用例中,使用特征或对象是不必要的面向对象的过度杀伤.您的策略只是功能,并且可以最干净地实施.

object Strategy{

  type Strategy = () => Unit

  val sayA:Strategy = ()=>{println("A")}
  val sayB:Strategy = ()=>{println("B")}
  val sayC:Strategy = ()=>{println("C")}
}

在这里创建Function0 [Unit]的子类只是不会给你买任何东西,并且使你有能力制作琐碎的文字.函数是Scala中非常好的实体.对它们感到舒服,并且不要犹豫直接使用它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读