DesignPattern_05_开闭原则

开闭原则

Open Closed Principle

开闭原则是编程中最基础的、最重要的设计原则
一个软件实体如类,模块,函数应该对扩展开放,对修改关闭。用抽象构建框架,用实现扩展细节
当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码实现变化
编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则

代码编写

问题代码

/**
 * @author huangqh
 * @create 2020/9/8 1:28
 */
public class Ocp {
    
    
    public static void main(String[] args) {
    
    
        //使用,查看出现的问题
        //违反了OCP原则,即对扩展开放,对修改关闭
        //即当给类添加新的功能的时候,尽量不修改代码,或尽可能少修改代码
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        //新增三角形时,不能实现
        graphicEditor.drawShape(new Triangle());
    }
}

//这是一个用于绘图的类
class GraphicEditor {
    
    
    //接收Shape对象,根据type,绘制不同的图形
    public void drawShape(Shape s) {
    
    
        if (s.m_type == 1)
            drawRectangle(s);
        else if (s.m_type == 2)
            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;
    }
}

//新增三角形
class Triangle extends Shape {
    
    
    Triangle() {
    
    
        super.m_type = 3;
    }
}

开闭原则

/**
 * @author huangqh
 * @create 2020/9/8 1:28
 */
public class Ocp {
    
    
    public static void main(String[] args) {
    
    
        //使用,查看出现的问题
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }
}

//这是一个用于绘图的类
class GraphicEditor {
    
    
    //接收Shape对象,绘制不同的图形
    public void drawShape(Shape s) {
    
    
        s.draw();
    }
}

//Shape类 基类
abstract class Shape {
    
    
    int m_type;

    public abstract void draw();
}

class Rectangle extends Shape {
    
    
    Rectangle() {
    
    
        super.m_type = 1;
    }

    public void draw() {
    
    
        System.out.println("矩形");
    }
}

class Circle extends Shape {
    
    
    Circle() {
    
    
        super.m_type = 2;
    }

    public void draw() {
    
    
        System.out.println("圆形");
    }
}

//新增三角形
class Triangle extends Shape {
    
    
    Triangle() {
    
    
        super.m_type = 3;
    }

    public void draw() {
    
    
        System.out.println("三角形");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38438909/article/details/108459713
今日推荐