Design Pattern's a tool to avoid resolving the already solved problem. Just apply the existing solution and your problem is solved. Patterns don't go directly into code, they first go into your mind. Once you train it with working knowledge, you then apply them to your design for any given problem or your old problem.
When ever design pattern comes to you first pattern that come into mind is Singleton. The singleton pattern deals with situations where only one instance of a class must be created.
Definitions:
- Ensure only one instance, and provide a global point of access to it.
- Restrict a class so that only one instance can be created.
Features:
- A single instance of a subsystem shall be enforced, and the subsystem itself shall be responsible for that enforcement.
- The single instance shall be globally accessible.
- The single instance shall be initialized only if, and when, it is accessed.
We can implement singleton class by doing following changes to any class:
- Make following private
- Constructor : to control instantiating
- Copy Constructor : do not want to create copies.
- Assignment Operator
- Create method that , creates a new instance of the class if one does not exist, return object reference.
- Base for implementing many other pattern like factory, abstract factory etc.
- Very common use is to create logger for you application.
- Make debugging difficult
- extra care should be taken while implementing for threaded application.
Example:
/* Singleton.h */
#ifndef SINGLETON_H_
#define SINGLETON_H_
#define SINGLETON singleton::Singleton::getInstance()
namespace singleton {
class Singleton {
public:
virtual ~Singleton();
static const Singleton& getInstance();
void doTask() const;
private:
Singleton();
Singleton(const Singleton &);
Singleton& operator = (const Singleton &);
};
} /* namespace singleton */
#endif /* SINGLETON_H_ */
/* Singleton.cpp */
#include "Singleton.h"
#include "assert.h"
namespace singleton {
Singleton::~Singleton() {
// TODO class cleaning
}
Singleton::Singleton() {
// TODO constructor stub
}
Singleton::Singleton(const Singleton & ref) {
// TODO copy constructor
}
// global interface
const Singleton & Singleton::getInstance() {
static Singleton obj;
return obj;
}
Singleton & Singleton::operator =(const Singleton & ref) {
assert(false);
return *this;
}
// task performed by class
void Singleton::doTask() const {
cout << "task to do" << endl;
}
}/* namespace singleton */
/* main.cpp */
#include "Singleton.h"
int main(int argc, char *argv[]) {SINGLETON.doTask();
return 0;}/****************************************************************/
No comments:
Post a Comment