Where is the benefit in using the Strategy Pattern?

前端 未结 8 1088
太阳男子
太阳男子 2020-12-28 10:22

I\'ve looked at this explanation on Wikipedia, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and call

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 10:50

    Strategy pattern works on simple idea i.e. "Favor Composition over Inheritance" so that strategy/algorithm can be changed at run time. To illustrate let's take an example where in we need to encrypt different messages based on its type e.g. MailMessage, ChatMessage etc.

    class CEncryptor
    {
        virtual void encrypt () = 0;
        virtual void decrypt () = 0;
    };
    class CMessage
    {
    private:
        shared_ptr m_pcEncryptor;
    public:
        virtual void send() = 0;
    
        virtual void receive() = 0;
    
        void setEncryptor(cost shared_ptr& arg_pcEncryptor)
        {
            m_pcEncryptor =  arg_pcEncryptor;
        }
    
        void performEncryption()
        {
            m_pcEncryptor->encrypt();
        }
    };
    

    Now at runtime you can instantiate different Messages inherited from CMessage (like CMailMessage:public CMessage) with different encryptors (like CDESEncryptor:public CEncryptor)

    CMessage *ptr = new CMailMessage();
    ptr->setEncryptor(new CDESEncrypto());
    ptr->performEncryption();
    

提交回复
热议问题