案例描述:
过程分析:
示例:
#include<iostream>
#include<string>
using namespace std;
//CUP 抽象类
class CPU
{
public:
virtual void calculate()=0;
};
//显卡 抽象类
class VideCard
{
public:
virtual void display()=0;
};
//内存条 抽象类
class Memory
{
public:
virtual void storage()=0;
};
//电脑类
class Computer
{
public:
// 构造函数中传入三个零件指针
Computer(CPU *cp,VideCard *vi,Memory *me)
{
m_cp=cp;
m_vi=vi;
m_me=me;
}
void show()
{
m_cp->calculate();
m_vi->display();
m_me->storage();
}
//提供工作的函数
//{
// 调用每个零件的接口
//}
~Computer()
{
//释放CUP
if(m_cp!=NULL)
{
delete m_cp;
m_cp=NULL;
}
if(m_vi!=NULL)
{
delete m_vi;
m_vi=NULL;
}
if(m_me!=NULL)
{
delete m_me;
m_me=NULL;
}
}
private:
CPU *m_cp;
VideCard *m_vi;
Memory *m_me;
};
//具体的零件厂商
//inter 厂商
class InterCPU:public CPU
{
public:
void calculate()
{
cout<<"Inter的CPU开始工作了"<<endl;
}
};
class InterVideCard:public VideCard
{
public:
void display()
{
cout<<"Inter的VideCard开始显示了"<<endl;
}
};
class InterMemory:public Memory
{
public:
void storage()
{
cout<<"Inter的Memory开始存储了"<<endl;
}
};
class LenovoCPU:public CPU
{
public:
void calculate()
{
cout<<"Lenovo的CPU开始工作了"<<endl;
}
};
class LenovoVideCard:public VideCard
{
public:
void display()
{
cout<<"Lenovo的VideCard开始显示了"<<endl;
}
};
class LenovoMemory:public Memory
{
public:
void storage()
{
cout<<"Lenovo的VideCard开始存储了"<<endl;
}
};
void test01()
{
//第一台电脑的零件
CPU *cp=new InterCPU;
VideCard *vi =new InterVideCard;
Memory *me=new InterMemory;
//第一台电脑
Computer *com1=new Computer(cp,vi,me);
com1->show();
delete com1;
cout<<"*********************"<<endl<<endl;
//第二台电脑
Computer *com2=new Computer(new LenovoCPU,new LenovoVideCard,new LenovoMemory);
com2->show();
delete com2;
}
int main()
{
test01();
return 0;
}