单例模式:
#include<iostream>
#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;
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();
{
Sig * s1 = Sig::getPoint();
system("pause");
return 0;
}
}
#include <iostream>
#include <string>
#include <string>
using namespace std;
class Printma
{
public:
static Printma* getPoint()
{
count++;
return new Printma;
}
{
public:
static Printma* getPoint()
{
count++;
return new Printma;
}
void print(string text)
{
cout << "text=:" << text << endl;
cout << "count=" << count << endl;
}
{
cout << "text=:" << text << endl;
cout << "count=" << count << endl;
}
private:
Printma()
{
cout << "Printma" << endl;
}
Printma()
{
cout << "Printma" << endl;
}
static Printma * point;
static int count;
};
Printma * Printma:: point = NULL;
int Printma::count = 0;
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");
p2->print("bbbb");
system("pause");
return 0;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
/*懒汉模式 在成员函数中初始化*/
class Printma
{
public:
static Printma* getPoint()
{
count++;
return new Printma;
}
/*懒汉模式 在成员函数中初始化*/
class Printma
{
public:
static Printma* getPoint()
{
count++;
return new Printma;
}
void print(string text)
{
cout << "text=:" << text << endl;
cout << "count=" << count << endl;
}
{
cout << "text=:" << text << endl;
cout << "count=" << count << endl;
}
private:
Printma()
{
cout << "Printma" << endl;
}
Printma()
{
cout << "Printma" << endl;
}
static Printma * point;
static int count;
};
Printma * Printma:: point = NULL;
int Printma::count = 0;
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");
p2->print("bbbb");
system("pause");
return 0;
}
return 0;
}