代码示例
#include <iostream>
using namespace std;
#include <string>
/*********************器件基类,不用作什么事,让子类派生重写************************/
//cpu基类
class Cpu
{
public:
virtual void calculate() = 0;
};
//VideoCard基类
class VideoCard
{
public:
virtual void display() = 0;
};
//Memory基类
class Memory
{
public:
virtual void storage() = 0;
};
/*********************派生类,不同厂商的器件对基类器件进行重写************************/
/********Inter*********/
//cpu基类
class InterCpu:public Cpu
{
public:
void calculate()
{
cout << "inter cpu is doing work" <<endl;
}
};
//VideoCard基类
class InterVideoCard:public VideoCard
{
public:
void display()
{
cout << "inter videoCard is doing work" <<endl;
}
};
//Memory 基类
class InterMemory:public Memory
{
public:
void storage()
{
cout << "inter memory is doing work" <<endl;
}
};
/********lenovo*********/
//cpu基类
class lenovoCpu :public Cpu
{
public:
void calculate()
{
cout << "lenovo cpu is doing work" <<endl;
}
};
//VideoCard基类
class lenovoVideoCard:public VideoCard
{
public:
void display()
{
cout << "lenovo videoCard is doing work" <<endl;
}
};
//Memory基类
class lenovoMemory :public Memory
{
public:
void storage()
{
cout << "lenovo memory is doing work" <<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();
}
~Computer()
{
if(m_cpu)
{
delete m_cpu;
m_cpu = NULL;
}
if(m_vc)
{
delete m_vc;
m_vc = NULL;
}
if(m_mem)
{
delete m_mem;
m_mem = NULL;
}
}
private:
Cpu *m_cpu;
VideoCard *m_vc;
Memory *m_mem;
};
void test()
{
//第一台电脑 采用inter零件
Cpu *Intercpu = new InterCpu;
VideoCard *Intervc = new InterVideoCard;
Memory *Intermem = new InterMemory;
Computer *c1 = new Computer(Intercpu,Intervc,Intermem);
c1->work();
cout <<"--------------------------------------" <<endl;
//第二台电脑 采用lenovo零件
Computer *c2 = new Computer(new lenovoCpu,new lenovoVideoCard,new lenovoMemory);
c2->work();
delete c1;
delete c2;
}
int main()
{
test();
return 0;
}
输出结果