当前位置: 移动技术网 > IT编程>软件设计>设计模式 > java设计模式学习笔记--开闭原则

java设计模式学习笔记--开闭原则

2020年01月11日  | 移动技术网IT编程  | 我要评论

三国志11mod,恶汉全文阅读,欢颜网

基本介绍

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

先来一段代码展示

public class ocp {
    public static void main(string[] args) {
        // 使用,看看存在的问题
        graphiceditor graphiceditor = new graphiceditor();
        graphiceditor.drawcircle(new shape());
        graphiceditor.drawrectangle(new shape());
        graphiceditor.drawother(new shape());

    }
}

//这是一个用于绘图的类
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) { 
            // 需在使用方添加(else if)代码快
            drawother(s);
        }
    }

    public void drawrectangle(shape s) {
        system.out.println("这是矩形");
    }

    public void drawcircle(shape s) {
        system.out.println("这是圆形");
    }

    // 需在使用方添加新的方法
    public void drawother(shape s) {
        system.out.println("这是其他图形");
    }
}

class shape {
    int m_type;
}

class rectangle extends shape {
    rectangle() {
        super.m_type = 1;
    }
}

class circle extends shape {
    circle() {
        super.m_type = 2;
    }
}

class other extends shape {
    other() {
        super.m_type = 3;
    }
}

分析这段代码中存在的问题

1、代码简单易懂,思路清晰。
2、但违反了设计模式的ocp原则,即对扩展开放,对修改关闭。即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少修改代码。
3、每增加一个功能都要需在使用方添加(else if)代码快,过多的(else if)会使代码过于臃肿,运行效率不高。

改进思路

创建一个shape类,并提供一个抽象的draw()方法,让子类实现该方法。每当增加一个图形种类时,让该图形种类继承shape类,并实现draw()方法。这样,使用方只需编写一个drawshape方法,传入一个图形类的对象,即可使用其相应的绘图方法。只需要修改提供方的代码,不需要修改使用方的代码,遵循ocp原则

使用ocp原则

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 other());

    }
}

//这是一个用于绘图的类,[使用方]
class graphiceditor {
    // 接收shape对象,调用其对应的draw方法
    public void drawshape(shape s) {
        s.draw();
    }
}

//shape类,基类
abstract class shape {
    public 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 other extends shape {
    other() {
        super.m_type = 3;
    }

    @override
    public void draw() {
        system.out.println("这是其他图形");
    }
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网