[设计模式]依赖倒转原则
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[设计模式]依赖倒转原则相关的知识,希望对你有一定的参考价值。
代码如下:
#include <iostream>
#include <string>
using namespace std;
//银行工作人员
class BankWorker
{
public:
void saveService()
{
cout << "办理存款业务" << endl;
}
void payService()
{
cout << "办理支付业务" << endl;
}
void transferService()
{
cout << "办理转账业务" << endl;
}
};
//中层模块
void doSaveBussiness(BankWorker *worker)
{
worker->saveService();
}
void doPayBussiness(BankWorker *worker)
{
worker->payService();
}
void doTransferBussiness(BankWorker *worker)
{
worker->transferService();
}
void test01()
{
BankWorker *worker = new BankWorker;
doSaveBussiness(worker);
doPayBussiness(worker);
doTransferBussiness(worker);
}
int main()
{
test01();
return 0;
}
依赖倒转原则
代码如下:
#include <iostream>
#include <string>
using namespace std;
class AbstractWorker
{
public:
virtual void doBusiness() = 0;
};
class SaveBankWorker :public AbstractWorker
{
public:
virtual void doBusiness()
{
cout << "办理存款业务" << endl;
}
};
class PayBankWorker :public AbstractWorker
{
public:
virtual void doBusiness()
{
cout << "办理支付业务" << endl;
}
};
class TransferBankWorker :public AbstractWorker
{
public:
virtual void doBusiness()
{
cout << "办理转账业务" << endl;
}
};
//中层模块
void doNewBusiness(AbstractWorker *worker)
{
worker->doBusiness();
delete worker;
}
void test01()
{
doNewBusiness(new TransferBankWorker);
doNewBusiness(new PayBankWorker);
doNewBusiness(new SaveBankWorker);
}
int main()
{
test01();
return 0;
}
测试结果:
以上是关于[设计模式]依赖倒转原则的主要内容,如果未能解决你的问题,请参考以下文章