设计模式-单例模式

单例模式: 
#include<iostream>
using namespace std;
/*
 一是某个类只能有一个实例
 二是它必须自行创建这个实例
 三是它必须自行向整个系统提供这个实例
*/
class Sig {
public:
 static Sig* getPoint()
 {
  return point;
 }
private:
 Sig()
 {
  cout << "Sig" << endl;
 }
 static Sig * point;
};
// 静态成员 只能别静态成员函数调用
// 静态成员函数初始化 在定义时初始化
// 类的静态成员函数由于不含有this指针,只能引用其类的静态成员变量。通过类名+"::"的方式进行使用
Sig * Sig::point = new Sig;
int main()
{
 Sig * s1 = Sig::getPoint();

 system("pause");
 return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Printma
{
public:
 static Printma* getPoint()
 {
  count++;
  return new Printma;
 }
  void print(string text)
 {
   cout << "text=:" << text << endl;
   cout << "count=" << count << endl;
  
 }
private:
 Printma()
 {
  cout << "Printma" << endl;
 }
 static Printma * point;
 static int count;
};
Printma * Printma:: point = NULL;
int Printma::count = 0;

int main(void)
{
 Printma * p1 = Printma::getPoint();
 p1->print("aaaa");
 Printma * p2 = Printma::getPoint();
 p2->print("bbbb");
 system("pause");
 return 0;
}

#include <iostream>
#include <string>
using namespace std;
/*懒汉模式 在成员函数中初始化*/
class Printma
{
public:
 static Printma* getPoint()
 {
  count++;
  return new Printma;
 }
  void print(string text)
 {
   cout << "text=:" << text << endl;
   cout << "count=" << count << endl;
  
 }
private:
 Printma()
 {
  cout << "Printma" << endl;
 }
 static Printma * point;
 static int count;
};
Printma * Printma:: point = NULL;
int Printma::count = 0;

int main(void)
{
 Printma * p1 = Printma::getPoint();
 p1->print("aaaa");
 Printma * p2 = Printma::getPoint();
 p2->print("bbbb");
 system("pause");
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值