C++:通过私有(private)担任复用类实现工场函数详解
通过接口类(interface class), 实现工场函数, 可以复用(reuse)已有类, 重写实现接口.
如:
接口类: IPerson; 复用类: PersonInfo; 实现类: CPerson;
工场函数: DatabaseID askUserForDatabaseID(); std::shared_ptr<IPerson> makePerson(DatabaseID personIndetifier);
可以通过私有担任复用类PersonInfo,公有担任接口类IPerson, 并重写相关接口, 即界定符(delim),实现类CPerson的要求.
代码如下:
/* * test.cpp * * Created on: 2014.04.14 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <cstring> #include <iostream> #include <string> #include <memory> using namespace std; class IPerson { public: virtual ~IPerson() = default; virtual std::string name() const = 0; virtual std::string birthDate() const = 0; }; struct DatabaseID { char name[256]; char birthDate[256]; }; class PersonInfo { public: explicit PersonInfo(DatabaseID pid){ std::strcpy(m_name, pid.name); std::strcpy(m_birthDate, pid.birthDate); } virtual ~PersonInfo() = default; virtual const char* theName() const; virtual const char* theBirthDate() const; protected: virtual const char* valueDelimOpen() const { return "["; }; virtual const char* valueDelimClose() const { return "]"; }; private: char m_name[256]; char m_birthDate[256]; static const int Max_Formatted_Filed_Value_Length = 512; }; const char* PersonInfo::theName() const { static char value[Max_Formatted_Filed_Value_Length]; std::strcpy(value, valueDelimOpen()); std::strcat(value, m_name); std::strcat(value, valueDelimClose()); return value; } const char* PersonInfo::theBirthDate() const { static char value[Max_Formatted_Filed_Value_Length]; std::strcpy(value, valueDelimOpen()); std::strcat(value, m_birthDate); std::strcat(value, valueDelimClose()); return value; } class CPerson : public IPerson, private PersonInfo { public: explicit CPerson(DatabaseID pid) : PersonInfo(pid) {} virtual std::string name() const { return PersonInfo::theName(); } virtual std::string birthDate() const { return PersonInfo::theBirthDate(); } private: const char* valueDelimOpen() const { return "---"; } const char* valueDelimClose() const { return "---"; } }; std::shared_ptr<IPerson> makePerson(DatabaseID personIndetifier) { std::shared_ptr<IPerson> pP = std::make_shared<CPerson>(personIndetifier); return pP; } DatabaseID askUserForDatabaseID() { DatabaseID di; std::strcpy(di.name, "Liu"); std::strcpy(di.birthDate, "1998.9.25"); return di; } int main() { DatabaseID id(askUserForDatabaseID()); std::shared_ptr<IPerson> pp(makePerson(id)); std::cout << pp->name() << std::endl; std::cout << pp->birthDate() << std::endl; return 0; }
输出:
---Liu--- ---1998.9.25---
作者:csdn博客 Spike_King