- During the interview, the interviewer mentioned the singleton mode. I have never touched on it, but I also understand it. This disappointed the interviewer with my impact. When I came back, I bought design patterns-the basis for reusable object-oriented software. Open the singleton mode and find that the singleton Mode Implemented in C ++ is still a bit level.
- Singleton mode refersProgramThere is a component. Its Class has only one unique object and it cannot create more objects. This mode is the singleton mode.
Implementation: The Implementation requirements of the singleton model above are as follows:
Class Singleton {public: static Singleton * instance (); void dosomething (); protected: Singleton (): totle (0.0) {}; PRIVATE: static Singleton * instance _;}; singleton * singleton: instance _ = 0; Singleton * singleton: instance () {If (instance _ = 0) {instance _ = new Singleton ();} return instance _;}
We may use Singleton * P = singleton: instance (); P-> dosomething ();
Because it does not have a shared constructor, it can only be obtained using the instance method. This method always determines whether a unique object has been created. If it has already been created, it will be used directly. Otherwise, create one. Its unique constructor is not public, but can be called inside the class. It initializes the instance _ pointer used to mark the number of objects to be created.
Sometimes my program needs something to facilitate timing, And I implement it in the singleton mode. It tells you how long it takes between every two calls, it also allows you to know how much time has been spent from the beginning to the present. In addition, it also supports printing descriptive text each time the time is displayed, which can be completed only once called. Is it great? The implementation is as follows:
Class singletontimer {public: static singletontimer * instance (); void print (const string & out) {double temp = timer _. elapsed (); totle + = temp; cout <out <"time used:" <temp <"seconds, currently used: "<totle <" seconds "<Endl; timer _. restart ();} protected: singletontimer (): totle (0.0) {}; PRIVATE: static singletontimer * instance _; timer _; double totle ;}; singletontimer * singletontimer :: instance _ = 0; singletontimer * singletontimer: instance () {If (instance _ = 0) {instance _ = new singletontimer ();} return instance _;}