设计模式之翻译模式

翻译模式(interpreter)属于行为模式,对于一串的目标,需要对其分别进行解析的时候就用翻译模式,一般对语句根据语法进行翻译就采用翻译模式,翻译模式对处理对象定义了统一的接口,又通过继承实现了对不同语法的具体翻译方法。
下面是翻译模式的C++实现,代码可到本人github网页下载:设计模式例子

/*
 * Example of 'Interpreter' design pattern.
 * Copyright (C) 2016 Leo Wang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <vector>
using namespace std;
class CContext
{
    public:
        string m_msg;
    public:
        void SetMsg(string msg)
        {
            m_msg=msg;
        };
        string GetMsg()
        {
            return m_msg;
        }
    public:
        CContext(string msg)
        {
            SetMsg(msg);
        };
};

class CInterpreter
{
    public:
        void ReplaceMsg(string& msg,string original,string target)
        {
            int pos=0;
            while((pos=msg.find(original,pos))!=string::npos)
            {
                msg.replace(pos,original.length(),target);
                pos+=target.length();
            }
        };

        void Interpreter(string& msg)
        {
            ReplaceMsg(msg,GetOriginal(),GetTarget());
        };

    public:
        virtual string GetOriginal()=0;
        virtual string GetTarget()=0;
};

class CInterpreterA:public CInterpreter
{
    public:
        string GetOriginal()
        {
            return "A";
        };
        string GetTarget()
        {
            return "a";
        };
};

class CInterpreterB:public CInterpreter
{
    public:
        string GetOriginal()
        {
            return "B";
        };
        string GetTarget()
        {
            return "b";
        };
};

int main()
{
    string msg="ABABAB";
    CContext* cp_context=new CContext(msg);
    cout<<cp_context->GetMsg()<<endl;
    vector<CInterpreter*> v_interpreter;
    v_interpreter.push_back(new CInterpreterA());
    v_interpreter.push_back(new CInterpreterB());
    for(auto &e:v_interpreter)
    {
         e->Interpreter(cp_context->m_msg);
    };
    cout<<cp_context->GetMsg()<<endl;
    return 1;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值