Scala:注册表设计模式或类似模式?

8

我希望你能帮忙将我的系统从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));
    }
}

Sale和Discount是Item的实现。我在ItemRegistry中使用newInstance方法根据名称获取类。有没有类似的东西可以让我在Scala中完成同样的操作?


是的,你可以在Scala中做类似的事情。你有什么具体的困难吗? - Jan Van den bosch
你能给我指一些例子吗?我很新手Scala..不确定如何开始依赖注入..在Java中我使用Spring来实现。 - user3407267
3个回答

4
其他答案提供以下选项:
  • 直接将您现有的Java代码翻译成Scala。
  • 在Scala中实现另一个版本的现有代码。
  • 使用Spring进行依赖注入。

本答案提供了一种与“注册表模式”不同的方法,它使用编译器而不是字符串或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"
}

让我们定义一个依赖于ItemShopping类。我们可以将这种依赖关系表示为self type:

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

Shopping有一个单一的方法shop,该方法调用其Item上的applyOrdername方法。让我们创建两个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]

编译器要求我们在创建Shopping实例时混入一个Item实现。这种模式使得依赖关系在编译时被强制执行,而且不需要第三方库。请注意保留HTML标签。

3
你不能在运行时打开它们,就像 OP 中的注册表模式一样。 - Rich
你的回答缺少类似于问题中的 final Supplier<Item> supplier = factory.get(alias); 的等效动态查找。 - Raniz
1
蛋糕与这个问题完全没有关系。 蛋糕要求您在编译时知道您想要哪个类和特质。 OP中的“注册表”是一种在运行时决定选择哪个类的方法。 - Rich

2

你可以将Java类翻译成Scala,并且使用与在Java中相同的模式。

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


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中都不太优雅的模式。虽然有时可能会有用。

你能举个例子说明你想要实现什么吗?在什么情况下需要根据运行时值使用不同的工厂?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接