OCP原则:开闭原则
1、对外能扩展(提供方)
2、对修改关闭(使用方)
下面这段代码实现了绘制形状的功能,如果设计如下:
package ocp;
/**
* @Author lihaiyu
* @Date 2020/11/8 20:50
*/
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
}
}
/**
* 这是一个用于绘制图形的类,【使用方】
*/
class GraphicEditor{
/**
* 接受Shage对象,然后根据Type,来绘制不同的图形
* @param shape
*/
public void drawShape(Shape shape){
if(shape.mType==1){
drawRectangle(shape);
}
else if(shape.mType==2){
drawCircle(shape);
}
}
private void drawRectangle(Shape shape){
System.out.println("绘制矩形");
}
private void drawCircle(Shape shape){
System.out.println("绘制圆形");
}
}
/**
* 基类
*/
class Shape{
int mType;
}
class Rectangle extends Shape{
Rectangle(){
super.mType=1;
}
}
class Circle extends Shape{
Circle(){
super.mType=2;
}
}
下面新增一个绘制三角形,来看一下代码改动了多少:
/**
* 这是一个用于绘制图形的类,【使用方】
*/
class GraphicEditor{
/**
* 接受Shage对象,然后根据Type,来绘制不同的图形
* @param shape
*/
public void drawShape(Shape shape){
if(shape.mType==1){
drawRectangle(shape);
}
else if(shape.mType==2){
drawCircle(shape);
}
else if(shape.mType==3){
drawTriangle(shape);
}
}
private void drawRectangle(Shape shape){
System.out.println("绘制矩形");
}
private void drawCircle(Shape shape){
System.out.println("绘制圆形");
}
private void drawTriangle(Shape shape){
System.out.println("绘制三角形");
}
}
/**
* 基类
*/
class Shape{
int mType;
}
class Rectangle extends Shape{
Rectangle(){
super.mType=1;
}
}
class Circle extends Shape{
Circle(){
super.mType=2;
}
}
/**
* 增加绘制三角形的类
*/
class Triangle extends Shape{
Triangle(){
super.mType=3;
}
}
1、扩展新增类
/**
* 增加绘制三角形的类
*/
class Triangle extends Shape{
Triangle(){
super.mType=3;
}
}
2、使用方增加了新方法也要修改
class GraphicEditor{
/**
* 接受Shage对象,然后根据Type,来绘制不同的图形
* @param shape
*/
public void drawShape(Shape shape){
if(shape.mType==1){
drawRectangle(shape);
}
else if(shape.mType==2){
drawCircle(shape);
}
else if(shape.mType==3){
drawTriangle(shape);
}
}
private void drawRectangle(Shape shape){
System.out.println("绘制矩形");
}
private void drawCircle(Shape shape){
System.out.println("绘制圆形");
}
private void drawTriangle(Shape shape){
System.out.println("绘制三角形");
}
}
显然违背了OCP原则,我们是希望使用方的修改是关闭的
根据开闭原则OCP修改代码:
package ocp1;
/**
* @Author lihaiyu
* @Date 2020/11/8 21:39
*/
public class OCP_1 {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
//使用方
class GraphicEditor{
public void drawShape(Shape shape){
shape.draw();
}
}
/**
* 基类
*/
abstract class Shape{
/**
* 绘制形状
*/
public abstract void draw();
}
class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
/**
* 增加绘制三角形的类
*/
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("绘制三角形");
}
}