设计模式基本原则
最终目的,高内聚,低耦合
开放封闭原则类的改动是通过增加代码进行的,不是修改源代码
银行类案例代码
- #include<iostream>
- using namespace std;
- class BankWorker
- {
- public:
- void save()
- {
- cout << "存款" << endl;
- }
- void moveM()
- {
- cout << "取款" << endl;
- }
- void jiaofei()
- {
- cout << "缴费" << endl;
- }
- };
- class AbBankWorker
- {
- public:
- virtual void dothing() = 0;
- };
- class SaveBanker :public AbBankWorker
- {
- public:
- virtual void dothing()
- {
- cout << "存款" << endl;
- }
- };
- class MoveBanker :public AbBankWorker
- {
- public:
- virtual void dothing()
- {
- cout << "取款" << endl;
- }
- };
- class SaveBanker :public AbBankWorker
- {
- public:
- virtual void dothing()
- {
- cout << "缴费款" << endl;
- }
- };
- void main11()
- {
- BankWorker*bw = new BankWorker;
- bw->jiaofei();
- bw->moveM();
- bw->save();
- cout << "hello..." << endl;
- system("pause");
- return;
- }
- void main22()
- {
- AbBankWorker*bw = NULL;
- bw=new MoveBanker;
- bw->dothing();
- delete bw;
- return;
- }
- void main()
- {
- main22();
- system("pause");
- return;
- }
单一职责原则类的职责要单一,对外只提供一种功能,而引起内变化的原因都应该只有一个
依赖倒置原则依赖于抽象接口,不要依赖具体的实现类,也就是针对接口编程
- #include<iostream>
- using namespace std;
- class HardDisk
- {public:
- virtual void work();
- };
- class Memory
- {
- public:
- virtual void work();
- };
- class Cpu
- {
- public:
- virtual void work();
- };
- class ComPuter
- {
- public:
- ComPuter(HardDisk*m_handdisk, Memory*m_memory, Cpu*m_cpu)
- {
- m_handdisk = handdisk;
- m_memory = memory;
- m_cpu = cpu;
- }
- public:
- void work()
- {
- m_handdisk->work();
- m_memory->work();
- m_cpu->work();
- }
- private:
- HardDisk*m_handdisk;
- Memory*m_memory;
- Cpu*m_cpu;
- };
- class InterCpu :public Cpu
- {
- public:
- void work()
- {
- cout << "我是因特尔厂家" << endl;
- }
- };
- class XSDisk :public HardDisk
- {
- public:
- void work()
- {
- cout << "我是西数硬盘厂家" << endl;
- }
- };
- class JSDMem :public Memory
- {
- public:
- void work()
- {
- cout << "我是JSDMem厂家" << endl;
- }
- };
- void main()
- {
- HardDisk*handdisk=NULL;
- Memory*memory=NULL;
- Cpu*cpu=NULL;
- handdisk = new XSDisk;
- memory= new JSDMem;
- cpu = new InterCpu;
- ComPuter*mycomputer = new ComPuter(harddisk, memory, cpu);
- mycomputer->work();
- delete mycomputer;
- delete cpu;
- delete memory;
- delete harddisk;
- cout << "hello" << endl;
- system("pause");
- return;
- }
接口隔离原则不应该强迫客户的程序依赖他们不需要的接口方法,一个接口应该是提供一种对外功能,不应该把所有的操作都封装到一个接口中去
里氏替换原则任何抽象类出现的地方都可以用它的实现类进行替换,实际就是虚拟机智语言级别,实现面向对象功能
优先使用组合而不是继承原则如果使用继承,会导致复位的任何变化,都可能影响此类的行为,如果使用对象组合,就降低了这种依赖关系
迪米特法则一个对象应当对其他对象尽可能少的了解,从而降低各个对象之间的耦合,提高系统的可维护性。例如,在一个程序中,各个模块之间相互调用时,通常会提供一个统一的接口来实现,这样其他模块不需要了解另外一个模块的内部实现细节,这样当一个模块内部的实现发生改变的时候,不会影响其他模块的使用黑盒原理。