Decorator, Facade, and Flyweight Structural Patterns (GoF)

This page covers the implementation details and known uses of the Decorator pattern, then presents the complete Facade and Flyweight patterns. All three are structural patterns from the Gang of Four catalog. Decorator wraps objects to add responsibilities transparently; Facade simplifies access to complex subsystems; Flyweight uses sharing to efficiently support large numbers of fine-grained objects.

Key Concepts

Decorator:

Facade:

Flyweight:

Commands and Syntax

Decorator composition (C++):


// Base component
class VisualComponent {
public:
    virtual void Draw();
    virtual void Resize();
};

// Abstract decorator — forwards all operations
class Decorator : public VisualComponent {
    VisualComponent* _component;
public:
    Decorator(VisualComponent*);
    void Draw() { _component->Draw(); }
    void Resize() { _component->Resize(); }
};

// Concrete decorator — adds border drawing
class BorderDecorator : public Decorator {
    int _width;
    void DrawBorder(int);
public:
    BorderDecorator(VisualComponent*, int borderWidth);
    void Draw() { Decorator::Draw(); DrawBorder(_width); }
};

// Composing decorators
window->SetContents(
    new BorderDecorator(
        new ScrollDecorator(textView), 1));

Decorator for streams:


Stream* aStream = new CompressingStream(
    new ASCII7Stream(
        new FileStream("aFileName")));
aStream->PutInt(12);
aStream->PutString("aString");

Facade — Compiler subsystem:


class Compiler {
public:
    virtual void Compile(istream&, BytecodeStream&);
};

void Compiler::Compile(istream& input, BytecodeStream& output) {
    Scanner scanner(input);
    ProgramNodeBuilder builder;
    Parser parser;
    parser.Parse(scanner, builder);
    RISCCodeGenerator generator(output);
    ProgramNode* parseTree = builder.GetRootNode();
    parseTree->Traverse(generator);
}

Flyweight structure participants:


FlyweightFactory  →  creates/manages  →  Flyweight (interface)
                                              ├── ConcreteFlyweight (shared, intrinsic state)
                                              └── UnsharedConcreteFlyweight (not shared)
Client  →  maintains references, stores/computes extrinsic state

Relationships

Decorator vs. related patterns:

Facade vs. related patterns:

Flyweight vs. related patterns:

Exam-Relevant Points