开闭原则 Open Closed Principle

开闭原则的介绍:

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


  

错误示例

package com.kittenplus.principle.ocp;

    public class ocp {
        public static void main(String[] args) {
            GraphicEditor ge = new GraphicEditor();
            ge.drawShape(new Rectangle() );
            ge.drawCircle(new Circle());
        }}
        
    //这是一个用于绘图的类
        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;
        }
}

package com.kittenplus.principle.ocp;

    public class ocp {
        public static void main(String[] args) {
            GraphicEditor ge = new GraphicEditor();
            ge.drawShape(new Rectangle() );
            ge.drawShape(new Circle());
            ge.drawShape(new Triangle());
            ge.drawShape(new OtherGraphic());
        }}
        
    //这是一个用于绘图的类
        class GraphicEditor {
    //接收Shape对象,然后根据Type绘制不同的图形
        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;
        }
        @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 OtherGraphic extends Shape{
            OtherGraphic(){
                super.m_type=4;
            }
            @Override
            public void draw() {
            System.out.println(" 绘制其他图形");    
            }
    }
        
        
    

猜你喜欢

转载自www.cnblogs.com/thinkAboutMore/p/12407369.html