Let's say I have an abstract class Drink, and a factory method which chooses the type of Drink (Wine, Beer, etc.) to create at runtime.
Each Drink needs some arguments to properly initialize itself. Some of these are common to all Drinks; for example, they might all require a DrinkConfig argument.
But each Drink may have its own unique requirements too. Maybe Wine needs a Sommelier helper object to initialize itself. Beer doesn't need that, but it may need its own helper objects.
So what should I pass to the factory method? When I call it, I have all the helper objects available, so I could just pass all of them to the factory. But this could end up being a lot of arguments. Is there a better way to design this?
EDIT: Let's assume I can't just create the helper objects in the factory; they're only available from the caller.
The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.
Abstract Factory pattern uses composition to delegate the responsibility of creating an object to another class while Factory Method design pattern uses inheritance and relies on a derived class or subclass to create an object.
The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
The factory method is a creational design pattern, i.e., related to object creation. In the Factory pattern, we create objects without exposing the creation logic to the client and the client uses the same common interface to create a new type of object.
I'd create different overload methods in your factory class.
public class DrinkFactory {
public static Drink CreateBeer(DrinkConfig config, string hops) {
return new Beer(config, hops);
}
public static Drink CreateWine(DrinkConfig config, string grapes, int temperature) {
return new Wine(config, grapes, temperature);
}
}
Edit:
If it's desired to to only have a single method in the Factory class an alternative implementation would be:
public enum DrinksEnum {
Beer,
Wine
}
public class DrinkFactory {
public static Drink CreateDrink(DrinksEnum drinkType, DrinkConfig config) {
switch(drinkType) {
case DrinksEnum.Beer:
return new Beer(config);
case DrinksEnum.Wine:
return new Wine(config);
default:
throw new ApplicationException("Drink type not recognised.");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With