一、开闭原则
1、开闭原则是编程中最基础、最重要的原则。
2、一个软件实体比如类,模块,函数应该对扩展开放(对提供方),对修改关闭(对使用方),用抽象构建框架,用实现扩展细节。
3、当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有代码来实现变化。
4、编程中遵循其它原则,以及使用设计模式的目的就是遵循开闭原则。
示例代码:
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
}
}
//绘图类
class GraphicEditor{
//接收Shape对象,根据type 绘制不同图形
public void drawShape(Shape s){
if (s.m_type == 1){
drawRectangle(s);
} else {
drawCircle(s);
}
}
public void drawRectangle(Shape r){
System.out.println("矩形");
}
public void drawCircle(Shape r){
System.out.println("圆形");
}
}
//一个Shape基类
class Shape{
int m_type;
}
class Rectangle extends Shape {
Rectangle(){
super.m_type = 1;
}
}
class Circle extends Shape {
Circle() {
super.m_type = 2;
}
}
1、上述代码的优点:简单好理解,易操作。
2、缺点:违反了设计模式的ocp原则,即对扩展开放,对修改关闭,当我们需要给类增加新功能的时候,尽量不修改代码,或者尽可能的少修改代码。
符合开闭原则的代码:
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Triangle());
}
}
//绘图类
class GraphicEditor {
//接收Shape对象,根据type 绘制不同图形
public void drawShape(Shape s) {
s.draw();
}
}
//一个Shape基类
abstract class Shape {
int m_type;
abstract void draw();
}
class Rectangle extends Shape {
Rectangle() {
super.m_type = 1;
}
@Override
void draw() {
System.out.println("矩形");
}
}
class Circle extends Shape {
Circle() {
super.m_type = 2;
}
@Override
void draw() {
System.out.println("圆形");
}
}
class Triangle extends Shape {
Triangle(){
super.m_type = 3;
}
@Override
void draw() {
System.out.println("三角形");
}
}