Scala : Registry design pattern or similar?

user3407267 :

I am migrating my system from java to Scala. I have used registry pattern in my java code to get the implementation from the string. Is there any similar thing I could do with scala ? I am new to scala, can someone point to me proper references ?

My java code :

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();
    }
}

My Item interface :

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

    String getItemName();
}

I map the string like :

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));
    }
}

where Sale and Discount are implemntation of Item. I use the newInstance method in ItemRegistry to get the class based on the name. Can some one suggest me any similar thing which can allow me to do the same in scala ?

Jeffrey Chung :

The other answers give the following options:

  • Directly translate your existing Java code to Scala.
  • Implement another version of your existing code in Scala.
  • Use Spring for dependency injection.

This answer offers an approach that is different from the "registry pattern" and that uses the compiler instead of a string, or Spring, to resolve implementations. In Scala, we can use the language constructs to inject dependencies with the cake pattern. Below is an example using simplified versions of your classes:

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"
}

Let's define a class Shopping that depends on an Item. We can express this dependency as a self type:

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

Shopping has a single method, shop, that calls both the applyOrder and name methods on its Item. Let's create two instances of Shopping: one that has a Sale item and one that has a Discount item...

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

...and invoke their respective shop methods:

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]

The compiler requires us to mix in an Item implementation when creating a Shopping instance. We have compile-time enforcement of the dependencies, and we don't need third-party libraries, with this pattern.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=461465&siteId=1