我正在审核一些代码并且是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();
}