Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. // All of these classes implement OrderStrategy
  2. switch (orderType) {
  3. case NEW_ORDER: return new NewOrder();
  4. case CANCELLATION: return new Cancellation();
  5. case RETURN: return new Return();
  6. }
  7.  
  8. <strategies>
  9. <order type="NEW_ORDER">com.company.NewOrder</order>
  10. <order type="CANCELLATION">com.company.Cancellation</order>
  11. <order type="RETURN">com.company.Return</order>
  12. </strategies>
  13.  
  14. Class strategyType = allStrategies[orderType];
  15. return runtime.create(strategyType);
  16.  
  17. factory.register(NEW_ORDER, NewOrder.class);
  18.  
  19. void register(OrderType orderType, Class class)
  20. {
  21. allStrategies[orderType] = class;
  22. }
  23.  
  24. public interface IOrderStrategy
  25. {
  26. OrderType OrderType { get; }
  27. }
  28.  
  29. public class NewOrder : IOrderStrategy
  30. {
  31. public OrderType OrderType { get; } = OrderType.NewOrder;
  32. }
  33.  
  34. public class OrderFactory
  35. {
  36. private IEnumerable<IOrderStrategy> _strategies;
  37.  
  38. public OrderFactory(IEnumerable<IOrderStrategy> strategies) // Injected by IoC container
  39. {
  40. _strategies = strategies;
  41. }
  42.  
  43. public IOrderStrategy Create(OrderType orderType)
  44. {
  45. IOrderStrategy strategy = _strategies.FirstOrDefault(s => s.OrderType == orderType);
  46.  
  47. if (strategy == null)
  48. throw new ArgumentException("Invalid order type.", nameof(orderType));
  49.  
  50. return strategy;
  51. }
  52. }
  53.  
  54. enum FactoryType {
  55. Type1(Type1.class),
  56. Type2(Type2.class);
  57.  
  58. private Class<? extends Type> clazz;
  59.  
  60. private FactoryType(Class<? extends Type> clazz) {
  61. this.clazz = clazz;
  62. }
  63.  
  64. public Class<? extends Type> getTypeClass() {
  65. return clazz;
  66. }
  67. }
  68.  
  69. public Type create(FactoryType type) throws Exception {
  70. return type.getTypeClass().newInstance();
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement