Singleton Implementation, Creational Pattern Comparison, and Adapter Pattern

This document covers three distinct topics from the Gang of Four design patterns book: the implementation details and sample code for the Singleton pattern, a comparative discussion of all creational patterns and when to choose each, and the full treatment of the Adapter structural pattern including its class and object variants.

Key Concepts

Singleton Implementation

Discussion of Creational Patterns

Adapter Pattern

Commands and Syntax

Singleton — Lazy Initialization (C++)


class Singleton {
public:
    static Singleton* Instance();
protected:
    Singleton();
private:
    static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;
Singleton* Singleton::Instance() {
    if (_instance == 0) {
        _instance = new Singleton;
    }
    return _instance;
}

Singleton — Subclass Selection via Environment Variable


MazeFactory* MazeFactory::Instance() {
    if (_instance == 0) {
        const char* mazeStyle = getenv("MAZESTYLE");
        if (strcmp(mazeStyle, "bombed") == 0) {
            _instance = new BombedMazeFactory;
        } else if (strcmp(mazeStyle, "enchanted") == 0) {
            _instance = new EnchantedMazeFactory;
        } else {
            _instance = new MazeFactory;
        }
    }
    return _instance;
}

Singleton — Registry Approach


class Singleton {
public:
    static void Register(const char* name, Singleton*);
    static Singleton* Instance();
protected:
    static Singleton* Lookup(const char* name);
private:
    static Singleton* _instance;
    static List<NameSingletonPair>* _registry;
};

Singleton* Singleton::Instance() {
    if (_instance == 0) {
        const char* singletonName = getenv("SINGLETON");
        _instance = Lookup(singletonName);
    }
    return _instance;
}

Singleton in Smalltalk


new
    self error: 'cannot create new object'
default
    SoleInstance isNil ifTrue: [SoleInstance := super new].
    ^ SoleInstance

Adapter — Class Adapter (C++)

Adapter — Object Adapter

Relationships

Exam-Relevant Points