对提供方开放,对使用方关闭
问题代码
public class Ocp {
public static void main(String[] args) {
// 使用,发现存在的问题
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
// 用于绘图的类,使用方 class GraphicEditor { //接受Shape对象,然后根据type绘制不同的图形 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) 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(" 三角"); } }
// 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; } }
改进
public class OcpImpro {
public static void main(String[] args) {
//使用,发现存在的问题
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
graphicEditor.drawShape(new OtherGraphic());
}
}
//用于绘图的类,使用方
class GraphicEditor {
//接受Shape对象,然后根据type绘制不同的图形
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 Triangle extends Shape {
Triangle() {
super.m_type = 3;
}
@Override
public void draw() {
System.out.println("三角形");
}
}
//新增一个图形
class OtherGraphic extends Shape {
OtherGraphic() {
super.m_type = 3;
}
@Override
public void draw() {
System.out.println("其他图形");
}
}