CKTIS / C++
Singleton, Factory, and Decorator in C++: architecture and object model
These three patterns separate object identity and lifetime, the choice of which implementation to construct, and the addition of behavior behind an unchanged interface.
Version: ISO C++23; implementation support may vary
Syntax
// C++23 architecture/object-model patterns (representative declarations, not special language syntax).
#include <memory>
#include <string>
// Singleton
class Style final {
public:
static const Style& instance();
Style(const Style&) = delete;
Style& operator=(const Style&) = delete;
char opening() const;
char closing() const;
private:
Style() = default;
~Style() = default;
};
struct Message {
virtual ~Message() = default;
virtual std::string text() const = 0;
};
// Factory
enum class Kind { brief, full };
std::unique_ptr<Message> make_message(Kind kind);
// Decorator
class Bracketed final : public Message {
public:
Bracketed(std::unique_ptr<Message> inner, const Style& style);
std::string text() const override;
private:
std::unique_ptr<Message> inner_;
char opening_;
char closing_;
};Scope — architecture and object model. These are design patterns, not special C++23 syntax. Singleton determines which instance clients share; Factory decides what object to create; Decorator decides what behavior to add to an existing object.
Singleton. Style::instance() returns a non-owning const reference to the same function-local static object. A private constructor and deleted copy operations prevent clients from directly constructing or copying instances. If dynamic initialization is needed, it occurs on the first passage through the declaration, and concurrent callers wait for it to finish. This does not synchronize later mutations. The object is destroyed at normal program termination; do not use it after destruction or assume one instance across all plugins. Prefer passing the dependency explicitly when global access is unnecessary.
Factory. make_message(Kind) selects Brief or Full at runtime, creates a fresh object with std::make_unique, and transfers exclusive ownership via std::unique_ptr<Message>. An unsupported value throws std::invalid_argument rather than returning a null pointer. This is a simple factory function, not a virtual Factory Method or an Abstract Factory for families of related products.
Decorator. Bracketed implements the same Message interface and takes exclusive ownership of the wrapped object via std::move. It rejects a null pointer with std::invalid_argument. It copies the characters from Style instead of retaining a reference. Its text() delegates to the wrapped object and adds brackets; decorators can be nested, and order can change the result. The virtual destructor of Message lets a std::unique_ptr<Message> with the default deleter correctly destroy a derived object.
Examples
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
class Style final {
public:
static const Style& instance() {
static const Style style;
return style;
}
Style(const Style&) = delete;
Style& operator=(const Style&) = delete;
char opening() const { return '['; }
char closing() const { return ']'; }
private:
Style() = default;
~Style() = default;
};
struct Message {
virtual ~Message() = default;
virtual std::string text() const = 0;
};
struct Brief final : Message {
std::string text() const override { return "brief"; }
};
struct Full final : Message {
std::string text() const override { return "full"; }
};
enum class Kind { brief, full };
std::unique_ptr<Message> make_message(Kind kind) {
switch (kind) {
case Kind::brief: return std::make_unique<Brief>();
case Kind::full: return std::make_unique<Full>();
}
throw std::invalid_argument("unsupported message kind");
}
class Bracketed final : public Message {
public:
Bracketed(std::unique_ptr<Message> inner, const Style& style)
: inner_(std::move(inner)),
opening_(style.opening()), closing_(style.closing()) {
if (!inner_) {
throw std::invalid_argument("missing wrapped message");
}
}
std::string text() const override {
return opening_ + inner_->text() + closing_;
}
private:
std::unique_ptr<Message> inner_;
char opening_;
char closing_;
};
int main() {
const auto& style = Style::instance();
auto plain = make_message(Kind::brief);
std::unique_ptr<Message> decorated =
std::make_unique<Bracketed>(make_message(Kind::full), style);
std::cout << std::boolalpha << (&style == &Style::instance()) << '\n'
<< plain->text() << '\n'
<< decorated->text() << '\n';
}
Result
true brief [full]
Expected lines: `true` confirms the same instance, `brief` is the plain factory product's result, and `[full]` is the second implementation's result after decoration.
Related lessons
- C++ · Lesson 55 · Intermediate · Version: 2
Sources
- Declaration statement [stmt.dcl]
- The inline specifier [dcl.inline]
- Termination [basic.start.term]
- Virtual functions [class.virtual]
- Delete [expr.delete]
- Unique-ownership pointers: Creation [unique.ptr.create]
- unique_ptr for single objects: Constructors [unique.ptr.single.ctor]
- unique_ptr for single objects: Destructor [unique.ptr.single.dtor]
- Default deleters [unique.ptr.dltr.dflt]