May 11th, 2012, 00:20 | #1 |
Senior Member
注册日期: Jul 2004
帖子: 174
|
problem on encapsulation of OO
One of the biggest benefits of encapsulation is that it allows programmers to change their minds about one part of a program without having to rewrite other parts. For example, suppose we want to represent rectangular sections of images. Our first attempt might store the XY coordinates of the rectangle’s bottom-left and upper-right corners, like this: class Rectangle(object): '''Represent a rectangular section of an image.''' def __init__(self, x0, y0, x1, y1): '' 'Create a rectangle with non-zero area. (x0,y0) is the lower left corner, (x1,y1) the upper right corner.'' ' self.x0 = x0 self.y0 = y0 self.x1 = x1 self.y1 = y1 def area(self): '''Return the area of the rectangle.''' return (self.x1 - self.x0) * (self.y1 - self.y0) def contains(self, x, y): '' 'Return True is (x,y) point is inside a rectangle, and False otherwise.'' ' return (self.x0 <= x <= self.x1) and \ (self.y0 <= y <= self.y1) Later, we might decide that it would be better to store the rectangle’s lower-left corner and XY size, like this: class Rectangle(object): '''Represent a rectangular section of an image.''' def __init__(self, x0, y0, width, height): '' 'Create a rectangle with non-zero area. (x0,y0) is the lower left corner, width and height the X and Y extent.'' ' self.x0 = x0 self.y0 = y0 self.width = width self.height = height def area(self): '''Return the area of the rectangle.''' return self.width * self.height def contains(self, x, y): '' 'Return True if (x,y) point is inside a rectangle, and False otherwise.'' ' return (self.x0 <= x) and (x <= self.x0 + width) and \ (self.y0 <= y) and (y <= self.y0 + height) If we made this change, we would obviously also have to change every piece of software that created new rectangles. However, we wouldn’t have to change code that used the area or contains methods—since they hide the details of how they calculate their results, we can change their operation without affecting anything else. 在后面的解释中:” we wouldn’t have to change code that used the area or contains methods—since they hide the details of how they calculate their results, we can change their operation without affecting anything else.” Area() 和Rectangle() 不是都改了吗? return (self.x0 <= x <= self.x1) and \ (self.y0 <= y <= self.y1) 变成了: return self.width * self.height return (self.x0 <= x <= self.x1) and \ (self.y0 <= y <= self.y1) 变成了: return (self.x0 <= x) and (x <= self.x0 + width) and \ (self.y0 <= y) and (y <= self.y0 + height) 怎么说:” we wouldn’t have to change code”? 不懂. 后面, 它又说:” we can change their operation without affecting anything else.” 难道说上面的改变只是它的操作的改变, 不是代码的改变? 那如果这个例子写成IF语句, 而不是返回语句, 放在函数里面, 代码不是改变了? |
|
May 11th, 2012, 12:43 | 只看该作者 #5 | |
不堪盈手赠 还寝梦佳期
注册日期: Jul 2004
帖子: 864
声望: 794908
|
引用:
代码:
if ( obj->Contains(x, y) == true ) { return obj->Area(); } else { return -1; } |
|
|