具有单类实例的C ++体系结构

时间:2017-06-22 20:03:18

标签: c++ class architecture

我正在审核一些代码并且是C ++的新手。 SW架构有哪些优点和/或缺点,其中所有代码都封装在只能有单个实例的类中。每个使用它的类都会检索此实例。我将尝试在下面举一个简短的例子:

//classa.h
class A
{
public:
  void foo ();
  ~A(); //Destructor
  static A& getInstance();  //Retrieve Only Instance
protected:
  A();  // Protected Constructor
};

//classa.cpp
#include "classa.h"
A::A() {}; //Constructor
A::~A() {}; //Destructor
A& A::getInstance()
{
  static A theOnlyInstance;
  return theOnlyInstance;
}
A::foo() {};

//classb.h and classc.h
include "classa.h"
//Normal Stuff..
A& localRefToA

//classb.cpp
B::B():localRefToA(A::getInstance()) {}; //Constructor
B::fooB()  //Function using A's member function
{
  localRefToA.foo();
}

//classC.cpp
C::C():localRefToA(A::getInstance()) {}; //Constructor
C::fooC()  //Function using A's member function
{
  localRefToA.foo();
}

0 个答案:

没有答案