案例描述:
1.电脑主要组成部件为 CPU(用于计算),显卡(用于显示),内存条(用于存储)
2.将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
3.创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
4.测试时组装三台不同的电脑进行工作
#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 dowork()
{
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
~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;
};
class IntelCPU :public CPU
{
void calculate()
{
cout << "Intel的CPU开始计算了" << endl;
}
};
class IntelVideoCard :public VideoCard
{
void display()
{
cout << "Intel能够正常显示" << endl;
}
};
class IntelMemory :public Memory
{
void storage()
{
cout << "Intel能够正常存储" << endl;
}
};
class LenovoCPU :public CPU
{
void calculate()
{
cout << "Lenovo的CPU开始计算了" << endl;
}
};
class LenovoVideoCard :public VideoCard
{
void display()
{
cout << "Lenovo能够正常显示" << endl;
}
};
class LenovoMemory :public Memory
{
void storage()
{
cout << "Lenovo能够正常存储" << endl;
}
};
void test()
{
cout<<"第一台电脑开始工作:" << endl;
CPU* cpu= new IntelCPU;
VideoCard* vc= new IntelVideoCard;
Memory* mem= new IntelMemory;
Computer *computer1=new Computer(cpu, vc, mem);
computer1->dowork();
delete computer1;
cout<<"-----------------------------------" << endl;
cout << "第二台电脑开始工作:" << endl;
Computer* computer2 = new Computer(new LenovoCPU, new IntelVideoCard, new LenovoMemory);
computer2->dowork();
delete computer2;
cout << "-----------------------------------" << endl;
cout << "第三台电脑开始工作:" << endl;
Computer* computer3 = new Computer(new IntelCPU, new LenovoVideoCard, new LenovoMemory);
computer3->dowork();
delete computer3;
}
int main()
{
test();
system("pause");
return 0;
}