高层模块不应该依赖低层模块,它们都应该依赖抽象。
抽象不应该依赖于细节,细节应该依赖于抽象。
减少类与类之间的耦合性,提高系统的稳定性和可读性。
小案例代码(正常写,不使用依赖倒置原则)
// 界面层
public interface ICalculatorForm
{
void Show();
}
// 业务逻辑层
public class CalculatorBLL
{
private Adder adder; // 加法类
private Subtractor subtractor; // 减法类
private Multiplier multiplier; // 乘法类
private Divider divider; // 除法类
public CalculatorBLL()
{
adder = new Adder();
subtractor = new Subtractor();
multiplier = new Multiplier();
divider = new Divider();
}
public double Add(double a, double b)
{
return adder.Calculate(a, b);
}
public double Subtract(double a, double b)
{
return subtractor.Calculate(a, b);
}
public double Multiply(double a, double b)
{
return multiplier.Calculate(a, b);
}
public double Divide(double a, double b)
{
return divider.Calculate(a, b);
}
}
小案例代码(使用依赖倒置原则重构后)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 依赖倒置原则(DIP)——案例
/// 高层模块不应该依赖低层模块,它们都应该依赖抽象。抽象不应该依赖于细节,细节应该依赖于抽象。
/// </summary>
public class OperationController : MonoBehaviour
{
private void Start()
{
Operation_Add operation_Add = new Operation_Add();
MyOperation myOperation_Add = new MyOperation(operation_Add);
Debug.Log(myOperation_Add.UnifyOperation(10, 20));
Operation_Sub operation_Sub = new Operation_Sub();
MyOperation myOperation_Sub = new MyOperation(operation_Sub);
Debug.Log(myOperation_Sub.UnifyOperation(10, 20));
Operation_Mul operation_Mul = new Operation_Mul();
MyOperation myOperation_Mul = new MyOperation(operation_Mul);
Debug.Log(myOperation_Mul.UnifyOperation(10, 20));
Operation_Div operation_Div = new Operation_Div();
MyOperation myOperation_Div = new MyOperation(operation_Div);
Debug.Log(myOperation_Div.UnifyOperation(10, 20));
}
}
/// <summary>
/// 运算逻辑层
/// </summary>
public class MyOperation
{
IOperation operation;//统一接口
public MyOperation(IOperation operation)
{
this.operation = operation;
}
public double UnifyOperation(double a,double b)
{
return operation.Calculate(a,b);
}
}
/// <summary>
/// 数据访问层
/// </summary>
public interface IOperation
{
double Calculate(double a, double b);
}
public class Operation_Add : IOperation
{
public double Calculate(double a, double b)
{
return a + b;
}
}
public class Operation_Sub : IOperation
{
public double Calculate(double a, double b)
{
return a - b;
}
}
public class Operation_Mul : IOperation
{
public double Calculate(double a, double b)
{
return a * b;
}
}
public class Operation_Div : IOperation
{
public double Calculate(double a, double b)
{
return a / b;
}
}