- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么组合要遵循“开放扩展,接近修改”的原则?
我理解:如果您想在类中添加功能,您只需编写新代码并使用组合来获取该代码。
但是你只是修改了你有组合的代码吗?因为您向该代码添加了组合,所以您修改了该代码。
示例:
之前是这样的:
public class Example{
public void Walk(){
//walking
}
}
之后:
public class Example{
RunClass r = new RunClass(); // I add this
public void Walk(){
//walking
}
public void Run(){ // I also add this
r.run();
}
}
所以这意味着我修改了这个类。
最佳答案
You need to take a look a the definitions first.
Composition is just a "has a" relationship, while inheritance Is a "is a" relationship. The open closed principle is about changing the behavior without altering the source code of a class. By themselves they don't ensure the OCP.
Design patterns follow the principle through composition or/and inheritance. E.g. The strategy design pattern uses composition to change bahavior at runtime, while the template method pattern uses inheritance to change behavior at compile time. So composition allows extension at runtime so while inheritance allows it at compile time. If you want your class to be sealed (can't be subclassed) the only available option is composition.
OCP is not ensured by composition, unless your design is loosely coupled. Remember that composition is just a "has a" relationship, which just says that your class has an instance of an object, but if you have to modify your code to change that instance, that doesn't follow the OCP. However if you use inversion of control (IoC), that composition becomes loosely coupled, therefore you don't have to change the code in your class. Here is an example:
不遵循 OCP 的构图
public class Bike {
Wheel wheel = new LargeWheel();
public void go(){
wheel.go();
}
遵循 OCP(通过 IoC)的组合
public class Bike {
Wheel wheel;
public setWheel(Wheel wheel){
this.wheel = wheel;
}
public void go(){
wheel.go();
}
在第一种情况下,如果您想要不同类型的轮子,则需要修改代码,但在第二种情况下,您“注入(inject)”所需的轮子实例。
关于java - 为什么构图要遵循开闭原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10373699/
我是一名优秀的程序员,十分优秀!