Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Вообще говоря, вскрытие реализации может привести ко многим подводным камням:
- например:
- class Rectangle {
- public:
- double x_right, x_left, y_bottom, y_top;
- double getWidth() {
- return sqrt(sqr(x_right - x_left) + sqr(...));
- }
- };
- Вроде норм.
- r.getWidth() работает всегда.
- можем обращаться r.x_left;
- Но допустим, мы не хотим много раз вычислять ширину, а делать это только один раз.
- class Rectangle {
- double cached_width;
- public:
- double x_right, x_left, y_bottom, y_top;
- Rectangle(...) {
- ...
- cached_width = -1;
- }
- double getWidth() {
- if(cached_width == -1)
- cached_width = sqrt(sqr(x_right - x_left) + sqr(...)
- return cached_width;
- }
- };
- Тогда если x_left, x_right открыты, то изменение координаты:
- r.x_left += 2;
- Сломает метод getWidth() (он больше не будет возвращать валидную ширину)
- Если же мы все спрячем и сделаем метод set_x_left, то мы можем контролировать ситуацию
- class Rectangle {
- double cached_width;
- double x_right, x_left, y_bottom, y_top;
- public:
- double get_x_left() { return x_left; }
- ...
- double set_x_left(double new_x_left) {
- x_left = new_x_left;
- cached_width = -1; // При следующем вызове getWidth() она будет вычислена заново
- }
- Rectangle(...) {
- ...
- cached_width = -1;
- }
- double getWidth() {
- if(cached_width == -1)
- cached_width = sqrt(sqr(x_right - x_left) + sqr(...)
- return cached_width;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement