UML—里氏替换原则

前端之家收集整理的这篇文章主要介绍了UML—里氏替换原则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

例子:

测试代码

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. //书类Book
  6. class Book
  7. {
  8. private:
  9. int width;
  10. int height;
  11. public:
  12. virtual void madeByWood()
  13. {
  14. cout<<"I'm made by wood!";
  15. }
  16. virtual void setI(int w,int h)
  17. {
  18. width=w;
  19. height=h;
  20. }
  21. virtual int getW()
  22. {
  23. return width;
  24. }
  25. virtual int getH()
  26. {
  27. return height;
  28. }
  29. };
  30.  
  31. //电子书类E_book
  32. class E_book:public Book
  33. {
  34. public:
  35. void madeByWood()
  36. {
  37. cout<<"I'm not made by wood!";
  38. }
  39. void setI(int w,int h)
  40. {
  41. Book::setI(0,0);
  42. }
  43. int getW()
  44. {
  45. return Book::getW();
  46. }
  47. int getH()
  48. {
  49. return Book::getH();
  50. }
  51. };
  52.  
  53. //测试类TextBook
  54. class TextBook
  55. {
  56. public:
  57. void caleArea(Book &book)
  58. {
  59. try
  60. {
  61. if(book.getW()==0&&book.getH()==0)
  62. throw 0;
  63. int area=book.getW()*book.getH();
  64. cout<<"书的面积为:"<<area<<endl;
  65. }
  66. catch(int)
  67. {
  68. cout<<"An error occured!"<<endl;
  69. }
  70. }
  71. };
  72.  
  73. int main()
  74. {
  75. Book b;
  76. b.setI(8,12);
  77. E_book e;
  78. e.setI(0,0);
  79. TextBook t;
  80. t.caleArea(b);
  81. t.caleArea(e);
  82. return 0;
  83. }

运行结果:


里氏替换原则:




猜你在找的设计模式相关文章