您的位置:首页 > 运维架构 > Apache

RHCE课程-RH253Linux服务器架设笔记五-APACHE服务器配置(3)

2009-05-08 20:43 537 查看
When talking about Object Oriented design, attributes and behaviors are more concepts than language constructs. For such design considerations, only the public elements of an object need generally be considered. Or protected, when you get to inheritance.

Consider the following:

csharp
class Point {
public int X, Y; // attribute
public Point(int x, int y) {
this.X = x;
this.Y = y;
}
public void moveX(int diff) { this.X += diff; } // behavior
}


An object variable can be considered an attribute by it's nature. However, it's considered very bad practice to ever expose variables to the public. What if you want to put a rule on the max value of x? How do you impose that on a variable? Remember, one of the big reasons to use OO techniques is to limit the impact of future changes.

csharp
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return this.x; } // attribute
public int getY() { return this.y; } // attribute
public void moveX(int diff) { this.x += diff; } // behavior
}


Now the only exposed elements of this object are methods. It's a little awkward, but it's good practice. Functionally, X is readonly. To make it read write, we can add a setX method. "Getters and setters" are part of a Java best practive for attributes. But they aren't implicit, they just follow a naming convention. In C# we can use a elegant solution: Properties.

csharp
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int X { get { return this.x; } set { this.x = value } } // attribute
public int Y { get { return this.y; } } // attribute ( read only )
public void moveX(int diff) { this.x += diff; } // behavior
}


With the properties we can give object attributes in a natural way. The following example works with the first class and the last one:

csharp
Point pt = new Point(2,3);
pt.X = 5;


For a program, a Property actually feels like a variable, serves as an OO attribute, and has the functionality of a method.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: