多态案例–组装三台电脑
- 电脑零件基类CPU,显卡,内存条
- 不同的厂商,如Intel,Lenovo等;
- 三个零件基类,CPU,Videocard,Memory;不同厂商生产的零件来实现具体的功能。
#include <iostream>
using namespace std;
class CPU
{
public:
virtual void calculate() = 0;
};
class Videocare
{
public:
virtual void display() = 0;
};
class Memory
{
public:
virtual void storage() = 0;
};
class IntelCPU : public CPU
{
public:
virtual void calculate()
{
cout << "IntelCPU is calculating\n";
}
};
class IntelVideocard : public Videocare
{
public:
virtual void display()
{
cout << "Intel Videocard is displaying\n";
}
};
class IntelMemory : public Memory
{
public:
virtual void storage()
{
cout << "Intel Memory is storaging\n";
}
};
class LenovoCPU : public CPU
{
public:
virtual void calculate()
{
cout << "LenovoCPU is calculating\n";
}
};
class LenovoVideocard : public Videocare
{
public:
virtual void display()
{
cout << "Lenovo Videocard is displaying\n";
}
};
class LenovoMemory : public Memory
{
public:
virtual void storage()
{
cout << "Lenovo Memory is storaging\n";
}
};
class Computer
{
private:
CPU* cpu;
Videocare* vc;
Memory* memory;
public:
Computer(CPU* cpu, Videocare* vc, Memory* memory)
{
this->cpu = cpu;
this->vc = vc;
this->memory = memory;
}
~Computer()
{
if (cpu != NULL)
{
delete cpu;
cpu = NULL;
}
if (cpu != NULL)
{
delete cpu;
cpu = NULL;
}
if (cpu != NULL)
{
delete cpu;
cpu = NULL;
}
}
void work()
{
cpu->calculate();
vc->display();
memory->storage();
}
};
void test1()
{
CPU* intelCpu = new IntelCPU;
Videocare* intelVc = new IntelVideocard;
Memory* memory = new IntelMemory;
Computer computer(intelCpu, intelVc, memory);
computer.work();
}
void test2()
{
Computer computer(new LenovoCPU, new LenovoVideocard, new LenovoMemory);
computer.work();
}
void test3()
{
Computer computer(new IntelCPU, new IntelVideocard, new LenovoMemory);
computer.work();
}
int main()
{
cout << "------------测试1开始-----------\n";
test1();
cout << "------------测试2开始-----------\n";
test2();
cout << "------------测试3开始-----------\n";
test3();
return 0;
}
|