设计模式2

行为型模式:

模板方法模式:
将逻辑和算法放在抽象基类之中,并定义好需要实现细节的接口,子类中实现细节

#include<iostream>
#include<vector>
using namespace std;
class Factory{
public:
   virtual void buildCar(){
       this->buildA();
       this->buildB();
       this->buildC();
       this->buildD();
   }
   virtual void buildA()=0;
   virtual void buildB()=0;
   virtual void buildC()=0;
   virtual void buildD()=0;
};
class FactoryBMW:public Factory{
public: 
    void buildA(){
        cout<<"BuildA In BMW Factory!"<<endl;
    }
    void buildB(){
        cout<<"BuildB In BMW Factory!"<<endl;
    }
    void buildC(){
        cout<<"BuildC In BMW Factory!"<<endl;
    }
    void buildD(){
        cout<<"BuildD In BMW Factory!"<<endl;
    }
};
class FactoryBENZ:public Factory{
public: 
    void buildA(){
        cout<<"BuildA In BENZ Factory!"<<endl;
    }
    void buildB(){
        cout<<"BuildB In BENZ Factory!"<<endl;
    }
    void buildC(){
        cout<<"BuildC In BENZ Factory!"<<endl;
    }
    void buildD(){
        cout<<"BuildD In BENZ Factory!"<<endl;
    }
};

int main(){
   Factory*p1=new FactoryBMW();
   Factory*p2=new FactoryBENZ();
   p1->buildCar();
   p2->buildCar();
   delete p1;
   delete p2;
   return 0;
}

策略模式:
Stragety模式和template模式是相同的(类似)的,都是给业务逻辑(算法)具体实现和抽象接口之间的解耦,Stragety模式将逻辑(算法)封装到一个类(context)里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口的实现委托给组合对象实现。
核心要点:指针/组合模式,抽象基类

#include<iostream>
using namespace std;
class Stragegy{
public:
virtual ~Stragegy(){}
virtual void sort(int arr[],int n)=0;
};
class InsertSort:public Stragegy{
public:
 void sort(int a[],int n)override{
      if(n<=1) return ;
      int temp;
      for(int i=0;i<n-1;i++){
          int minID=i;
          for(int j=i+1;j<n;j++){
              if(a[j]<a[minID]){
                  minID=j;
              }
          }
          temp=a[i];
          a[i]=a[minID];
          a[minID]=temp;
      }
  }
};
class BubbleSort:public Stragegy{
 void sort(int arr[],int n)override{
      if(n<=1) return ;
      int temp;
      for(int i=0;i<n-1;i++){
          for(int j=1;j<n-i;j++){
              if(a[j]<a[j-1]){
                  temp=a[j];
                  a[j]=a[j-1];
                  a[j-1]=temp;
              }
          }
      }
  }
};
class SelectSort:public Stragegy{
  void sort(int a[],int n)override{
      if(n<=1) return ;
      int temp;
      for(int i=0;i<n-1;i++){
          int minID=i;
          for(int j=i+1;j<n;j++){
              if(a[j]<a[minID]){
                 minID=j;
              } 
          } 
          temp=a[i];
          a[i]=a[minID];
          a[minID]=temp;
      }
  }
};
class Context{
public:
    void setData(int*data,int size){
        _arr=data;
        _size=size;
    }
    void setStrategy(Stragegy*p){
        _strategy=p;
    } 
    void sort(){
      _strategy->sort(_arr,_size);
    }
    void print(){
        for(int i=0;i<_size;i++){
            cout<<_arr[i]<<" ";
        }
        cout<<endl;
      
    }
private:
   int*_arr;
   int _size;
   Stragegy*_strategy;
};
int main(){
    Context*ctx=new Context();
    int arr[]={2,56,4,-56,-236,85,-2,74};
    ctx->setData(arr,sizeof(arr)/sizeof(int));
    Stragegy*p1=new BubbleSort();
    Stragegy*p2=new InsertSort();
    Stragegy*p3=new SelectSort();
    ctx->setStrategy(p1) ;
    ctx->sort();
    ctx->print();
    ctx->setStrategy(p2) ;
    ctx->sort();
    ctx->print();
    ctx->setStrategy(p3) ;
    ctx->sort();
    ctx->print();
    delete p1;
    delete p2;
    delete p3;   
    return 0;
}

观察者模式

Observer模式要解决的问题为:建立一个一(Subject)对多(Observer)的依赖关系,并且做到当“一”变化的时候,依赖这个“一”的多也能同步变化

#include<iostream>
#include<vector>
#include<map>
using namespace std;
class Subject;

class AbstractObserver{
public:
   AbstractObserver(string name):_name(name){}
   virtual ~AbstractObserver(){}
   virtual void update(Subject*p)=0;
   virtual const string&getName()const{
       return _name;
   }
protected:
   string _name;
};
class ObserverA:public AbstractObserver{
public:
  ObserverA(string s):AbstractObserver(s){}
  ~ObserverA(){}
  void update(Subject*p)override{
      cout<<"Update ObeserverA name ="<<_name<<" address ="<<this<<endl;
  }
};
class ObserverB:public AbstractObserver{
public:
  ObserverB(string s):AbstractObserver(s){}
  ~ObserverB(){}
  void update(Subject*p)override{
      cout<<"Update ObeserverB name ="<<_name<<" address ="<<this<<endl;
  }
};
class Subject{
public:
void addObserver(AbstractObserver*p)
{
  auto arr= _observers.find(p->getName());
  if(arr!=_observers.end()){
      _observers[p->getName()].push_back(p);
  }else{
      std::vector<AbstractObserver*>v;
      v.push_back(p);
      _observers[p->getName()]=v;
  }
}
void removeObserver(AbstractObserver*p){
    
}
void notify(string s){
    if(_observers.find(s)==_observers.end()){
        cout<<"not found any observer!"<<endl;
        return;
    }
    for(auto p:_observers[s]){
        p->update(this);
    }
}
protected:
//key当作观察id
std::map<string,std::vector<AbstractObserver*>>_observers;

};
int main(){
    Subject subject;//观察者
    AbstractObserver*p1=new ObserverA("abc");
    AbstractObserver*p2=new ObserverA("abcd");
    AbstractObserver*p3=new ObserverA("abc");
    AbstractObserver*p4=new ObserverB("abc123");
    AbstractObserver*p5=new ObserverA("abcd");
    AbstractObserver*p6=new ObserverB("a");
    AbstractObserver*p7=new ObserverA("bc");
    AbstractObserver*p8=new ObserverB("abc123");
    subject.addObserver(p1);
    subject.addObserver(p2);
    subject.addObserver(p3);
    subject.addObserver(p4);
    subject.addObserver(p5);
    subject.addObserver(p6);
    subject.addObserver(p7);
    cout<<"---------abc------\n";
    subject.notify("abc");
    cout<<"---------abc------\n";
    subject.notify("abc");
    cout<<"---------abc------\n";
    subject.notify("abc");
    cout<<"---------abc------\n";
    subject.notify("abc");
    cout<<"---------abc------\n";
    subject.notify("abc");
    cout<<"---------abc------\n";
    subject.notify("abc");
    cout<<"---------abc------\n";
    subject.notify("abc");

    delete p1;
    delete p2;
    delete p3;
    delete p4;
    delete p5;
    delete p6;
    delete p7;
    delete p8;

    return 0;
}

命令模式:
Command模式通过将请求封装到一个对象(Command)中,并将请求的接收者存放到具体的ConcreteCommand类(Receiver)中,从而实现调用的操作对象和操作的具体实现者之间的解耦

#include<iostream>
using namespace std;
class Receiver{
public:
  Receiver(){}
  virtual ~Receiver(){}
  virtual void operator()(){
    cout<<"Execute Command!"<<endl;
  }
};
class Receiver2:public Receiver{
public:
    void operator()()override{
    cout<<"Execute Command2!"<<endl;
  }
};
class Command{
public:
   Command()=delete;
   Command(Receiver* p):_receiver(p){}
   virtual ~Command(){}
   virtual void doCommand(int n)=0;
protected:
   Receiver*_receiver;
};
class CommandA:public Command{
public:
    CommandA()=delete;
    CommandA(Receiver*p):Command(p){

    }
    CommandA(Receiver*p1,Receiver*p2):Command(p),_receiver2(p2){

    }
    void setReceiver(){

    }
    void doCommand(int n)override{
      if(n==1)
      (*_receiver)();
      else
      (*_receiver2)();
    }
protected:
  Receiver*_receiver2;
};
class Invoker{
public:
   Invoker():_command(nullptr){}
   virtual ~Invoker(){}
   void setCommand(Command*p){
       _command=p;
   }
   void executeCommand(int n){
    if(_command)_command->doCommand(n);
   }
private:
   Command*_command;
};
int main(){
   Invoker*invoker=new Invoker();
   Receiver*receiver=new Receiver();
   Receiver2*receiver2=new Receiver2();
   Command*command=new CommandA(receiver,receiver2);
   invoker->setCommand(command);
   invoker->executeCommand(1);
   invoker->executeCommand(2);
   delete command;
   delete receiver2;
   delete receiver;
   delete invoker;
   return 0;
}

访问者模式:
不改变类的前提下定义作用于这些元素的新操作

#include<iostream>
using namespace std;
class Visitor{
public:
  virtual ~Visitor(){}
  virtual void visit(Node*node)=0;
};
class Node{
public:
  virtual ~Node(){};
  virtual void accept(Visitor*visitor)=0; 
};
class NodeA:public Node{
friend class VisitorA;
public:
   NodeA(){
       s="hello my !";
   }
   void accept(Visitor*vistor)override{
       vistor->visit(this);

   }
private:
   string s;
};
class NodeB:public Node{
friend class VisitorB;
public:
   NodeB(){
       s="hello master !";
   }
   void accept(Visitor*vistor)override{
       vistor->visit(this);

   }
private:
   string s;
};
class VisitorA:public Visitor{
public:
    void visit(Node*node)override{
        NodeA*p=dynamic_cast<NodeA*>(node);
        if(p){
            cout<<"Node A ---- "<<p->s.c_str()<<endl;
        }  
    }
};
class VisitorB:public Visitor{
public:
    void visit(Node*node)override{
        NodeB*p=dynamic_cast<NodeB*>(node);
        if(p){
            cout<<"Node B ---- "<<p->s.c_str()<<endl;
        }  
    }
};
int main(){
   Node*p1=new NodeA();
   Node*p2=new NodeB();
   Visitor*p3=new VisitorA();
   Visitor*p4=new VisitorB();
   p1->accept(p3);
   p2->accept(p4);
   delete p1;
   delete p2;
   delete p3;
   delete p4;
   return 0;
}

责任链模式:
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止,

#include<iostream>
#include<string>
using namespace std;
struct Request{
    int days;
    int type;
    string desc;
};
class Handler{
public:
   Handler():_nextHandler(nullptr){}
   virtual ~Handler(){}
   virtual void setNextHandler(Handler*p){
       _nextHandler=p;
   }
   virtual void dealRequest(Request*p)=0;
   virtual void request(int days,int type,string desc){
       Request*p=new Request{days,type,desc};
       this->dealRequest(p);
       delete p;
   }
protected:
    Handler*_nextHandler;
};
class Employee:public Handler{
public:
   void dealRequest(Request*p)override{
     
           cout<<"没有权限,需要上级审批! \n";
           if(this->_nextHandler)
           this->_nextHandler->dealRequest(p);
       
   }
};
class TeamLeader:public Handler{
public:
   void dealRequest(Request*p)override{
       if(p->days<=3){
           cout<<"少于三天,直接通过审批! \n";
       }else{
           cout<<"没有权限,需要上级审批! \n";
           if(this->_nextHandler)
           this->_nextHandler->dealRequest(p);
       }
   }
};
class Manager:public Handler{
public:
   void dealRequest(Request*p)override{
       if(p->days<=5){
           cout<<"少于5天,直接通过审批! \n";
       }else{
           cout<<"没有权限,需要上级审批! \n";
           if(this->_nextHandler)
           this->_nextHandler->dealRequest(p);
       }
   }
};
class Boss:public Handler{
public:
   void dealRequest(Request*p)override{
       if(p->days<=10){
           cout<<"少于10天,直接通过审批! \n";
       }else{
           cout<<"大于10天,拒绝! \n";
           if(this->_nextHandler)
           this->_nextHandler->dealRequest(p);
       }
   }
};
int main(){
    Handler*p1=new Boss();
    Handler*p2=new Manager();
    Handler*p3=new TeamLeader();
    Handler*p4=new Employee();
    p4->setNextHandler(p3);
    p3->setNextHandler(p2);
    p2->setNextHandler(p1);
    p4->request(2,0,"事假");
    p4->request(5,1,"病假");
    p4->request(11,1,"婚假");
    delete p4;
    delete p3;
    delete p2;
    delete p1;
    return 0;
}

迭代器模式:
提供一种顺序访问一个聚合对象中各个元素,而不暴露该对象的内部表现,

类似vector的迭代器

备忘录模式:
备忘录模式是保存一个对象的某个状态,以便在适当的时候恢复对象,备忘录模式属于行为型模式

#include<iostream>
#include<vector>
using namespace std;

struct StateInfo{
   int _a;
   int _b;
};
class CareTaker{
public:
static  CareTaker*_instance;
static CareTaker*instance(){
    if(_instance==nullptr){
        _instance=new CareTaker();
    }
    return _instance;
}

virtual ~CareTaker(){
    for(auto it:_states){
        delete it;
    }
}
void addState(int a,int b){
    _states.push_back(new StateInfo{a,b});
}
StateInfo*getState(int index){
    if(_states.size()>index){
        return _states[index];
    }
    return nullptr;
}
private:
   std::vector<StateInfo*>_states;
};
class Originator{
public:
Originator():_a(0),_b(0){

}
void setA(int n){
    _a=n;
    this->saveState();

}
void setB(int n){
    _b=n;
    this->saveState();
}    
void getState(int index){
    auto p=CareTaker::instance()->getState(index);
    if(p){
    _a=p->_a;
    _b=p->_b;
    }
}
void saveState(){
   CareTaker::instance()->addState(_a,_b);
}
void debug(){
    cout<<"a="<<_a<<"b ="<<_b<<endl;
}
private:
  int _a;
  int _b;
};
CareTaker*CareTaker::_instance=nullptr;
int main(){
   Originator*p=new Originator();
   p->setA(1);
   p->setB(1);
   p->setB(3421);
   p->setA(44);
   p->setA(877);
   p->debug();
   cout<<"------恢复第一步----"<<endl;
   p->getState(1);
   p->debug();
   cout<<"------恢复第三步----"<<endl;
   p->getState(3);
   p->debug();
   return 0;
}


中介者模式:
中介者模式是用来降低多个对象和类之间通信的复杂性,这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护,中介者模式属于行为者模式

#include<iostream>
using namespace std;
class Colleague;
class Mediator{
public:
   virtual void deal(Colleague*p)=0;
   virtual void setMediator(Colleague*from,Colleague*to){
      _from=from;
      _to=to;
   }
protected:
   Colleague*_from;
   Colleague*_to;
};

// class MediatorB:public Mediator{
    
// };
class Colleague{
public:
   Colleague()=delete;
   Colleague(Mediator*p):_mediator(p){

   }
   virtual ~Colleague(){}
   virtual void send()=0;
   virtual void receive(string s)=0;
protected:
   Mediator* _mediator;
};

class ColleagueA:public Colleague{
public:
  ColleagueA(Mediator*p):Colleague(p){

  }
  void send()override{
      _mediator->deal(this);
  }
  void receive(string s)override{
      cout<<s.c_str()<<endl;
  }
};
class ColleagueB:public Colleague{
public:
  ColleagueB(Mediator*p):Colleague(p){

  }
  void send(){
      _mediator->deal(this);
  }
  void receive(string s)override{
      cout<<s.c_str()<<endl;
  }
};
class MediatorA:public Mediator{
public:
  void deal(Colleague* p)override{
      if(p==_from){
          _from->receive("from---to");
      }else{
          _to->receive("to---from");
      }
  }
};
int main(){
    Mediator*mediator=new MediatorA();
    Colleague*p1=new ColleagueA(mediator);
    Colleague*p2=new ColleagueB(mediator);
    mediator->setMediator(p1,p2);
    p1->send();
    p2->send();
    return 0;
}

解释器模式:
和命令模式和建造者模式类似:
解释器模式提供了评估语言的语法或表达式的方法,它属于行为型模式,这种模式提供了一个表达式接口,该接口解释了一个特定的上下文,这种模式被用在在SQL解析,符号处理引擎等。

模式设计原则:

设计原则:
1.应对变化,提高复用
2.寻找变化点,然后在变化点处应用设计模式,从而更好地面对需求地变化
3.没有一步到位的设计模式
解耦-提高复用率

不可用设计模式:
1.代码可读性很差
2.需求理解还很浅时
3.变化没有显现时
4.不是系统的关键依赖点
5.项目没有复用价值
6.项目将要发布时

代码重构的方法:
1.静态->动态
2.早绑定->晚绑定
3.继承->组合
4.编译时依赖->运行时依赖
5.紧耦合->松耦合

代码重构:

代码重构原则:
1.不要为了模式而模式
2.关注抽象类和接口
3.理清变化点和稳定点
4.审视依赖关系
5.要求FrameWork和Application分隔思维
6.良好的设计是演化的结果

终极之道:
1.见模式而不知
2.可以识别模式,作为应用开发人员模式
3.作为框架开发人员为应用设计某些模式
4.忘掉模式,只有原则

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值