1 inf.h
#pragma once
class ITest
{
public:
virtual void sayMe() = 0;
virtual void showMessage() = 0;
virtual void sayBye() = 0;
};
ITest* getTestInf();
2. inf.cpp
#include "inf.h"
#include <iostream>
using namespace std;
class MyIMpl : public ITest
{
public:
static MyIMpl* instance()
{
if (MyIMpl::inst == nullptr)
MyIMpl::inst = new MyIMpl;
if (MyIMpl::inst == nullptr)
MyIMpl::inst = new MyIMpl;
return MyIMpl::inst;
}
private:
MyIMpl() : kk(1) {}
virtual void sayMe() { cout << "I am MyImpl " << kk << endl; }
virtual void showMessage() { cout << "today is a happy day" << endl; }
virtual void sayBye() { cout << "byebye " << --kk << endl; delete this; }
private:
static MyIMpl* inst;
int kk;
};
MyIMpl* MyIMpl::inst = nullptr;
ITest* getTestInf()
{
return (ITest*)(MyIMpl::instance());
}
3. infTest.cpp
// infTest01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include "inf.h"
int main()
{
std::cout << "Hello World!\n";
ITest* inf = getTestInf();
inf->sayMe();
inf->showMessage();
inf->sayBye();
}
4. 运行结果显示