[Design Pattern] Erzeugende Muster: Factory Method


#1
Hallo,

dieser Beitrag erklärt das erzeugende Muster: Factory Method

Java:
package de.tutorials.design.patterns.creational;

import org.jpatterns.gof.AbstractFactoryPattern.FactoryMethod;

public class FactoryMethodPatternExample {
  public static void main(String[] args) {
    Factory standardFactory = new Factory();
    Product standardProduct = standardFactory.makeProduct();
    System.out.println(standardProduct);
    
    Factory enhancedFactory = new EnhancedFactory();
    Product enhancedProduct = enhancedFactory.makeProduct();
    System.out.println(enhancedProduct);
  }

  public static class Factory {
    
    @FactoryMethod
    public Product makeProduct() {
      return new Product(makePartA(), makePartB());
    }


    protected PartA makePartA() {
      return new PartA();
    }


    protected PartB makePartB() {
      return new PartB();
    }
  }
  
  
  
  public static class EnhancedFactory extends Factory{
    @Override
    protected PartA makePartA() {
      return new PartAGoldPlated();
    }
    
    @Override
    protected PartB makePartB() {
      return new PartBGoldPlated();
    }
  }
  
  

  @org.jpatterns.gof.FactoryMethodPattern.Product
  static class Product {
    PartA a;
    PartB b;


    public Product(PartA a, PartB b) {
      this.a = a;
      this.b = b;
    }


    @Override
    public String toString() {
      return "Product [a=" + a + ", b=" + b + "]";
    }
  }
  
  static class Part {
    @Override
    public String toString() {
      return getClass().getSimpleName() + "@" + System.identityHashCode(this);
    }
  }
  static class PartA extends Part {}
  static class PartB extends Part {}
  
  static class PartAGoldPlated extends PartA{};
  static class PartBGoldPlated extends PartB{};
}
Ausgabe:
Code:
Product [a=PartA@148669801, b=PartB@1690552137]
Product [a=PartAGoldPlated@1807500377, b=PartBGoldPlated@355165777]
Gruß Tom
 

Neue Beiträge