开闭原则:

基本介绍:

1.开闭原则(Open Closed Principle)是编程中最基础,最重要的原则。

2.一个软件实体如类,模块和函数应该对扩展开饭,对修改关闭。用抽象构建框架,用实现扩展细节。

3.当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。

4.编程中遵循其它原则,以及使用设计模式的目的就是遵循开闭原则。

案例:

1.

package ocp;

public class Ocp {
public static void main(String[] args) {
//使用看看存在的问题
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawCircle(new Circle());
graphicEditor.drawRectangle(new Rectangle());
graphicEditor.drawTriangle(new Triangle());
}
}


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

public void drawRectangle(Shape r){
System.err.println("绘制矩形");
}

public void drawCircle(Shape s){
System.err.println("绘制圆形");
}

public void drawTriangle(Shape s){
System.err.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 Triangle extends Shape{
Triangle(){
super.m_type = 3;
}
}

优缺点:

1)优点是比较好理解,简单易操作。

2)缺点是违反了是设计模式的ocp原则,即“对扩展开饭,对修改关闭”。即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少的修改代码。

3)比如案例中增加了一个三角形绘制,需要对客户端那边要做修改,这是不对的。

2.对方案1的改进思路分析:

把创建Shape类做成抽象类,并提供一个抽象的draw方法,让子类去实现即可,这样我们有新的图形种类时,只需要让新的图形继承Shape,并实现draw方法即可,使用方的代码就不需要修改,这样就满足了:开闭原则。

package ocp;

public class Ocp1 {
public static void main(String[] args) {
//使用看看存在的问题
GraphicEditor1 graphicEditor1 = new GraphicEditor1();
graphicEditor1.drwaShape(new Rectangle1());
graphicEditor1.drwaShape(new Circle1());
graphicEditor1.drwaShape(new Triangle1());
}
}

class GraphicEditor1{
public void drwaShape(Shape1 s) {
s.draw();
}
}

abstract class Shape1{
int m_type;
public abstract void draw();
}

class Rectangle1 extends Shape1{
Rectangle1(){
super.m_type = 1;
}

@Override
public void draw() {
System.err.println("绘制矩形");
}
}

class Circle1 extends Shape1{
Circle1(){
super.m_type = 2;
}

@Override
public void draw() {
System.err.println("绘制圆形");
}
}

//新增画三角形
class Triangle1 extends Shape1{
Triangle1(){
super.m_type = 3;
}

@Override
public void draw() {
System.err.println("绘制三角形");
}
}