记录一下设计模式开闭原则的学习:
1,概念
开闭原则,在面向对象编程领域中,规定“软件中的对象(类,模块,函数等等)应该对于扩展是开放的,但是对于修改是封闭的”,这意味着一个实体是允许在不改变它的源代码的前提下变更它的行为,通常是定义一个抽象类,在其中定义抽象方法,定义子类去实现其中的抽象方法,这样在不修改源代码的情况下,拓展新的功能。
2,案例演示
1,不采用开闭原则进行设计
//main方法
public class Ocp {
public static void main(String[] args) {
GraphicEditor ge=new GraphicEditor();
ge.drawRectangle(new Rectangle());
ge.drawCircle(new Circle());
ge.drawTriangle(new Triangle());
}
}
//绘制图形的方法函数
public class GraphicEditor {
public void drawShape (shape s){
if(s.my_type == 1) drawRectangle(s);
else if(s.my_type ==2) drawCircle(s);
else if(s.my_type ==3) drawTriangle(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("绘制三角形");
}
}
//shape基类与拓展类
public class shape {
int my_type;
}
public class Rectangle extends shape{
Rectangle(){
super.my_type=1;
}
}
public class Circle extends shape{
Circle(){super.my_type =2;}
}
public class Triangle extends shape{ //需要增加的类
Triangle(){
super.my_type=3;
}
}
运行结果如下:
"C:\Program Files (x86)\Java\jdk1.8.0_151\bin\java.exe" "-javaagent:C:\Program
绘制矩形
绘制圆形
绘制三角形
在此方法下,若要增加新的绘图功能则需要修改绘制图形的方法函数GraphicEditor里面的代码,均以注释标出。
2,采用开闭原则进行设计
将shape类改进为抽象类,并提供一个抽象方法draw,让子类去实现即可,这样有新图形种类时,只需要让新的图形类继承shape,并实现draw方法即可。
public class opcdemo {
public static void main(String[] args) {
GraphicEditor ge=new GraphicEditor();
ge.drawShape(new Rectangle());
ge.drawShape(new Circle());
ge.drawShape(new Triangel());
}
}
class GraphicEditor{
public void drawShape(Shape s){s.draw();}
}
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 Triangel extends Shape{ //仅需增加子类
Triangel(){
super.m_type=3;
}
@Override
public void draw() {
System.out.println("绘制三角形");
}
}
运行结果:
绘制矩形
绘制圆形
绘制三角形