fork download
  1. // Abstract Factory
  2. interface AbstractFactory {
  3. AbstractProduct createProduct();
  4. }
  5.  
  6. // Concrete Factory 1
  7. class ConcreteFactory1 implements AbstractFactory {
  8. public AbstractProduct createProduct() {
  9. return new ConcreteProduct1();
  10. }
  11. }
  12.  
  13. // Concrete Factory 2
  14. class ConcreteFactory2 implements AbstractFactory {
  15. public AbstractProduct createProduct() {
  16. return new ConcreteProduct2();
  17. }
  18. }
  19.  
  20. // Abstract Product
  21. interface AbstractProduct {
  22. void operation();
  23. }
  24.  
  25. // Concrete Product 1
  26. class ConcreteProduct1 implements AbstractProduct {
  27. public void operation() {
  28. System.out.println("ConcreteProduct1 operation");
  29. }
  30. }
  31.  
  32. // Concrete Product 2
  33. class ConcreteProduct2 implements AbstractProduct {
  34. public void operation() {
  35. System.out.println("ConcreteProduct2 operation");
  36. }
  37. }
  38.  
  39. // Client
  40. class Client {
  41. private AbstractFactory factory;
  42.  
  43. public Client(AbstractFactory factory) {
  44. this.factory = factory;
  45. }
  46.  
  47. public void executeOperation() {
  48. AbstractProduct product = factory.createProduct();
  49. product.operation();
  50. }
  51. }
  52.  
  53. // Usage
  54. public class Main {
  55. public static void main(String[] args) {
  56. AbstractFactory factory1 = new ConcreteFactory1();
  57. Client client1 = new Client(factory1);
  58. client1.executeOperation();
  59.  
  60. AbstractFactory factory2 = new ConcreteFactory2();
  61. Client client2 = new Client(factory2);
  62. client2.executeOperation();
  63. }
  64. }
  65.  
Success #stdin #stdout 0.09s 44828KB
stdin
Standard input is empty
stdout
ConcreteProduct1 operation
ConcreteProduct2 operation