通过私有(private)继承复用类实现工厂函数详解

通过接口类(interface class), 实现工厂函数, 可以复用(reuse)已有类, 重写实现接口.

如:

接口类: IPerson; 复用类: PersonInfo; 实现类: CPerson;

工厂函数: DatabaseID askUserForDatabaseID(); std::shared_ptrmakePerson(DatabaseID personIndetifier);

可以通过私有继承复用类PersonInfo,公有继承接口类IPerson, 并重写相关接口, 即界定符(delim),实现类CPerson的要求.

代码如下:

/*
* test.cpp
*
*  Created on: 2014.04.14
*      Author: Spike
*/
     
/*eclipse cdt, gcc 4.8.1*/
     
#include 
#include 
#include 
#include 
     
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_ptrmakePerson(DatabaseID personIndetifier) {  
   std::shared_ptrpP = std::make_shared(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_ptrpp(makePerson(id));  
   std::cout << pp->name() << std::endl;  
   std::cout << pp->birthDate() << std::endl;  
     
   return 0;  
}

输出:

---Liu---  
---1998.9.25---


来源:Mystra的CSDN博客

上一篇: 虚继承(virtual inheritance) 详解

下一篇: 模板(template)中typename的使用方法

分享到: 更多