Skip to content

Instantly share code, notes, and snippets.

@alexprivalov
Forked from pazdera/bridge.cpp
Last active August 29, 2015 14:14
Show Gist options
  • Save alexprivalov/8332a34a25ce56503c9f to your computer and use it in GitHub Desktop.
Save alexprivalov/8332a34a25ce56503c9f to your computer and use it in GitHub Desktop.
/*
* Example of `bridge' design pattern
* Copyright (C) 2011 Radek Pazdera
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <string>
/* Implemented interface. */
class AbstractInterface
{
public:
virtual ~AbstractInterface() {}
virtual void someFunctionality() = 0;
};
/* Interface for internal implementation that Bridge uses. */
class ImplementationInterface
{
public:
virtual ~ImplementationInterface() {}
virtual void anotherFunctionality() = 0;
};
/* The Bridge */
class Bridge : public AbstractInterface
{
protected:
ImplementationInterface* implementation;
public:
Bridge(ImplementationInterface* backend)
{
implementation = backend;
}
};
/* Different special cases of the interface. */
class UseCase1 : public Bridge
{
public:
UseCase1(ImplementationInterface* backend)
: Bridge(backend)
{}
void someFunctionality()
{
std::cout << "UseCase1 on ";
implementation->anotherFunctionality();
}
};
class UseCase2 : public Bridge
{
public:
UseCase2(ImplementationInterface* backend)
: Bridge(backend)
{}
void someFunctionality()
{
std::cout << "UseCase2 on ";
implementation->anotherFunctionality();
}
};
/* Different background implementations. */
class Windows : public ImplementationInterface
{
public:
void anotherFunctionality()
{
std::cout << "Windows :-!" << std::endl;
}
};
class Linux : public ImplementationInterface
{
public:
void anotherFunctionality()
{
std::cout << "Linux! :-)" << std::endl;
}
};
int main()
{
AbstractInterface *pUseCase = 0;
ImplementationInterface *pOSWindows = new Windows;
ImplementationInterface *pOSLinux = new Linux;
/* First case */
pUseCase = new UseCase1(pOSWindows);
pUseCase->someFunctionality();
pUseCase = new UseCase1(pOSLinux);
pUseCase->someFunctionality();
/* Second case */
pUseCase = new UseCase2(pOSWindows);
pUseCase->someFunctionality();
pUseCase = new UseCase2(pOSLinux);
pUseCase->someFunctionality();
delete pUseCase;
delete pOSWindows;
delete pOSLinux;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment