1. Strategy design mode
Policy pattern: depending on c + + polymorphism, the pointer of abstract class can access all subclass objects, (pure virtual function), and one pointer can access all policy implementation classes.
#include <iostream> using namespace std; /*Strategy design pattern*/ class Strategy { public: Strategy(){} virtual ~Strategy(){} virtual void strategy()=0; }; //Implementation strategy A class ContoneStrategyA: public Strategy { public: virtual void strategy() { cout<<"strategy A"<<endl; } }; //Implementation strategy B class ContoneStrategyB: public Strategy { public: virtual void strategy() { cout<<"strategy B"<<endl; } }; class Context { Strategy *sty; public: Context(Strategy* s){this->sty = s;} ~Context() { delete sty; } void doWork() { sty->strategy(); } }; int main() { Context *ct ; ct = new Context(new ContoneStrategyA()); ct->doWork(); delete ct; ct = new Context(new ContoneStrategyB()); ct->doWork(); return 0; }
2. Single design mode
Singleton mode: Singleton mode ensures that a class has only one instance, and it instantiates itself and provides the whole system with this instance singleton mode (a program cannot be opened twice); singleton mode is also called singleton mode and singleton mode. There are many places that need such functional modules, such as the log output of the system.
#include <iostream> using namespace std; /*Single design mode*/ class LcdDevice { LcdDevice(){} LcdDevice(LcdDevice& lcd){} public: ~LcdDevice(){} static LcdDevice* getInstance();//Static member function protected: static LcdDevice * instance;//Define static member variable -- LcdDevice pointer }; LcdDevice* LcdDevice::instance = nullptr;//Allocate 8 bytes in data segment and initialize to nullptr LcdDevice* LcdDevice::getInstance() { if(instance == nullptr) { instance = new LcdDevice();//Create an lcd object } return instance; } void fun() { LcdDevice* lcd = LcdDevice::getInstance(); } int main() { LcdDevice* lcd = LcdDevice::getInstance(); return 0; }
3. Adapter design mode
Adapter pattern: transform the interface of one class into another expected by the client, so that the two classes that could not work together due to interface mismatch can work together.
Existing power supply 220v
Required power supply 5v
Transfer 220v to 5v --- this process is called adaptation
#include <iostream> using namespace std; class chargeHigh{ public: virtual void outHigh(){ cout<<"out high"<<endl; } }; class chargeLow{ public: virtual void outLow()=0; }; class Adapter:public chargeHigh, public chargeLow { public: virtual void outLow() { this->high_to_low(); cout<<"out low"<<endl; } void high_to_low() { this->outHigh(); cout<<"high to low"<<endl; } }; int main() { chargeLow *low = new Adapter(); low->outLow(); return 0; }