Created
August 20, 2019 01:01
-
-
Save slwu89/dce0abb504de657c2846a62c826e9102 to your computer and use it in GitHub Desktop.
bridge-ish pattern with c++ when you want to have the different implementations store variable data using void*
This file contains hidden or 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 <iomanip> | |
#include <string> | |
#include <string> | |
#include <memory> | |
class impl_base { | |
public: | |
/* ctor & dtor */ | |
impl_base(){}; | |
virtual ~impl_base() = default; | |
/* move operators */ | |
impl_base(impl_base&&) = default; | |
impl_base& operator=(impl_base&&) = default; | |
/* copy operators */ | |
impl_base(impl_base&) = delete; | |
impl_base& operator=(impl_base&) = delete; | |
/* algorithm that can vary */ | |
virtual void algorithm() = 0; | |
/* factory */ | |
static impl_base* factory(int type, void* data); | |
}; | |
class impl_pfsi : public impl_base { | |
public: | |
/* ctor & dtor */ | |
impl_pfsi() : impl_base() {}; | |
~impl_pfsi() = default; | |
/* move operators */ | |
impl_pfsi(impl_pfsi&&) = default; | |
impl_pfsi& operator=(impl_pfsi&&) = default; | |
/* copy operators */ | |
impl_pfsi(impl_pfsi&) = delete; | |
impl_pfsi& operator=(impl_pfsi&) = delete; | |
/* algorithm that can vary */ | |
virtual void algorithm(){ | |
std::cout << "i'm the pfsi model!\n"; | |
} | |
}; | |
class impl_pfmoi : public impl_base { | |
public: | |
/* ctor & dtor */ | |
impl_pfmoi(double number) : impl_base(), a_number(number) {}; | |
~impl_pfmoi() = default; | |
/* move operators */ | |
impl_pfmoi(impl_pfmoi&&) = default; | |
impl_pfmoi& operator=(impl_pfmoi&&) = default; | |
/* copy operators */ | |
impl_pfmoi(impl_pfmoi&) = delete; | |
impl_pfmoi& operator=(impl_pfmoi&) = delete; | |
/* algorithm that can vary */ | |
virtual void algorithm(){ | |
std::cout << "i'm the pfmoi model! i'm special and store a number: " << a_number << "\n"; | |
} | |
private: | |
double a_number; | |
}; | |
//the factory method | |
impl_base* impl_base::factory(int type, void *data){ | |
if(type==0){ | |
return new impl_pfsi(); | |
} else if(type==1){ | |
double* num = static_cast<double*>(data); | |
return new impl_pfmoi(*num); | |
} else { | |
return nullptr; | |
} | |
}; | |
class human { | |
}; | |
int main(){ | |
double number = 5.56; | |
double* ptr2num = &number; | |
void* voidptr = ptr2num; | |
double* voidptr2num = static_cast<double*>(voidptr); | |
std::cout << "deref voidptr2num: " << *voidptr2num << std::endl; | |
impl_base* pfsi = impl_base::factory(0, nullptr); | |
impl_base* pfmoi = impl_base::factory(1, &number); | |
pfsi->algorithm(); | |
pfmoi->algorithm(); | |
delete pfsi; | |
delete pfmoi; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment