1.设计模式的基本原则:
开放封闭原则:类的改动应该是通过增加代码实现而不是更改代码
class BankWorker
{
public:
void save(){cout<<"存款"<<endl;}
void moveM(){cout<<"转账"<<endl}
void giveM(){cout<<"缴费"<<endl}
};
class AvBankeWorker
{
public:
virtual void dothing()=0;
};
class SaveBanker:public AvBankWOrker
{
public:
virtual void dothing(){cout<<"存款"<<endl;}
}
class moveMBanker:public AvBankWOrker
{
public:
virtual void dothing(){cout<<"转账"<<endl;}
}
class giveMBanker:public AvBankWOrker
{
public:
virtual void dothing(){cout<<"缴费"<<endl;}
}
void HowDo(AvBankWorker *bw)
{
bw->dothing();//多态
}
void main01()
{
BankWorker *bw=new BankWorker;
bw->save();
bw->moveM();
bw->giveM();
}
void main02()
{
AvBankWorker *bw = NULL;
bw=new saveMBanker;
HowDo();
delete bw;
bw=new moveMBanker;
HowDo();
delete bw;
bw=new giveMBanker;
HowDo();
delete bw;
}
void main()
{
//main01();
main02();
}
依赖倒置原则:
class Memory{
public:
virtual void work()=0;
};
class Cpu{
public:
virtual void work()=0;
}
class HardDisk{
public:
virtual void work()=0;
}
class Computer{
public:
Computer(Memory *Memory,HardDisk *harddisk, Cpu *cpu)
{
m_Memory = Memory;
m_harddisk = harddisk;
m_cpu = cpu;
}
void work()
{
m_harddisk->work();
m_cpu->work();
m_Memory->work();
}
private:
Memory *m_Memory;
HardDisk *m_harddisk;
Cpu *m_cpu;
}
class IntelCpu:public Cpu{
public:
virtual void work(){cout<<"Intel"<<endl}
}
class LenovoCpu:public Cpu{
public:
virtual void work(){cout<<"Lenovo"<<endl}
}
class WDHardDisk:public HardDisk{
public:
virtual void work(){cout<<"WD"<<endl};
}
class JSD:public Memory{
public:
virtual void work(){cout<<"JSD"<<endl};
};
void main()
{
HardDisk *harddisk=new WDHardDisk;
Memory *memory=new JSD;
Cpu *cpu=new LenovoCpu;
Computer *my_computer()=new Computer(harddisk,memory,cpu)
my_computer->work();
delete cpu;
delete memory;
delete harddisk;
}
接口隔离原则,里氏替换原则,优先使用组合而不是继承原则,迪米特原则