案例描述:
- 电脑主要组成部件为 CPU (用于计算) ,显卡 (用于显示) ,内存条 (用于存储)
- 将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
- 创建电脑类提供让电脑工作的函数,并且调用每个警件工作的接口
- 测试时组装三台不同的电脑进行工作
程序设计伪代码
测试代码
#include<iostream>
#include<string>
using namespace std;
//抽象不同的零件类
//抽象CPU类
class CPU
{
public:
virtual void calculate() = 0; //计算
};
//抽象VideoCard类
class VideoCard
{
public:
virtual void display() = 0;//显示
};
//抽象Memory类
class Memory
{
public:
virtual void storage() = 0;//存储
};
/****************************厂商一*****************/
///具体类继承抽象类
class IntelCPU:public CPU
{
public:
//计算
virtual void calculate()
{
cout << "Intel的CPU正式计算啦" << endl;
}
};
class IntelVideoCard:public VideoCard
{
public:
//显示
void display()
{
cout << "Intel的VideoCard正式显示啦" << endl;
}
};
class IntelMemory:public Memory
{
public:
//存储
virtual void storage()
{
cout << "Intel的Memory正式存储啦" << endl;
}
};
/****************************厂商二*****************/
///具体类继承抽象类
class LenovoCPU :public CPU
{
public:
//计算
virtual void calculate()
{
cout << "Lenovo的CPU正式计算啦" << endl;
}
};
class LenovoVideoCard :public VideoCard
{
public:
//计算
virtual void display()
{
cout << "Lenovo的CPU正式显示啦" << endl;
}
};
class LenovoMemory :public Memory
{
public:
//计算
virtual void storage()
{
cout << "Lenovo的Memory正式存储啦" << endl;
}
};
// 计算机类
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;
VideoCard *m_vc;
Memory *m_mem;
};
//组装电脑
void testComputer()
{
//第一台电脑零件
CPU *intelCpu = new IntelCPU;
VideoCard *Intelcard = new IntelVideoCard;
Memory *intelMem = new IntelMemory;
//创建第一台电脑
Computer *computerl = new Computer(intelCpu, Intelcard, intelMem);
computerl->work();
cout << "第1台电脑组装成功了" << endl;
delete computerl;
//创建第二台电脑
Computer *computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory);
computer2->work();
cout << "第2台电脑组装成功了" << endl;
delete computer2;
}
int main()
{
testComputer();
}
结果