Singleton pattern
来源:互联网 发布:mysql存储图片 编辑:程序博客网 时间:2024/06/02 04:45
单例模式,感觉看了还是不是很懂,尤其是什么多线程,什么锁。。
自己写了个单线程下的额单例模式,这个单例类是时间,用于程序的运行时告知系统当前时间。
至于头文件time.h看看能不能也研究研究。
参考:
http://blog.csdn.net/boyxiaolong/article/details/6645681
http://blog.yangyubo.com/2009/06/04/best-cpp-singleton-pattern/#id15
http://blog.csdn.net/lanxuezaipiao/article/details/16974151
main.cpp
#include <iostream>using namespace std;#include "Timer.h"int main() { Timer& t = Timer::instance(); Timer& t_1 = Timer::instance(); //t = t_1; // error: operator assignment is private, to ensure a singleton class cout << endl; string control; while (1) { cin >> control; if (control == "end") { break; } else if (control == "show") { t.show_time_here(); } else { cout << "error order!" << endl; } } cout << endl; return 0;}Timer.h
#ifndef __TIMER_H#define __TIMER_H#include <iostream>#include <time.h> // to include this header file to get the system timeusing namespace std;class Timer { public: static Timer& instance() { static Timer the_timer; // with the static, the class the_timer will be alive in all the program since its birth, when the function instance is called, this can avoid making another timer return the_timer; } void show_time_here() { ti = time(NULL); here_time = localtime(&ti); gm_time = localtime(&ti); cout << "The local time is: " << here_time->tm_year + 1900<< " " << here_time->tm_mon + 1<< " " << here_time->tm_mday << " " << here_time->tm_hour << " " << here_time->tm_min << " " << here_time->tm_sec << endl; // remember to add 1900 to the year and 1 to the month(the starting points are 1900 and 0) cout << "The local time is: " << gm_time->tm_year + 1900 << " " << gm_time->tm_mon + 1 << " " << gm_time->tm_mday << " " << gm_time->tm_hour << " " << gm_time->tm_min << " " << gm_time->tm_sec << endl; } private: Timer() { cout << "the timer is born." << endl; } Timer(Timer const&); // to avoid this Timer& operator=(Timer const&); // to avoid this ~Timer() { // notice that the destructor is called after return 0 in main, cause static class the_timer is alive since its birth until the program is over cout << "the timer died." << endl; } struct tm *here_time; // tm is struct that contains time struct tm *gm_time; clock_t ti; };#endif
0 0
- singleton pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton pattern
- Singleton Pattern
- Singleton Pattern
- singleton pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton Pattern
- Singleton pattern
- UVA - 12532 Interval Product
- UVA 10130 SuperSale (DP 01背包)
- time.h
- JS中日期和时间的获取
- 请教一下 服务器的环境是用PHPstudy搭建的用的80口?
- Singleton pattern
- 4-使用synchronized实现线程间通信-实现线程间通信方式(1)
- Decorator pattern
- 大学三年
- 蓝桥杯带分数
- poj 1250 Tanning Salon
- Sicily 2401. Judges' Time Calculation
- Pre,in,post expression
- Sicily 1533. CIVIC DILL MIX