Created
September 19, 2011 19:34
-
-
Save fpersson/1227354 to your computer and use it in GitHub Desktop.
Abstract Adaptor patter in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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
Kan även använda std::vector<IUnit*> UnitList då blir det (*it).attack() i teratorn