I was trying to apply the Attorney-Client Idiom (know as PassKey Idiom) and this for two classes.
I explain :
I have a class named Secret
which contains name
and age
as private members. I have created a class Attorney
which defines 2 getters for each memeber in class Secret
.
I want to create 2 classes:
showAge
which only have access to 1 gettershowAgeAndName
which has access to both getters.
So far all works fine, but looking at the code, it not well maintainable : if I add new members to my Secret
and want a specific access to new getters I have to add another class and end with lot of copy-paste.
So is there a better alternative like : using Factory design pattern / enhance the templated class ...
Below is my code:
using namespace std;
class Secret;
class showAge;
class showAgeAndName;
template<typename T>
class Attorney
{
private:
friend T;
Attorney(const Attorney&) {}
Attorney() {}
};
class Secret
{
public:
std::string getAge(Attorney<showAge>) noexcept { return "Age is " + to_string((long long)age); }
std::string getName(Attorney<showAgeAndName>) noexcept { return "Name is " + name; }
private:
int age{36};
std::string name{"Mike"};
};
class showAge
{
public:
showAge() noexcept {};
void showInfos(Secret& src)
{
std::cout << src.getAge(Attorney<showAge>()) << std::endl;
}
};
class showAgeAndName
{
public:
showAgeAndName() noexcept {};
void showInfos(Secret& src)
{
std::cout << src.getName(Attorney<showAgeAndName>()) << std::endl;
}
};
int main() {
Secret s;
showAge prA;
showAgeAndName prAn;
prA.showInfos(s);
prAn.showInfos(s);
}
Thank you
Aucun commentaire:
Enregistrer un commentaire