案例描述:
电脑主要组成部件CPU(用于计算),显卡(用于显卡),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
#include<iostream>
using namespace std;
#include<string>
//抽象不同零件类
//抽象计算函数
class CPU
{
public:
virtual void calculate() = 0;
};
//抽象显示函数
class VideoCard
{
public:
virtual void display() = 0;
};
//抽象存储函数
class Memory
{
public:
virtual void storage() = 0;
};
//电脑类
class Computer
{
public:
//构造函数中传入三个零件指针
Computer(CPU * cpu, VideoCard * vc, Memory * mem)
{
m_cpu = cpu;//指针接收
m_vc = vc;
m_mem = mem;
}
//提供工作的函数
void work()
{
//调用每个零件工作的接口
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
//提供析构函数,释放 3个电脑零件
~Computer()
{
if (m_cpu != NULL)
{
delete m_cpu;
m_cpu = NULL;
}
if (m_vc != NULL)
{
delete m_vc;
m_vc = NULL;
}
if (m_mem != NULL)
{
delete m_mem;
m_mem = NULL;
}
}
private:
CPU * m_cpu;//CPU的零件指针
VideoCard * m_vc;//显卡零件指针
Memory * m_mem;//内存零件指针
};
//具体厂商
//Intel厂商
class IntelCpu:public CPU
{
public:
virtual void calculate()
{
cout << "Intel的CPU开始计算了!" << endl;
}
};
class IntelVideoCard :public VideoCard
{
public:
virtual void display()
{
cout << "Intel的VideoCard开始显示了!" << endl;
}
};
class IntelMemory :public Memory
{
public:
virtual void storage()
{
cout << "Intel的Memory开始存储了!" << endl;
}
};
//Lenovo厂商
class LenovoCpu :public CPU
{
public:
virtual void calculate()
{
cout << "Lenovo的CPU开始计算了!" << endl;
}
};
class LenovoVideoCard :public VideoCard
{
public:
virtual void display()
{
cout << "Lenovo的VideoCard开始显示了!" << endl;
}
};
class LenovoMemory :public Memory
{
public:
virtual void storage()
{
cout << "Lenovo的Memory开始存储了!" << endl;
}
};
void test01()
{
//第一台电脑
CPU * intelCpu = new IntelCpu;//父类指向子类对象,//需释放
VideoCard * intelVCard = new IntelVideoCard;//需释放
Memory * intelMem = new IntelMemory;//需释放,
//1.直接delete 在 delete computer1; 后
//2.提供析构函数在 class Computer 中
//创建第一台电脑
Computer * computer1 = new Computer(intelCpu, intelVCard, intelMem);//需释放
computer1->work();
delete computer1;
cout << "-----------------------------" << endl;
cout << "第二台电脑开始工作" << endl;
//创建第二台电脑
Computer * computer2 = new Computer(new LenovoCpu, new LenovoVideoCard, new LenovoMemory);//需释放
computer2->work();
delete computer2;
cout << "-----------------------------" << endl;
cout << "第三台电脑开始工作" << endl;
//创建第三台电脑
Computer * computer3 = new Computer(new LenovoCpu, new IntelVideoCard, new LenovoMemory);//需释放
computer3->work();
delete computer3;
}
int main()
{
test01();
system("pause");
return 0;
}