As we know, there are three types of design patterns such as creational, structural ad behavioral but the first thing to remember that a bridge design pattern is a structural design pattern
Intent
in brief, decouple an abstraction from its implementation so that the two can vary independently
on one hand, Abstraction: is an interface that provides the non specific implementation of the logic
on the other hand, implementation: implementation of the abstraction, which is responsible for low-level work
But, why we use a bridge design pattern?
As we know through abstraction we can have several ways to implement it and we use inheritance to make it possible but it is not flexible enough
The problem with inheritance is that it binds abstraction and implementation permanently together because of that it becomes difficult to modify abstraction and implementation independently or reuse it or extend it
Example
at this time, suppose you have a family class which is an abstraction or interface through which you have inherited father, mother, and toddler
All the family members have their way of movement logic such as father goes to the office, mother stay at home
basically, each family member have different movement logic
Abstraction implementation
Family move logic
Father drive car
+ go to the office
+ go to the meeting
Mother stay at home
+cook food
Toddler stay at the cradle
+crawl
Structure
Participants
Abstraction(Family)
Refined abstraction(father,mother,toddler)
Implementor(move logic)
Concrete implementor(Drive car, stay at cradle)
#include<iostream>
#include<string>
using namespace std;
class MoveLogic
{
public:
virtual void move() = 0;
};
class Drivecar : public MoveLogic
{
public:
void move()
{
cout << "Go to office\n";
}
};
class Stayatcradle : public MoveLogic
{
public:
void move()
{
cout << "Crawl\n";
}
};
class Family
{
public:
virtual void howDoIMove() = 0;
};
class Father : public Family
{
MoveLogic* _myMoveLogic;
public:
Father(MoveLogic *obj) :_myMoveLogic(obj){}
void howDoIMove()
{
_myMoveLogic->move();
}
};
class Toddler : public Family
{
MoveLogic* _myMoveLogic;
public:
Toddler(MoveLogic *obj) :_myMoveLogic(obj){}
void howDoIMove()
{
_myMoveLogic->move();
}
};
int main()
{
MoveLogic* drivecar = new Drivecar();
MoveLogic* stayatcradle = new Stayatcradle();
Family* FamilyA = new Father(drivecar);
Family* FamilyB = new Toddler(stayatcradle);
FamilyA->howDoIMove();
FamilyB->howDoIMove();
return 1;
}
Output
Go to office
Crawl
Leave a Reply