Skip to content

Instantly share code, notes, and snippets.

@fpersson
Created September 19, 2011 19:34
Show Gist options
  • Save fpersson/1227353 to your computer and use it in GitHub Desktop.
Save fpersson/1227353 to your computer and use it in GitHub Desktop.
Abstract Adaptor patter in C++
cmake_minimum_required (VERSION 2.6)
project(demo)
find_package(Boost 1.4.2)
include_directories(${Boost_INCLUDE_DIR})
set(CORELIBS ${Boost_LIBRARIES})
add_executable(demo ${CORELIBS} test.cpp )
target_link_libraries(demo ${CORELIBS})
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <fstream>
#include <boost/ptr_container/ptr_vector.hpp>
/**
* A simple adapter pattern based på http://johnlindquist.com/2011/05/17/patterncraft-adapter-pattern/
* Uses http://www.boost.org/doc/libs/1_42_0/libs/ptr_container/doc/ptr_container.html
*/
/**
* Interface
*/
class IUnit{
public:
virtual void attack() = 0;
};
class Zergling : public IUnit{
public:
void attack(){
std::cout << "Zergling, clawing attack" << std::endl;
}
};
class Zealot : public IUnit{
public:
void attack(){
std::cout << "Zealot, slash attack." << std::endl;
}
};
class Marine : public IUnit{
public:
void attack(){
std::cout << "Marine, armed attack" << std::endl;;
}
};
class Mario{
public:
void jumpAttack(){
std::cout << "Mario, jump attack." << std::endl;
}
};
class MarioAdapter : public IUnit{
public:
void attack(){
m_Mario.jumpAttack();
}
private:
Mario m_Mario;
};
int main(int argc, char* argv[])
{
boost::ptr_vector<IUnit> UnitList;
UnitList.push_back(new Zergling());
UnitList.push_back(new Zealot());
UnitList.push_back(new Marine());
UnitList.push_back(new MarioAdapter());
boost::ptr_vector<IUnit>::iterator it;
for(it = UnitList.begin(); it != UnitList.end(); ++it){
it->attack();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment