Add example of adapter pattern in C++

This commit is contained in:
Shaun Reed 2021-05-11 16:57:21 -04:00
parent da9d26cf15
commit 912cb47dcf
5 changed files with 83 additions and 0 deletions

View File

@ -16,3 +16,7 @@ project(
)
add_subdirectory(singleton)
add_subdirectory(adapter)
add_subdirectory(bridge)
add_subdirectory(factory)
add_subdirectory(abstract-factory)

View File

@ -0,0 +1,20 @@
###############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2021 Shaun Reed, all rights reserved ##
## About: A project for practicing the adapter C++ design pattern ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com | GitHub: shaunrd0 ##
##############################################################################
#
cmake_minimum_required(VERSION 3.15)
project(
#[[NAME]] Adapter
VERSION 1.0
DESCRIPTION "An example of the adapter design pattern in C++"
LANGUAGES CXX
)
add_compile_options("-Wall")
add_library(adapter "adapter.cpp")
add_executable(adapter-test "main.cpp")
target_link_libraries(adapter-test adapter)

View File

@ -0,0 +1,2 @@
#include "adapter.hpp"

View File

@ -0,0 +1,37 @@
#ifndef ADAPTER_HPP
#define ADAPTER_HPP
#include <random>
// Target implementation to adapt to a new interface
class Add {
public:
virtual ~Add() = default;
virtual int doMath(const int &a, const int &b) const { return a + b;}
};
// An adaptee with some useful behavior to adapt to our Add target
class RandomNumber {
public:
explicit RandomNumber(const int &max) : maxNum(max) { srand(time(nullptr));}
int getRandom() const { return rand() % maxNum;}
private:
int maxNum;
};
// An adapter that combines behaviors of Add and RandomNumber
class RandomAddAdapter : public Add {
public:
explicit RandomAddAdapter(RandomNumber *random_) : random(random_) {}
int doMath(const int &a, const int &b) const override { return a + b + random->getRandom();}
private:
RandomNumber *random;
};
#endif // ADAPTER_HPP

View File

@ -0,0 +1,20 @@
#include <iostream>
#include "adapter.hpp"
int main(const int argc, const char * argv[]) {
const int a = 5;
const int b = 10;
std::cout << "A = " << a << "\nB = " << b << std::endl;
// Testing target implementation
Add adder;
std::cout << "Adding a + b: " << adder.doMath(a, b) << std::endl;
// Testing RandomAddAdapter using RandomNumber as the adaptee
RandomNumber *adaptee = new RandomNumber(100);
RandomAddAdapter *adapter = new RandomAddAdapter(adaptee);
std::cout << "\nAdding a + b + RandomNumber: " << adapter->doMath(a, b)
<< std::endl;
}