开闭原则

官方定义

开闭原则(Open Close Principle),又称OCP原则

一个软件实体如类,模块和函数应该对扩展开放,对修改关闭

基本介绍

对扩展开放
对修改关闭

package OpenClosePrinciple;

public class OcpDemo {
    public static void main(String[] args) {
        new GraphicEditor().drawRectangle(new Rectangle());
        new GraphicEditor().drawCircle(new Circle());
        new GraphicEditor().drawCircle(new Triangle());
    }
}

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;
    }
}


class GraphicEditor {
    public void drawShape(Shape s) {
        if (s.m_type == 1) {
            drawRectangle(s);
        } else if (s.m_type == 2) {
            drawCircle(s);
        } else if (s.m_type == 3) {
            drawCircle(s);
        }
    }

    public void drawRectangle(Shape r) {
        System.out.println("  正在绘制矩形中------绘制成功");
    }

    public void drawCircle(Shape r) {
        System.out.println("   正在绘制圆形中-----绘制成功");
    }

    public void drawTriangle(Shape r) {
        System.out.println("   正在绘制三角形中-----绘制成功");
    }
}

改后

package OpenClosePrinciple.next;

public class OcpDemo {
    public static void main(String[] args) {
        new GraphicEditor().drawShape(new Circle());
        new GraphicEditor().drawShape(new Rectangle());
        new GraphicEditor().drawShape(new Triangle());
    }
}

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("   正在绘制圆形中-----绘制成功");
    }
}

class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }

    @Override
    public void draw() {
        System.out.println("   正在绘制三角形中-----绘制成功");
    }
}


class GraphicEditor {
    public void drawShape(Shape s) {
        s.draw();
    }
}

注意事项

  • 开闭原则是最基础最重要的设计原则
  • 开闭原则可以提高复用性和可维护性
posted @ 2021-04-16 21:28  我等着你  阅读(84)  评论(0编辑  收藏  举报