通過接口類(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