設計模式之解釋器(C++實例代碼)

#include <iostream>
#include <string>

using namespace std;

class numContext
{
public:
    void show(int val)
    {
        cout<<"num  = "<<val<<endl;
    }

};

class numExp
{
public:
    numExp()
    {

    }

    virtual int num_abs(numContext& cot) = 0;
};

class numObj : public numExp
{
public:
    numObj(int _num) : num(_num)
    {

    }

    virtual int num_abs(numContext& cot)
    {      
        return abs(num);
    }

private:
    int num;
};

class numAdd : public numExp
{
public:
    numAdd(numExp* obj1, numExp* obj2)
    {
        lobj = obj1;
        robj = obj2;
    }
   
    virtual int num_abs(numContext& cot)
    {
        cout<<"numAdd : ";
        int tmp = abs(lobj->num_abs(cot) + robj->num_abs(cot));
        cot.show(tmp);

        return tmp;
    }

private:
    numExp* lobj;
    numExp* robj;
};


class numSub : public numExp
{
public:
    numSub(numExp* obj1, numExp* obj2)
    {
        lobj = obj1;
        robj = obj2;
    }

    virtual int num_abs(numContext& cot)
    {
        cout<<"numSub : ";
        int tmp = abs(lobj->num_abs(cot) - robj->num_abs(cot));
        cot.show(tmp);

        return tmp;
    }

private:
    numExp* lobj;
    numExp* robj;
};

 

int main()
{
    numObj * num1 = new numObj(-10);
    numObj * num2 = new numObj(20);
    numContext * context = new numContext();

    //(-10) - 20 + (-10)
    numExp* exp = new numAdd(new numSub(num1, num2),num1);

    cout<<"result is "<<exp->num_abs(*context)<<endl;

 

//remember to delete val

    getchar();

    return 1;
}

其中解釋器就是num_abs,支持整形的取絕對值的加減運算。可以用運算符重載,更形象。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章