C ++ singleton polymorphic experiment

C ++ singleton polymorphic experiment

#include <iostream>
using namespace std;
class Ceshi
{
public:	
	~Ceshi();
	//static Ceshi* getCeshi();
	virtual void printf();
	Ceshi*next;
protected:
	Ceshi();
	static Ceshi* ceshi;
};
class A:public Ceshi
{
public:	
	void printf();
	 static Ceshi* getA();
private:
	A();
	~A();
};
class B :public Ceshi
{
public:
	void printf();
	static Ceshi* getA();
private:
	B();
	~B();
};
Ceshi* Ceshi::ceshi = NULL;
Ceshi* A::getA() {//留一个接口创建A对象
	if (ceshi==NULL)
	{
		ceshi = new A();
		ceshi->next = NULL;	
	}
	else
	{
		Ceshi* another = new A();//创建异质链表
		another->next = ceshi;
		ceshi = another;
	}
	return ceshi;
}
Ceshi* B::getA() {//留一个接口创建B对象
	if (ceshi == NULL)
	{
		ceshi = new B();
		ceshi->next = NULL;
	}
	else
	{
		Ceshi* another = new B();//创建异质链表
		another->next = ceshi;
		ceshi = another;
	}
	return ceshi;
}
Ceshi::Ceshi()
{
	cout << "构造Ceshi" << endl;
}
Ceshi::~Ceshi()//单例模式一般不需要手动析构
{
	cout << "析构Ceshi" << endl;
}
void Ceshi::printf() {
	cout << "Ceshi" << endl;
}
void A::printf() {
	cout << "A" << endl;
}
void B::printf() {
	cout << "B" << endl;
}
A::A()
{
	cout << "构造A" << endl;
}
A::~A() {
	cout << "析构A" << endl;		
}
B::B()
{
	cout << "构造B" << endl;
}
B::~B()
{
	cout << "析构B" << endl;
}

void main() {
	Ceshi*my;
	//my = Ceshi::getCeshi();
	my = A::getA();
	my->printf();//发生多态
	my = B::getA();
	
	my->printf();//发生多态
}

Renderings:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44567289/article/details/90273838