Entwurfsmuster-Beispiele

· by

Contents

Singleton

Zweck: Stelle sicher, dass es nur eine Instanz dieser Klasse gibt. Beispiel: java.lang.Runtime.getRuntime()

public class Singleton {
    // an instance of a singleton
    private static Singleton instance = null;

    // private default constructor to prevent the external creation
    // of more instances
    private Singleton() {
    }

    // static method which returns the instance
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Bequemlichkeitsklasse

Zweck: Faulheit - mache Methodenaufrufe durch änderbare default-Parameter einfacher. Das Bequemlichkeitsmuster ist einfach das Überladen einer Methode:

public class Bequemlichkeitsklasse {
    // convenience class
    int v1, v2, v3;

    int anfrage(int p1, int p2, int p3) {
        return p1 * p2 * p3;
    }

    int anfrage(int p1) {
        return anfrage(p1, v2, v3);
    }

    int anfrage() {
        return anfrage(v1, v2, v3);
    }

    void setzeZustand(int p1, int p2, int p3) {
        v1 = p1;
        v2 = p2;
        v3 = p3;
    }
}

Schablonenmethode

Siehe Java Puzzle #9: Template method pattern.

Siehe auch