传统过程式设计

传统依赖关系

传统的过程式设计倾向于使高层次的模块依赖于低层次的模块,抽象层依赖于具体实现层

// 底层实现
class BankWorker{
public:
    void saveService(){
        cout << "办理存款业务..." << endl;
    }
    void transferService(){
        cout << "办理转账业务..." << endl;
    }
    void payService(){
        cout << "办理支付业务..." << endl;
    }
};
// 中层封装
void doSaveBusiness(BankWorker* worker){
    worker->saveService();
}
void doTransferBusiness(BankWorker* worker){
    worker->transferService();
}
void doPayBusiness(BankWorker* worker){
    worker->payService();
}
// 高层调用
void test1(){
    BankWorker* bw = new BankWorker;
    doSaveBusiness(bw);
    doPayBusiness(bw);
    doTransferBusiness(bw);
    delete bw;
}

依赖倒置

  • 高层模块(稳定) 不应该依赖于 低层模块(变化),二者都应该依赖于 抽象(稳定)
  • 抽象(稳定) 不应该依赖于 实现细节(变化),实现细节应该依赖于 抽象(稳定)

依赖倒转

// 抽象层
class AbstractWorker{
public:
    virtual void doBusiness() = 0;
};
// 实现层
class SaveBankWorker:public AbstractWorker{
public:
    void doBusiness()override{
        cout << "办理存款业务..." << endl;
    }
};
class PayBankWorker:public AbstractWorker{
public:
    void doBusiness()override{
        cout << "办理支付业务..." << endl;
    }
};
class TransferBankWorker:public AbstractWorker{
public:
    void doBusiness()override{
        cout << "办理转账业务..." << endl;
    }
};
// 业务封装
void doBusiness(AbstractWorker* aw){
    aw->doBusiness();
    delete aw;
}
// 高层调用
void test2(){
    doBusiness(new SaveBankWorker);
    doBusiness(new PayBankWorker);
    doBusiness(new TransferBankWorker);
}