Evgenii Legotckoi
17 сентября 2018 г. 19:47

Пример - Абстрактная фабрика на Java

Содержание

Классы Абстрактных фабрик часто реализуются с помощью фабричных методов, но они также могут быть реализованы с использованием Prototype. Абстрактная фабрика может хранить набор прототипов, из которых можно клонировать и возвращать объекты.

  • Factory Method: создание через наследование.
  • Prototype: создание через делегирование.
  • Виртуальный конструктор: отложить выбор объекта для создания до времени выполнения.

  1. class Expression implements Cloneable{
  2. public String str;
  3.  
  4. public Expression(String str) {
  5. this.str = str;
  6. }
  7.  
  8. @Override
  9. public Expression clone() {
  10. Expression clone = null;
  11. try {
  12. clone = (Expression)super.clone();
  13. } catch (CloneNotSupportedException ex) {
  14. ex.printStackTrace();
  15. }
  16. return clone;
  17. }
  18.  
  19. @Override
  20. public String toString() {
  21. return str;
  22. }
  23. }
  24.  
  25. abstract class AbstractFactory {
  26. public Expression prototype;
  27.  
  28. public Expression makePhase() {
  29. return prototype.clone();
  30. }
  31.  
  32. public abstract Expression makeCompromise();
  33.  
  34. public abstract Expression makeGrade();
  35. }
  36.  
  37. class PCFactory extends AbstractFactory {
  38.  
  39. public PCFactory() {
  40. prototype = new PCPhase();
  41. }
  42.  
  43. @Override
  44. public Expression makeCompromise() {
  45. return new Expression("\"do it your way, any way, or no way\"");
  46. }
  47.  
  48. @Override
  49. public Expression makeGrade() {
  50. return new Expression("\"you pass, self-esteem intact\"");
  51. }
  52. }
  53.  
  54. class PCPhase extends Expression {
  55. private static int next = 0;
  56. private static final String[] list = {"\"animal companion\"", "\"vertically challenged\"",
  57. "\"factually inaccurate\"", "\"chronologically gifted\""};
  58.  
  59. public PCPhase() {
  60. super(list[next]);
  61. next = (next + 1) % list.length;
  62. }
  63.  
  64. @Override
  65. public Expression clone() {
  66. return new PCPhase();
  67. }
  68. }
  69.  
  70. class NotPCPhase extends Expression {
  71. private static int next = 0;
  72. private static final String[] list = {"\"pet\"", "\"short\"", "\"lie\"", "\"old\""};
  73.  
  74. public NotPCPhase() {
  75. super(list[next]);
  76. next = (next + 1) % list.length;
  77. }
  78.  
  79. @Override
  80. public Expression clone() {
  81. return new NotPCPhase();
  82. }
  83. }
  84.  
  85. class NotPCFactory extends AbstractFactory {
  86.  
  87. public NotPCFactory() {
  88. prototype = new NotPCPhase();
  89. }
  90.  
  91. @Override
  92. public Expression makeGrade() {
  93. return new Expression("\"my way, or the highway\"");
  94. }
  95.  
  96. @Override
  97. public Expression makeCompromise() {
  98. return new Expression("\"take test, deal with the results\"");
  99. }
  100. }
  101.  
  102. public class FactoryFmProto {
  103. public static void main(String[] args) {
  104. AbstractFactory factory;
  105. if (args.length > 0) {
  106. factory = new PCFactory();
  107. } else {
  108. factory = new NotPCFactory();
  109. }
  110. for (int i = 0; i < 3; i++) {
  111. System.out.print(factory.makePhase() + " ");
  112. }
  113. System.out.println();
  114. System.out.println(factory.makeCompromise());
  115. System.out.println(factory.makeGrade());
  116. }
  117. }

Вывод

  1. if args = 0
  2. "short" "lie" "old"
  3. "my way, or the highway"
  4. "take test, deal with the results"
  5.  
  6. if args > 0
  7. "vertically challenged" "factually inaccurate" "chronologically gifted"
  8. "do it your way, any way, or no way"
  9. "you pass, self-esteem intact"

Вам это нравится? Поделитесь в социальных сетях!

Комментарии

Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь