Scala:注册表设计模式还是类似的?

时间:2017-08-28 04:53:14

标签: java scala design-patterns

我正在将我的系统从java迁移到Scala。我在我的java代码中使用了注册表模式来从字符串中获取实现。 scala有什么类似的事情吗?我是scala的新手,有人能指出我适当的参考资料吗?

我的java代码:

public class ItemRegistry {

    private final Map<String, ItemFactory> factoryRegistry;

    public ItemRegistry() {
        this.factoryRegistry = new HashMap<>();
    }

    public ItemRegistry(List<ItemFactory> factories) {
        factoryRegistry = new HashMap<>();
        for (ItemFactory factory : factories) {
            registerFactory(factory);
        }
    }

    public void registerFactory(ItemFactory factory) {
        Set<String> aliases = factory.getRegisteredItems();
        for (String alias : aliases) {
            factoryRegistry.put(alias, factory);
        }
    }

    public Item newInstance(String itemName) throws ItemException {
        ItemFactory factory = factoryRegistry.get(itemName);
        if (factory == null) {
            throw new ItemException("Unable to find factory containing alias " + itemName);
        }
        return factory.getItem(itemName);
    }

    public Set<String> getRegisteredAliases() {
        return factoryRegistry.keySet();
    }
}

我的项目界面:

public interface Item {
    void apply(Order Order) throws ItemException;

    String getItemName();
}

我将字符串映射为:

public interface ItemFactory {

    Item getItem(String itemName) throws ItemException;

    Set<String> getRegisteredItems();
}


public abstract class AbstractItemFactory implements ItemFactory {


    protected final Map<String, Supplier<Item>> factory = Maps.newHashMap();

    @Override
    public Item getItem(String alias) throws ItemException {
        try {
            final Supplier<Item> supplier = factory.get(alias);
            return supplier.get();
        } catch (Exception e) {
            throw new ItemException("Unable to create instance of " + alias, e);
        }
    }

    protected Supplier<Item> defaultSupplier(Class<? extends Item> itemClass) {
        return () -> {
            try {
                return itemClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Unable to create instance of " + itemClass, e);
            }
        };
    }

    @Override
    public Set<String> getRegisteredItems() {
        return factory.keySet();
    }
}

public class GenericItemFactory extends AbstractItemFactory {

    public GenericItemFactory() {
        factory.put("reducedPriceItem",  () -> new Discount(reducedPriceItem));
        factory.put("salePriceItem",  () -> new Sale(reducedPriceItem));
    }
}

销售和折扣是物品的实施。我使用ItemRegistry中的newInstance方法根据名称获取类。有人可以建议我任何类似的事情可以让我在scala中做同样的事情吗?

3 个答案:

答案 0 :(得分:3)

其他答案提供以下选项:

  • 直接将现有Java代码翻译为Scala。
  • 在Scala中实现现有代码的另一个版本。
  • 使用Spring进行依赖注入。

这个答案提供的方法不同于注册表模式&#34;并使用编译器而不是字符串或Spring来解析实现。在Scala中,我们可以使用语言结构向cake pattern注入依赖项。下面是使用类的简化版本的示例:

case class Order(id: Int)

trait Item {
  // renamed to applyOrder to disambiguate it from apply(), which has special use in Scala
  def applyOrder(order: Order): Unit 
  def name: String
}

trait Sale extends Item {
  override def applyOrder(order: Order): Unit = println(s"sale on order[${order.id}]")
  override def name: String = "sale"
}

trait Discount extends Item {
  override def applyOrder(order: Order): Unit = println(s"discount on order[${order.id}]")
  override def name: String = "discount"
}

让我们定义一个取决于Shopping的班级Item。我们可以将此依赖关系表示为self type

class Shopping { this: Item =>
  def shop(order: Order): Unit = {
    println(s"shopping with $name")
    applyOrder(order)
  }
}

Shopping有一种方法shop,可以调用applyOrder上的nameItem方法。让我们创建两个Shopping实例:一个具有Sale项且一个具有Discount项目的实例...

val sale = new Shopping with Sale
val discount = new Shopping with Discount

...并调用各自的shop方法:

val order1 = new Order(123)
sale.shop(order1)
// prints:
//   shopping with sale
//   sale on order[123]

val order2 = new Order(456)
discount.shop(order2)
// prints:
//   shopping with discount
//   discount on order[456]

编译器要求我们在创建Item实例时混合使用Shopping实现。我们有依赖项的编译时执行,我们不需要第三方库,这种模式。

答案 1 :(得分:2)

您几乎可以将Java类转换为Scala,并使用与您在Java中完全相同的模式。

由于Scala在JVM上运行,因此您也可以将它与Spring一起使用。它可能不是在Scala中编写服务的“标准”方式,但它绝对是一个可行的选择。

答案 2 :(得分:0)

正如其他人已经建议的那样,您可以直接将代码转换为Scala,而无需更改设计模式,如果这是您想要的。

这可能是这样的:

import scala.collection.Set
import scala.collection.mutable
import scala.collection.immutable

trait Item

trait ItemFactory {
  def registeredItems: Set[String]
  def getItem(alias: String): Item
}

class ItemRegistry(factories: List[ItemFactory]) {

  final private val factoryRegistry = mutable.Map[String, ItemFactory]()

  factories.foreach(this.registerFactory)

  def registerFactory(factory: ItemFactory): Unit = {
    factory.registeredItems.foreach(alias =>
      factoryRegistry.put(alias, factory))
  }

  def newInstance(itemName: String): Item = {
    val factory = this.factoryRegistry.get(itemName)
        .getOrElse(throw new Exception("Unable to find factory containing alias " + itemName))
    factory.getItem(itemName)
  }

  def getRegisteredAliases: Set[String] = this.factoryRegistry.keySet
}

我建议这在Java和Scala中都是一个笨重的模式。它可能不时有用。 你能举个例子来说明你想要实现的目标吗?什么时候需要根据运行时值使用不同的工厂?

相关问题