BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Design Patterns - Decorator Pattern

Patterns.png




Bookmark and Share





bogotobogo.com site search:

Decorator Pattern

Intent
Attach additional responsibilities to an object dynamically.
Decorators provide flexible alternatives to subclassing for extending functionality.




decorator_diagram
#include <iostream> 
#include <string>

using namespace std;
 
class Window 
{
public:
  virtual void draw() = 0;
  virtual string getDescription() = 0;
  virtual ~Window() {}
};
 
class SimpleWindow : public Window 
{
public:
  void draw() {
    // draw window 
  }
  string getDescription() {
	  return "simple window\n";
  }
};

class WindowDecorator : public Window 
{
protected:
	Window *m_decoratedWindow; 
 
public:
	WindowDecorator (Window *decoratedWindow): 
	  m_decoratedWindow(decoratedWindow) {}
};

class VerticalScrollBarDecorator : public WindowDecorator 
{
public:
	VerticalScrollBarDecorator (Window *decoratedWindow): 
		WindowDecorator(decoratedWindow) {}
 
	void draw() {
        drawVerticalScrollBar();
        m_decoratedWindow->draw();
    }
 
    string getDescription() {
        return m_decoratedWindow->getDescription() + "with vertical scrollbars\n";
    }

private:
	void drawVerticalScrollBar() {
        // draw the vertical scrollbar
    }
};

class HorizontalScrollBarDecorator : public WindowDecorator 
{
public:
	HorizontalScrollBarDecorator (Window *decoratedWindow): 
		WindowDecorator(decoratedWindow) {}
 
	void draw() {
        drawHorizontalScrollBar();
        m_decoratedWindow->draw();
    }
 
    string getDescription() {
        return m_decoratedWindow->getDescription() + "with horizontal scrollbars\n";
	}
private:
	void drawHorizontalScrollBar() {
        // draw the horizontal scrollbar
    }
};

int main()
{
  Window *simple = new SimpleWindow();
  cout << simple -> getDescription() << endl;

  Window *horiz = new HorizontalScrollBarDecorator ( new SimpleWindow());
  cout << horiz -> getDescription() << endl;

  Window *vert = new VerticalScrollBarDecorator ( new SimpleWindow());
  cout << vert -> getDescription() << endl;

  Window *decoratedWindow = new HorizontalScrollBarDecorator (
                new VerticalScrollBarDecorator(new SimpleWindow()));
  cout << decoratedWindow -> getDescription() << endl;

  return 0;
}

Output:

simple window

simple window
with horizontal scrollbars

simple window
with vertical scrollbars

simple window
with vertical scrollbars
with horizontal scrollbars

Let's take a look at code with the class diagram.

  1. Each component (Window) can be used on its own, or wrapped by decorator.
  2. The ConcreteComponent (SimpleWindow) is the object we're going to dynamically add new behavior (vertical/horizontal scrollbars) to. It inherits Component.
    class SimpleWindow : public Window
    
  3. Each decorator has-a (wraps) a component, which means the decorator has an instance variable that holds a pointer to a component.
    class WindowDecorator : public Window 
    {
    protected:
    	Window *m_decoratedWindow; 
    ...
    
  4. Decorators implement the same interface or abstract class as the component they are going to decorate.
  5. The ConcreteDecorator has an instance variable for the thing it decorate (the Component the Decorator wraps).
    class VerticalScrollBarDecorator : public WindowDecorator 
    {
    public:
    	VerticalScrollBarDecorator (Window *decoratedWindow): 
    		WindowDecorator(decoratedWindow) {}
     
    	void draw() {
            drawVerticalScrollBar();
            m_decoratedWindow->draw();
        }
     
        string getDescription() {
            return m_decoratedWindow->getDescription() + "with vertical scrollbars\n";
        }
    ...
    };
    





Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong





List of Design Patterns



Introduction

Abstract Factory Pattern

Adapter Pattern

Bridge Pattern

Chain of Responsibility

Command Pattern

Composite Pattern

Decorator Pattern

Delegation

Dependency Injection(DI) and Inversion of Control(IoC)

Façade Pattern

Factory Method

Model View Controller (MVC) Pattern

Observer Pattern

Prototype Pattern

Proxy Pattern

Singleton Pattern

Strategy Pattern

Template Method Pattern

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master