Design patterns Monostate The Monostate Pattern


Example

The Monostate pattern is usually referred to as syntactic sugar over the Singleton pattern or as a conceptual Singleton.

It avoids all the complications of having a single instance of a class, but all the instances use the same data.
This is accomplished mostly by using static data members.
One of the most important feature is that it's absolutely transparent for the users, that are completely unaware they are working with a Monostate. Users can create as many instances of a Monostate as they want and any instance is good as another to access the data.

The Monostate class comes usually with a companion class that is used to update the settings if needed.

It follows a minimal example of a Monostate in C++:

struct Settings {
    Settings() {
        if(!initialized) {
            initialized = true;
            // load from file or db or whatever
            // otherwise, use the SettingsEditor to initialize settings
            Settings::width_ = 42;
            Settings::height_ = 128;
        }
    }

    std::size_t width() const noexcept { return width_; }
    std::size_t height() const noexcept { return height_; }

private:
    friend class SettingsEditor;

    static bool initialized;
    static std::size_t width_;
    static std::size_t height_;
};

bool Settings::initialized = false;
std::size_t Settings::width_;
std::size_t Settings::height_;

struct SettingsEditor {
    void width(std::size_t value) noexcept { Settings::width_ = value; }
    void height(std::size_t value) noexcept { Settings::height_ = value; }
};

Here is an example of a simple implementation of a Monostate in Java:

public class Monostate {
    private static int width;
    private static int height;

    public int getWidth() {
        return Monostate.width;
    }

    public int getHeight() {
        return Monostate.height;
    }

    public void setWidth(int value) {
        Monostate.width = value;
    }

    public void setHeight(int value) {
        Monostate.height = value;
    }

    static {
        width = 42;
        height = 128;
    }
}