设计模式——单件模式

需要注意:

单件模式在写作时,需要对构造函数,析构函数,赋值函数,拷贝构造函数等设置为对外不可见的。

最大程度避免出问题。

 

// MyInstance.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

class MyInstance
{
public:
    static MyInstance *Instance();
    void  SetSalary(int iSalary);
 int GetSalary();
private:
    MyInstance() : m_iSalary(0){}
    ~MyInstance();
    MyInstance(const MyInstance &obj);
    MyInstance &operator=(const MyInstance &obj);
private:
    static MyInstance *m_pInstance;
    int m_iSalary;   
};

MyInstance *MyInstance::m_pInstance = NULL;
MyInstance *MyInstance::Instance()
{
     if (NULL == m_pInstance)
  {
        m_pInstance = new MyInstance();
  }
  return m_pInstance;
}

void MyInstance::SetSalary(int iSalary)
{
     m_iSalary = iSalary;
}

int MyInstance::GetSalary()
{
     return m_iSalary;
}


int main(int argc, char* argv[])
{
 MyInstance::Instance()->SetSalary(2000000);
 int iSalary = MyInstance::Instance()->GetSalary();
 printf("My Salary is %d\n", iSalary);
 printf("Hello World!\n");
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灰暗角落里的琴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值