Freitag, 31. August 2007

Singleton pattern

Surpose the Routing Graph is used everywhere in the code, but it should only be initialized once(by calling its init_from_psf() method).

A clean solution is to use singleton pattern. Declare an instance() mehtod, which is static. In the instance() method, a flag is set to ensure only the flag has a value of zero, the method init_from_psf() will be called.


#include ".\routinggraphsingleton.h"
#include

RoutingGraphSingleton::RoutingGraphSingleton()
{
}

Routing_Graph* RoutingGraphSingleton::instance() {
if (_instance == 0) {
_instance = new Routing_Graph;
cout << "Loading routing graph... "; _instance->init_from_psf();
cout << "Done." << endl;
}
return _instance;
}

Routing_Graph* RoutingGraphSingleton::_instance =0;

---------------------------------------------------------------------------
header:

#include "routing_graph.h"

using namespace lb_dp_routing;

class RoutingGraphSingleton
{
public:
static Routing_Graph* instance();
protected:
RoutingGraphSingleton();
private:
static Routing_Graph* _instance;
};

Keine Kommentare: