在工厂中使用特征 [英] Using traits with a factory

查看:78
本文介绍了在工厂中使用特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在发现scala,我想知道我是否可以在工厂中使用traits.

I'm currently discovering scala and I was wondering if I could use traits with a factory.

我尝试过这个:


abstract class Foo {
  ...
}
object Foo {
  def apply() = new Bar

  private class Bar extends Foo {
    ...
  }
}

Foo() with MyTrait // Not working

我想是因为with必须在new之前.

I guess it's because with must be preceded by new.

那么有什么办法吗?

谢谢

推荐答案

不为时已晚,当apply()方法返回时,实例已经创建.

No it is too late, the instance is already created when the apply() method returns.

您可以做的是使用工厂方法内的特征.下面的代码来自我正在写的一个相当大的代码示例:

What you can do is using the traits inside the factory method. The code below is from a rather big code example I am writing:

object Avatar {
 // Avatar factory method
 def apply(name: String, race: RaceType.Value, character: CharacterType.Value
  ): Avatar = {
    race match {
      case RaceType.Dwarf => {
        character match {
          case CharacterType.Thief => new Avatar(name) with Dwarf with Thief
          case CharacterType.Warrior => new Avatar(name) with Dwarf with Warrior
          case CharacterType.Wizard => new Avatar(name) with Dwarf with Wizard
        }
      }
      case RaceType.Elf => {
        character match {
          case CharacterType.Thief => new Avatar(name) with Elf with Thief
          case CharacterType.Warrior => new Avatar(name) with Elf with Warrior
          case CharacterType.Wizard => new Avatar(name) with Elf with Wizard
        }
      }
    }
  }
}

class Avatar(val name: String) extends Character {
  ...
}

在此代码中,头像的类型(职业和种族)是在工厂根据RaceType和CharacterType枚举确定的.您拥有的是一个工厂,用于各种不同类型或类型组合.

In this code the type (profession and race) of your Avatar is decided in the factory based on the RaceType and CharacterType enumerations. What you have is one factory for all sorts of different types or type combinations.

这篇关于在工厂中使用特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆