组装一台电脑

    1. //组装使用电脑
    2. //CPU抽象类
    3. class CPU
    4. {
    5. public:
    6. //抽象计算
    7. virtual void calculate() = 0;
    8. };
    9. //GPU抽象类
    10. class GPU
    11. {
    12. public:
    13. //抽象显示
    14. virtual void dispaly() = 0;
    15. };
    16. //Memory抽象类
    17. class Memory
    18. {
    19. public:
    20. //抽象存储
    21. virtual void storage() = 0;
    22. };
    23. //电脑类
    24. class Computer
    25. {
    26. public:
    27. Computer(CPU* cpu, GPU* gpu, Memory* mem) :m_cpu(cpu), m_gpu(gpu), m_mem(mem)
    28. {
    29. }
    30. //提供工作的函数
    31. void work()
    32. {
    33. //让零件工作起来,调用接口
    34. m_cpu->calculate();
    35. m_gpu->dispaly();
    36. m_mem->storage();
    37. }
    38. ~Computer()
    39. {
    40. if (NULL != m_cpu)
    41. {
    42. delete m_cpu;
    43. m_cpu = nullptr;
    44. }
    45. if (NULL != m_gpu)
    46. {
    47. delete m_gpu;
    48. m_gpu = nullptr;
    49. }
    50. if (NULL != m_mem)
    51. {
    52. delete m_mem;
    53. m_mem = nullptr;
    54. }
    55. }
    56. private:
    57. CPU* m_cpu; //cpu零件指针
    58. GPU* m_gpu; //gpu零件指针
    59. Memory* m_mem; //内存条零件指针
    60. };
    61. //具体厂商
    62. //Intel厂商
    63. class IntelCPU :public CPU
    64. {
    65. public:
    66. void calculate()
    67. {
    68. cout << "Intel CPU开始计算" << endl;
    69. }
    70. };
    71. class LenovoCPU :public CPU
    72. {
    73. public:
    74. void calculate()
    75. {
    76. cout << "Lenovo CPU开始计算" << endl;
    77. }
    78. };
    79. class IntelGPU :public GPU
    80. {
    81. public:
    82. void dispaly()
    83. {
    84. cout << "Intel GPU开始显示" << endl;
    85. }
    86. };
    87. class LenovoGPU :public GPU
    88. {
    89. public:
    90. void dispaly()
    91. {
    92. cout << "Lenovo GPU开始显示" << endl;
    93. }
    94. };
    95. class IntelMemory :public Memory
    96. {
    97. public:
    98. void storage()
    99. {
    100. cout << "Intel Memory开始存储数据" << endl;
    101. }
    102. };
    103. class LenovoMemory :public Memory
    104. {
    105. public:
    106. void storage()
    107. {
    108. cout << "Lenovo Memory开始存储数据" << endl;
    109. }
    110. };
    111. void test01()
    112. {
    113. //第一台零件
    114. CPU* intelCpu = new IntelCPU;
    115. GPU* intelGpu = new IntelGPU;
    116. Memory* intelMem = new IntelMemory;
    117. //创建第一台电脑
    118. Computer* computer1 = new Computer(intelCpu, intelGpu, intelMem);
    119. computer1->work();
    120. delete computer1;
    121. cout << "--------------------------" << endl;
    122. //创建第二台电脑
    123. Computer* computer2 = new Computer(new LenovoCPU, new LenovoGPU, new LenovoMemory);
    124. computer2->work();
    125. delete computer2;
    126. }
    127. int main(void)
    128. {
    129. test01();
    130. return 0;
    131. }