七大常用设计模式

七大常用设计模式

设计模式共分为三种类型:创建型,结构型和行为型,每一种类型有很多不同的设计模式,而设计模式一共多达二十多种。这里对常用的七个设计模式进行说明,每一种设计模式都配有相应的代码,而测试代码没有编写,若有需要请自行编写。

创建型:

  1. 单例模式
    某些时候,创建一个类的很多实例并没有得到很好的使用,而且不断的创建和销毁不仅费时而且占用系统资源,造成系统的性能下降,而如果一个类只存在一个实例就可以解决所有问题,那么就可以将此类封装为单例模式。
    class Singleton{
    public:
        static Singleton* getInstance(){
            if(!instance){
                instance = new Singleton;
            }
            return instance;
          }
    private:
        static Singleton* instance;
        Singleton(){}
        Singleton(const Singleton&) = delete;
        Singleton& operator=(const Singleton&) = delete;
    };
    
  2. 工厂模式
    工厂模式就是不再需要客户去调用具体的类的构造函数,而只需要传入需要的类的名称,就可以直接返回需要类的实例。工厂模式分为3种:

    (1)简单工厂
    class Car{
    public:
        virtual void run() = 0;
    };
    
    class Benz:public Car{
    public:
        virtual void run(){
            cout<<"Benz is running..."<<endl;
        }
    };
    
    class BMW:public Car{
    public:
        virtual void run(){
            cout<<"BMW is running..."<<endl;
        }
    };
    
    class Factory{
    public:
        static Car* produce(string car_type){
            if(car_type == "Benz"){
                return new Benz();
            }else if(car_type == "BMW"){
                return new BMW();
            }else{
                cout<<"No car has typename of "<<car_type<<endl;
                return nullptr;
            }
        }
    };
    
    (2)抽象工厂
    class Motor{
    public:
        virtual void operate() = 0;
    };
    
    class SixCylinder: public Motor{
    public:
        virtual void operate(){
            cout<<"Ouput 600 horsepower!"<<endl;
        }
    };
    
    class EightCylinder: public Motor{
    public:
        virtual void operate(){
            cout<<"Ouput 800 horsepower!"<<endl;
        }
    };
    
    class Tyre{
    public:
        virtual void run() = 0;
    };
    
    class EighteenInches: public Tyre{
    public:
        virtual void run(){
            cout<<"Run actually fast!"<<endl;
        }
    };
    
    class NinteeneenInches: public Tyre{
    public:
        virtual void run(){
            cout<<"Run so fast!"<<endl;
        }
    };
    
    class CarPartsFactory{
    public:
        virtual Tyre* produceTyre() = 0;
        virtual Motor* produceMotor() = 0;
    };
    
    class BenzPartsFactory: public CarPartsFactory{
    public:
        virtual Tyre* produceTyre(){
            return new NinteeneenInches();
        }
        virtual Motor* produceMotor(){
            return new EightCylinder();
        }
    };
    
    class HondaPartsFactory: public CarPartsFactory{
    public:
        virtual Tyre* produceTyre(){
            return new EighteenInches();
        }
        virtual Motor* produceMotor(){
            return new SixCylinder();
        }
    };
    
    (3)工厂方法
    class Vehicle{
    public:
        virtual void run() = 0;
    };
    
    class Plane: public Vehicle{
    public:
        virtual void run(){
            cout<<"Plane is running..."<<endl;
        }
    };
    
    class Car: public Vehicle{
    public:
        virtual void run(){
            cout<<"Car is running..."<<endl;
        }
    };
    
    class VehicleFactory{
    public:
        virtual Vehicle* produce() = 0;
    };
    
    class PlaneFactory: public VehicleFactory{
    public:
        virtual Vehicle* produce(){
            return new Plane();
        }
    };
    
    class CarFactory: public VehicleFactory{
    public:
        virtual Vehicle* produce(){
            return new Car();
        }
    };
    

结构型:

  1. 装饰器模式
    装饰模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能。在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
    class Car{
    public:
        Car(string description): car_description(description){}
        virtual int cost(){
            return 0;
        }
        string getDescription(){
            return car_description;
        }
    private:
        string car_description;
    };
    
    class CarDecorator{
    public:
        CarDecorator(Car* car): inner_car(car){}
        int cost(){
             return inner_car->cost();
         }
         string getDescription(){
             return inner_car->getDescription();
         }
        private:
         Car* inner_car;
    }
    
    class AutomaticCar: public Car{
    public:
        AutomaticCar():Car("Automatic"){}
        virtual int cost(){
            return 20;
        }
    };
    
    class  ManualCar: public Car{
    public:
        ManualCar():Car("Manual"){}
        virtual int cost(){
            return 15;
        }
    };
    
    class RearWingDecorator: public CarDecorator{
    public:
        RearWingDecorator(Car* car): CarDecorator(car){}
        int cost(){
            return CarDecorator::cost() + 5;
        }
        string getDescription()
        {
            return CarDecorator::getDescription() + " add Rear Wing.";
        }
    };
    
    class PedalDecorator: public CarDecorator{
    public:
        PedalDecorator(Car* car): CarDecorator(car){}
        int cost(){
            return CarDecorator::cost() + 2;
        }
        string getDescription()
        {
            return CarDecorator::getDescription() + " add Pedal.";
        }
    };
    
  2. 适配器模式
    适配器模式将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
    class System{
    public:
        System(const int& voltage): inner_voltage(voltage){}
        virtual int output(){
            return inner_voltage;
        }
    private:
        int inner_voltage;
    };
    
    class SystemA: public System{
    public:
        SystemA(): System(10){}
    };
    
    class SystemB: public System{
    public:
        SystemB(): System(15){}
    };
    
    class AdapterSystem{
    public:
        AdapterSystem(System* system, const int& need):inner_system(system), voltage_need(need){}
        int output(){
            int des = inner_system->output() - voltage_need;
            return inner_system->output() - des;
        }
    private:
        System* inner_system;
        int voltage_need;
    };
    
    class Client{
    public:
        void charge(const int& voltage_input){
            if(voltage_input > 10){
                cout<<"voltage is too high!"<<endl;
                return;
            }
            cout<<"charging..."<<endl;
        }
    };
    
  3. 代理模式
    在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
    class Person{
    public:
        Person(const int& money): inner_money(money){}
        virtual int getMoney(){
            return inner_money;
        }
        virtual void buyShare() = 0;
    private:
        int inner_money;
    };
    
    class Folks: public Person{
    public:
        Folks(const int& money): Person(money){}
        virtual void buyShare(){
            cout<<"I will buy share "<<to_string(getMoney())<<"w yuan"<<endl;
        }
    };
    
    class Proxy: public Person{
    public:
        Proxy(Folks* folks): inner_folk(folks),Person(0){}
        virtual int getMoney(){
            return inner_folk->getMoney();
        }
        virtual void buyShare(){
            cout<<"I will buy share "<<to_string(static_cast<int>(inner_folk->getMoney() * 0.3))<<"w yuan"<<endl;
        }
    private:
        Folks* inner_folk;
    };
    

行为型:

  1. 观察者模式
    观察者模式是为了达到对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
    class StateObject{
    public:
        StateObject(const int& primary_state = 0):inner_state(primary_state){}
        void setState(const int& newState){
            updateState(newState);
            notify();
        }
        void notify(){
            for(StateObject* obj : objVec){
                obj->setState(inner_state);
            }
        }
        void attach(StateObject* obj){
            objVec.push_back(obj);
        }
        virtual void updateState(const int& newState) = 0;
    protected:
        float inner_state;
    private:
        vector<StateObject*> objVec;
    };
    
    class AddState:public StateObject{
    public:
        AddState(const int& num, const int& primary_state = 0):addNum(num), StateObject(primary_state){}
        virtual void updateState(const int& newState){
            inner_state = newState + addNum;
            cout<<"[Add State: add_num "<<addNum<<"]"<<inner_state<<endl;
        }
    private:
        int addNum;
    };
    
    class MultiplyState:public StateObject{
    public:
        MultiplyState(const float& num, const int& primary_state = 0):mulNum(num), StateObject(primary_state){}
        virtual void updateState(const int& newState){
            inner_state = newState * mulNum;
            cout<<"[Muliply State: mul_Num "<<mulNum<<"]"<<inner_state<<endl;
        }
    private:
        float mulNum;
    };
    
  2. 策略模式
    将不同的算法封装成一个个策略,这些策略拥有共同的接口,使用这些算法的成为Context类,该类对象可以自由选择其中一种算法,使用策略模式的优势是为了支持算法的自由切换。
    class Strategy{
    public:
        virtual float operate(const float& num_1, const float& num_2) const = 0;
    };
    
    class AddStrategy:public Strategy{
    public:
        virtual float operate(const float &num_1, const float &num_2) const{
            return num_1 + num_2;
        }
    };
    
    class MultiplyStrategy:public Strategy{
    public:
        virtual float operate(const float &num_1, const float &num_2) const{
            return num_1 * num_2;
        }
    };
    
    class PowStrategy:public Strategy{
    public:
        virtual float operate(const float &num_1, const float &num_2) const{
            return pow(num_1, num_2);
        }
    };
    
    class Context{
    public:
        void setStrategy(const Strategy* strategy){
            inner_strategy = strategy;
        }
        void executeStrategy(const float& num_1, const float& num_2){
            cout<<"The output: "<<inner_strategy->operate(num_1, num_2)<<endl;
        }
    private:
        const Strategy* inner_strategy;
    };
    
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读