Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CPlusPlusNotesForProfessionals.pdf
Скачиваний:
47
Добавлен:
20.05.2023
Размер:
5.11 Mб
Скачать

Chapter 112: Design pattern implementation in C++

On this page, you can find examples of how design patterns are implemented in C++. For the details on these patterns, you can check out the design patterns documentation.

Section 112.1: Adapter Pattern

Convert the interface of a class into another interface clients expect. Adapter (or Wrapper) lets classes work together that couldn't otherwise because of incompatible interfaces. Adapter pattern's motivation is that we can reuse existing software if we can modify the interface.

1.Adapter pattern relies on object composition.

2.Client calls operation on Adapter object.

3.Adapter calls Adaptee to carry out the operation.

4.In STL, stack adapted from vector: When stack executes push(), underlying vector does vector::push_back().

Example:

#include <iostream>

//Desired interface (Target) class Rectangle

{

public:

virtual void draw() = 0;

};

//Legacy component (Adaptee) class LegacyRectangle

{

public:

LegacyRectangle(int x1, int y1, int x2, int y2) { x1_ = x1;

y1_ = y1;

x2_ = x2;

y2_ = y2;

std::cout << "LegacyRectangle(x1,y1,x2,y2)\n";

}

void oldDraw() {

std::cout << "LegacyRectangle: oldDraw(). \n";

}

private: int x1_; int y1_; int x2_; int y2_;

};

//Adapter wrapper

class RectangleAdapter: public Rectangle, private LegacyRectangle

{

public:

RectangleAdapter(int x, int y, int w, int h): LegacyRectangle(x, y, x + w, y + h) {

GoalKicker.com – C++ Notes for Professionals

563

std::cout << "RectangleAdapter(x,y,x+w,x+h)\n";

}

void draw() {

std::cout << "RectangleAdapter: draw().\n"; oldDraw();

}

};

int main()

{

int x = 20, y = 50, w = 300, h = 200; Rectangle *r = new RectangleAdapter(x,y,w,h); r->draw();

}

//Output:

//LegacyRectangle(x1,y1,x2,y2)

//RectangleAdapter(x,y,x+w,x+h)

Summary of the code:

1.The client thinks he is talking to a Rectangle

2.The target is the Rectangle class. This is what the client invokes method on.

Rectangle *r = new RectangleAdapter(x,y,w,h); r->draw();

3. Note that the adapter class uses multiple inheritance.

class RectangleAdapter: public Rectangle, private LegacyRectangle {

...

}

4.The Adapter RectangleAdapter lets the LegacyRectangle responds to request (draw() on a Rectangle) by inheriting BOTH classes.

5.The LegacyRectangle class does not have the same methods (draw()) as Rectangle, but the Adapter(RectangleAdapter) can take the Rectangle method calls and turn around and invoke method on the LegacyRectangle, oldDraw().

class RectangleAdapter: public Rectangle, private LegacyRectangle { public:

RectangleAdapter(int x, int y, int w, int h): LegacyRectangle(x, y, x + w, y + h) {

std::cout << "RectangleAdapter(x,y,x+w,x+h)\n";

}

void draw() {

std::cout << "RectangleAdapter: draw().\n"; oldDraw();

}

};

Adapter design pattern translates the interface for one class into a compatible but di erent interface. So, this is similar to the proxy pattern in that it's a single-component wrapper. But the interface for the adapter class and the

GoalKicker.com – C++ Notes for Professionals

564

original class may be di erent.

As we've seen in the example above, this adapter pattern is useful to expose a di erent interface for an existing API to allow it to work with other code. Also, by using adapter pattern, we can take heterogeneous interfaces, and transform them to provide consistent API.

Bridge pattern has a structure similar to an object adapter, but Bridge has a di erent intent: It is meant to separate an interface from its implementation so that they can be varied easily and independently. An adapter is meant to change the interface of an existing object.

Section 112.2: Observer pattern

Observer Pattern's intent is to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

The subject and observers define the one-to-many relationship. The observers are dependent on the subject such that when the subject's state changes, the observers get notified. Depending on the notification, the observers may also be updated with new values.

Here is the example from the book "Design Patterns" by Gamma.

#include <iostream> #include <vector>

class Subject;

class Observer

{

public:

virtual ~Observer() = default; virtual void Update(Subject&) = 0;

};

class Subject

{

public:

virtual ~Subject() = default;

void Attach(Observer& o) { observers.push_back(&o); } void Detach(Observer& o)

{

observers.erase(std::remove(observers.begin(), observers.end(), &o));

}

void Notify()

{

for (auto* o : observers) { o->Update(*this);

}

}

private:

std::vector<Observer*> observers;

};

class ClockTimer : public Subject

{

public:

void SetTime(int hour, int minute, int second)

{

this->hour = hour;

GoalKicker.com – C++ Notes for Professionals

565

this->minute = minute; this->second = second;

Notify();

}

int GetHour() const { return hour; }

int GetMinute() const { return minute; } int GetSecond() const { return second; }

private:

int hour; int minute; int second;

};

class DigitalClock: public Observer

{

public:

explicit DigitalClock(ClockTimer& s) : subject(s) { subject.Attach(*this); } ~DigitalClock() { subject.Detach(*this); }

void Update(Subject& theChangedSubject) override

{

if (&theChangedSubject == &subject) { Draw();

}

}

void Draw()

{

int hour = subject.GetHour(); int minute = subject.GetMinute(); int second = subject.GetSecond();

std::cout << "Digital time is " << hour << ":"

<<minute << ":"

<<second << std::endl;

}

private:

ClockTimer& subject;

};

class AnalogClock: public Observer

{

public:

explicit AnalogClock(ClockTimer& s) : subject(s) { subject.Attach(*this); } ~AnalogClock() { subject.Detach(*this); }

void Update(Subject& theChangedSubject) override

{

if (&theChangedSubject == &subject) { Draw();

}

}

void Draw()

{

int hour = subject.GetHour(); int minute = subject.GetMinute(); int second = subject.GetSecond();

std::cout << "Analog time is " << hour << ":" << minute << ":"

GoalKicker.com – C++ Notes for Professionals

566

<< second << std::endl;

}

private:

ClockTimer& subject;

};

int main()

{

ClockTimer timer;

DigitalClock digitalClock(timer);

AnalogClock analogClock(timer);

timer.SetTime(14, 41, 36);

}

Output:

Digital time is 14:41:36

Analog time is 14:41:36

Here are the summary of the pattern:

1.Objects (DigitalClock or AnalogClock object) use the Subject interfaces (Attach() or Detach()) either to subscribe (register) as observers or unsubscribe (remove) themselves from being observers (subject.Attach(*this); , subject.Detach(*this);.

2.Each subject can have many observers( vector<Observer*> observers;).

3.All observers need to implement the Observer interface. This interface just has one method, Update(), that gets called when the Subject's state changes (Update(Subject &))

4.In addition to the Attach() and Detach() methods, the concrete subject implements a Notify() method that is used to update all the current observers whenever state changes. But in this case, all of them are done in the parent class, Subject (Subject::Attach (Observer&), void Subject::Detach(Observer&) and void Subject::Notify() .

5.The Concrete object may also have methods for setting and getting its state.

6.Concrete observers can be any class that implements the Observer interface. Each observer subscribe (register) with a concrete subject to receive update (subject.Attach(*this); ).

7.The two objects of Observer Pattern are loosely coupled, they can interact but with little knowledge of each other.

Variation:

Signal and Slots

Signals and slots is a language construct introduced in Qt, which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that controls (also known as widgets) can send signals containing event information which can be received by other controls using special functions known as slots. The slot in Qt must be a class member declared as such. The signal/slot system fits well with the way Graphical User Interfaces are designed. Similarly, the signal/slot system can be used for asynchronous I/O (including sockets, pipes, serial devices, etc.) event notification or to associate timeout events with appropriate object instances and methods or functions. No registration/deregistration/invocation code need be written, because Qt's Meta Object Compiler (MOC) automatically generates the needed infrastructure.

GoalKicker.com – C++ Notes for Professionals

567