开闭原则
使用开闭原则之前一个银行柜员会将所有的工作都操作一遍,这样会大大降低办事的效率,而且银行的业务不适合扩展,没扩展一项业务就要培训所有的业务员。改为使用开闭原则之后,每个银行业务员只负责一项业务即可,这样做增加了系统的复杂性,但是想要新增业务只需要增加个人员,培训一个人新技能即可。也即是增加系统复杂性,但是原有的基础不变的情况下就可实现对业务的扩展。
具体的CPP
代码如下:
#include <iostream>
using namespace std;
// 在使用开闭原则之前
// 所有的事情都一个对象中完成,显得类很臃肿
class BankWorker
{
public:
void SaveMoney(void)
{
cout << "save money" << endl;
}
void WithdrawMoney(void)
{
cout << "withdraw money" << endl;
}
void TransferMoney(void)
{
cout << "transfer money" << endl;
}
};
/* 使用开闭原则之后 */
// 定义一个虚类,相当于java中的接口
class OcpBankWorker
{
public:
virtual void DoSomething(void) = 0;
};
// 虚函数实现
class SaveBankWorker : public OcpBankWorker
{
public:
virtual void DoSomething(void)
{
cout << "save money ocp" << endl;
}
};
class WithdrawBankWorker : public OcpBankWorker
{
public:
virtual void DoSomething(void)
{
cout << "withdraw money ocp" << endl;
}
};
class TransferBankWorker : public OcpBankWorker
{
public:
virtual void DoSomething(void)
{
cout << "transfer money ocp" << endl;
}
};
// 框架函数
void HowDo(OcpBankWorker &ocpBankWorker)
{
ocpBankWorker.DoSomething();
}
// 使用多态的三个原则
// 1.要有继承
// 2.要有函数重写
// 3.要有父类指针(父类引用)指向子类对象
int main(int argc, char const *argv[])
{
// 在使用开闭原则之前
cout << "before use open close principle" << endl;
BankWorker *bw = new BankWorker;
bw->SaveMoney();
bw->TransferMoney();
bw->WithdrawMoney();
cout << "=========================================" << endl;
// 使用开闭原则之后
// 使用多态技术实现
OcpBankWorker *aw = NULL;
aw = new SaveBankWorker;
HowDo(*aw);
delete aw;
aw = new WithdrawBankWorker;
HowDo(*aw);
delete aw;
aw = new TransferBankWorker;
HowDo(*aw);
delete aw;
cout << "open close principle" << endl;
return 0;
}
上述程序执行之后输出结果:
before use open close principle
save money
transfer money
withdraw money
=========================================
save money ocp
withdraw money ocp
transfer money ocp
open close principle
转载:https://blog.csdn.net/andrewgithub/article/details/108949749
查看评论