设计模式七大原则五之开闭原则

基本介绍

1)开闭原则Open Closed Principle,重要设计原则

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

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

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

 

package com.hy.principle.ocp;

/**
* @author hanyong
* @date 2020/9/23 0:19
*/
public class Ocp {


public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShap(new Rectangle());
graphicEditor.drawShap(new Circle());
graphicEditor.drawShap(new Triangle());

}


}


class GraphicEditor {

public void drawShap(Shape shape) {
if (shape.m_type == 1) {
drawRectangle();
} else if (shape.m_type == 2) {
drawCircle();
}else if(shape.m_type==3){
drawTriangle();
}
}

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

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

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


package com.hy.principle.ocp.improve;

/**
* @author hanyong
* @date 2020/9/23 0:19
*/
public class Ocp {


public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShap(new Rectangle());
graphicEditor.drawShap(new Circle());
graphicEditor.drawShap(new Triangle());
graphicEditor.drawShap(new WujiaoStar());
}


}


class GraphicEditor {

public void drawShap(Shape shape) {
shape.draw();
}


}

abstract class Shape {
int m_type;
//使用方没有变动,修改关闭
abstract void draw();

}

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

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

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

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

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

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

}
//扩展开放
//添加一种,改动少
class WujiaoStar extends Shape {

@Override
void draw() {
System.out.println("绘制五角星");
}
}
posted @ 2020-09-23 00:42  yongzhewuwei  阅读(144)  评论(0编辑  收藏  举报