案例描述:
    image.png
    过程分析:

    image.png
    示例:

    1. #include<iostream>
    2. #include<string>
    3. using namespace std;
    4. //CUP 抽象类
    5. class CPU
    6. {
    7. public:
    8. virtual void calculate()=0;
    9. };
    10. //显卡 抽象类
    11. class VideCard
    12. {
    13. public:
    14. virtual void display()=0;
    15. };
    16. //内存条 抽象类
    17. class Memory
    18. {
    19. public:
    20. virtual void storage()=0;
    21. };
    22. //电脑类
    23. class Computer
    24. {
    25. public:
    26. // 构造函数中传入三个零件指针
    27. Computer(CPU *cp,VideCard *vi,Memory *me)
    28. {
    29. m_cp=cp;
    30. m_vi=vi;
    31. m_me=me;
    32. }
    33. void show()
    34. {
    35. m_cp->calculate();
    36. m_vi->display();
    37. m_me->storage();
    38. }
    39. //提供工作的函数
    40. //{
    41. // 调用每个零件的接口
    42. //}
    43. ~Computer()
    44. {
    45. //释放CUP
    46. if(m_cp!=NULL)
    47. {
    48. delete m_cp;
    49. m_cp=NULL;
    50. }
    51. if(m_vi!=NULL)
    52. {
    53. delete m_vi;
    54. m_vi=NULL;
    55. }
    56. if(m_me!=NULL)
    57. {
    58. delete m_me;
    59. m_me=NULL;
    60. }
    61. }
    62. private:
    63. CPU *m_cp;
    64. VideCard *m_vi;
    65. Memory *m_me;
    66. };
    67. //具体的零件厂商
    68. //inter 厂商
    69. class InterCPU:public CPU
    70. {
    71. public:
    72. void calculate()
    73. {
    74. cout<<"Inter的CPU开始工作了"<<endl;
    75. }
    76. };
    77. class InterVideCard:public VideCard
    78. {
    79. public:
    80. void display()
    81. {
    82. cout<<"Inter的VideCard开始显示了"<<endl;
    83. }
    84. };
    85. class InterMemory:public Memory
    86. {
    87. public:
    88. void storage()
    89. {
    90. cout<<"Inter的Memory开始存储了"<<endl;
    91. }
    92. };
    93. class LenovoCPU:public CPU
    94. {
    95. public:
    96. void calculate()
    97. {
    98. cout<<"Lenovo的CPU开始工作了"<<endl;
    99. }
    100. };
    101. class LenovoVideCard:public VideCard
    102. {
    103. public:
    104. void display()
    105. {
    106. cout<<"Lenovo的VideCard开始显示了"<<endl;
    107. }
    108. };
    109. class LenovoMemory:public Memory
    110. {
    111. public:
    112. void storage()
    113. {
    114. cout<<"Lenovo的VideCard开始存储了"<<endl;
    115. }
    116. };
    117. void test01()
    118. {
    119. //第一台电脑的零件
    120. CPU *cp=new InterCPU;
    121. VideCard *vi =new InterVideCard;
    122. Memory *me=new InterMemory;
    123. //第一台电脑
    124. Computer *com1=new Computer(cp,vi,me);
    125. com1->show();
    126. delete com1;
    127. cout<<"*********************"<<endl<<endl;
    128. //第二台电脑
    129. Computer *com2=new Computer(new LenovoCPU,new LenovoVideCard,new LenovoMemory);
    130. com2->show();
    131. delete com2;
    132. }
    133. int main()
    134. {
    135. test01();
    136. return 0;
    137. }