设计原则
参考:设计模式笔记
开闭原则
对扩展开放、修改关闭
迪米特原则
有一个中介类,最少知识原则
合成复用原则
它要求在软件复用时,要尽量先使用组合或者聚合等关联关系来实现,其次才考虑使用继承关系来实现。
定义一个Person类,Person中使用一个基类指针作为复用。
#include<bits/stdc++.h>
using namespace std;
class Car{
public:
virtual void run()=0;
};
class dazhong:public Car{
public:
virtual void run(){
cout<<"dazhong"<<endl;
}
};
class baoma:public Car{
public:
virtual void run(){
cout<<"baoma"<<endl;
}
};
//Person中使用一个基类指针作为复用
//只要是基类派生的类,都可以通过统一的接口实现调用
class Person{
private:
Car* car;
public:
void setCar(Car* c){
this->car=c;
}
void drive(){
car->run();
}
};
int main(){
Person* p=new Person();
Car* c=new dazhong();
p->setCar(c);
p->drive();
delete c;
c=new baoma();
p->setCar(c);
p->drive();
delete c;
return 0;
}
依赖倒转原则
高层业务逻辑依赖抽象层,具体的实现层也是依赖于抽象层。
#include<bits/stdc++.h>
using namespace std;
class AbustractWorker{
public:
virtual void work() = 0;
};
//业务员是抽象员工的具体实现
//存款业务员
class DepositWorker:public AbustractWorker{
public:
virtual void work(){
cout<<"办理存款业务"<<endl;
}
};
//取款业务员
class WithdrawWorker:public AbustractWorker{
public:
virtual void work(){
cout<<"办理取款业务"<<endl;
}
};
//转账业务员
class TransferWorker:public AbustractWorker{
public:
virtual void work(){
cout<<"办理转账业务"<<endl;
}
};
//中层业务,依赖于抽象员工的接口
void doWork(AbustractWorker *worker){
worker->work();
}
int main(){
AbustractWorker * worker = new DepositWorker();
doWork(worker);
delete worker;
worker = new WithdrawWorker();
doWork(worker);
delete worker;
worker = new TransferWorker();
doWork(worker);
delete worker;
return 0;
}