Singleton pattern

单例模式,感觉看了还是不是很懂,尤其是什么多线程,什么锁。。
自己写了个单线程下的额单例模式,这个单例类是时间,用于程序的运行时告知系统当前时间。
至于头文件time.h看看能不能也研究研究。
参考:

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 time
using 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
Singleton pattern - Night - Night


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值