Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // All of these classes implement OrderStrategy
- switch (orderType) {
- case NEW_ORDER: return new NewOrder();
- case CANCELLATION: return new Cancellation();
- case RETURN: return new Return();
- }
- <strategies>
- <order type="NEW_ORDER">com.company.NewOrder</order>
- <order type="CANCELLATION">com.company.Cancellation</order>
- <order type="RETURN">com.company.Return</order>
- </strategies>
- Class strategyType = allStrategies[orderType];
- return runtime.create(strategyType);
- factory.register(NEW_ORDER, NewOrder.class);
- void register(OrderType orderType, Class class)
- {
- allStrategies[orderType] = class;
- }
- public interface IOrderStrategy
- {
- OrderType OrderType { get; }
- }
- public class NewOrder : IOrderStrategy
- {
- public OrderType OrderType { get; } = OrderType.NewOrder;
- }
- public class OrderFactory
- {
- private IEnumerable<IOrderStrategy> _strategies;
- public OrderFactory(IEnumerable<IOrderStrategy> strategies) // Injected by IoC container
- {
- _strategies = strategies;
- }
- public IOrderStrategy Create(OrderType orderType)
- {
- IOrderStrategy strategy = _strategies.FirstOrDefault(s => s.OrderType == orderType);
- if (strategy == null)
- throw new ArgumentException("Invalid order type.", nameof(orderType));
- return strategy;
- }
- }
- enum FactoryType {
- Type1(Type1.class),
- Type2(Type2.class);
- private Class<? extends Type> clazz;
- private FactoryType(Class<? extends Type> clazz) {
- this.clazz = clazz;
- }
- public Class<? extends Type> getTypeClass() {
- return clazz;
- }
- }
- public Type create(FactoryType type) throws Exception {
- return type.getTypeClass().newInstance();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement