Advertisement
nolog1n

Untitled

Feb 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. Вообще говоря, вскрытие реализации может привести ко многим подводным камням:
  2. например:
  3.  
  4. class Rectangle {
  5. public:
  6. double x_right, x_left, y_bottom, y_top;
  7. double getWidth() {
  8. return sqrt(sqr(x_right - x_left) + sqr(...));
  9. }
  10. };
  11.  
  12. Вроде норм.
  13. r.getWidth() работает всегда.
  14. можем обращаться r.x_left;
  15.  
  16. Но допустим, мы не хотим много раз вычислять ширину, а делать это только один раз.
  17.  
  18. class Rectangle {
  19. double cached_width;
  20. public:
  21. double x_right, x_left, y_bottom, y_top;
  22. Rectangle(...) {
  23. ...
  24. cached_width = -1;
  25. }
  26. double getWidth() {
  27. if(cached_width == -1)
  28. cached_width = sqrt(sqr(x_right - x_left) + sqr(...)
  29. return cached_width;
  30. }
  31. };
  32.  
  33.  
  34. Тогда если x_left, x_right открыты, то изменение координаты:
  35. r.x_left += 2;
  36.  
  37. Сломает метод getWidth() (он больше не будет возвращать валидную ширину)
  38.  
  39. Если же мы все спрячем и сделаем метод set_x_left, то мы можем контролировать ситуацию
  40.  
  41. class Rectangle {
  42. double cached_width;
  43. double x_right, x_left, y_bottom, y_top;
  44. public:
  45.  
  46. double get_x_left() { return x_left; }
  47. ...
  48. double set_x_left(double new_x_left) {
  49. x_left = new_x_left;
  50. cached_width = -1; // При следующем вызове getWidth() она будет вычислена заново
  51. }
  52.  
  53. Rectangle(...) {
  54. ...
  55. cached_width = -1;
  56. }
  57. double getWidth() {
  58. if(cached_width == -1)
  59. cached_width = sqrt(sqr(x_right - x_left) + sqr(...)
  60. return cached_width;
  61. }
  62. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement