开闭原则

开闭原则

Open Closed Principle

基本介绍

  • 开闭原则是编程中最基础、最重要的设计原则
  • 一个软件实体如类,模块和函数应该对扩展开放,对修改关闭。用抽象构建框架,用实体扩展细节。
  • 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
  • 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。
public class Ocp{
    public status void main(String[] args){
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
    }
}
class GraphicEditor{
    public void drawShape(Shape shape){
        shape.draw();
    }
}
//Shape类,基类
abstract class Shape{
    int m_type;
    public abstract void draw();//抽象方法
}
class Rectangle extends Shape{
    Rectangle(){
        super.m_type = 1;
    }
    @Override
    public void draw(){
        System.out.println("绘制矩形")
    }
}
class Circle extends Shape{
    Circle(){
        super.m_type = 2;
    }
    @Override
    public void draw(){
        System.out.println("绘制圆形")
    }
}
Licensed under CC BY-NC-SA 4.0
Last updated on Mar 23, 2024 06:11 UTC
让过去的过去,给时间点时间
Built with Hugo
Theme Stack designed by Jimmy