[Design Pattern] Erzeugende Muster: Abstract Factory

Thomas Darimont

Erfahrenes Mitglied
Hallo,

dieser Beitrag erklärt das erzeugende Muster: Abstract Factory
Java:
package de.tutorials.design.patterns.creational;

import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;

import org.jpatterns.gof.AbstractFactoryPattern.AbstractFactory;
import org.jpatterns.gof.AbstractFactoryPattern.ConcreteFactory;
import org.jpatterns.gof.AbstractFactoryPattern.FactoryMethod;

public class AbstractFactoryExample {

  public static class TestEnv {
    public static void run() {
      System.out.println(Factory.getInstance().create().getClass());
    }
  }
  
  public static void main(String[] args) throws Exception {
    smartSingletonTesting();
  }


  protected static void smartSingletonTesting() throws IllegalAccessException, InvocationTargetException,
    NoSuchMethodException, ClassNotFoundException {
    loadTestEnv().getMethod("run").invoke(null);
    System.setProperty("factory", "StringFactory");
    loadTestEnv().getMethod("run").invoke(null);
  }


  protected static Class<?> loadTestEnv() throws ClassNotFoundException {
    URL classpath = TestEnv.class.getProtectionDomain().getCodeSource().getLocation();
    URLClassLoader cl = new URLClassLoader(new URL[] { classpath }, null);
    Class<?> testEnv = cl.loadClass(TestEnv.class.getName());
    return testEnv;
  }

  @AbstractFactory
  static abstract class Factory {
    static final Factory factory = System.getProperty("factory", "LongFactory").equals("LongFactory")
      ? new LongFactory() : new StringFactory();


    @FactoryMethod
    public abstract Object create();


    public static Factory getInstance() {
      return factory;
    }
  }

  @ConcreteFactory
  static class LongFactory extends Factory {
    public Object create() {
      return Long.valueOf(System.currentTimeMillis() % 128);
    }
  }

  @ConcreteFactory
  static class StringFactory extends Factory {
    public Object create() {
      return String.valueOf(System.currentTimeMillis());
    }
  }
}

Ausgabe:
Code:
class java.lang.Long
class java.lang.String

Gruß Tom
 

Neue Beiträge

Zurück