C++與設計模式(2)--策略模式

策略模式

策略模式是指提供接口,讓用戶使用可替換的算法。

enum ALG {first, second, third}; //標籤  
//抽象接口  
class Algorithm  
{  
public:  
    virtual void alg() = 0;  
};  
//三種具體的替換算法  
class Algorithm1 : public Algorithm  
{  
public:  
    void alg() { cout << "Algorithm1" << endl; }  
};  

class Algorithm2 : public Algorithm  
{  
public:  
    void alg() { cout << "Algorithm2" << endl; }  
};  
class Algorithm3 : public Algorithm  
{  
public:  
    void alg() { cout << "Algorithm3" << endl; }  
};

class User  
{  
private:  
    Algorithm *m_al;  
public:  
    User(enum ALG a)   
        {   
            if(a == first)  
                m_al = new Algorithm1();  
            else if(a == second)  
                m_al = new Algorithm2();  
            else if(a == third)  
                m_al = new Algorithm3();  
            else   
                m_al = NULL;  
        }  
    ~User() { delete m_ra; }  
    void alg() { m_ra->alg(); }  
};

int main()  
{  
    Cache cache(first); //指定算法標籤
    cache.Replace();  
    return 0;  
}  

這裏使用標籤來區分不同的算法,可以看出這麼做會難以進行擴展。

使用函數指針和匿名函數會對策略模式有很大的幫助,舉個例子:

struct Info
{
    int a;
    int b;
    int c;
};

template <class L>
class Vector
{
public:
    template <class T>
    void sort(T t)
    {
        int i, j;
        for (i = 0; i < InfoList.size(); i++)
            for (j = 1; j < InfoList.size() - i; j++)
                if (t(InfoList[j - 1],InfoList[j]))//依據用戶提供的算法進行比較
                    std::swap(InfoList[j - 1], InfoList[j]);
    }

private:
    vector<L> InfoList;
};

int main()
{
    Vector<Info> l;
    l.sort([](Info x,Info y){if(x.a>y.a)return 1;else return 0;});
}

在這個例子中我們遇到了一個’複雜’的數據-由三個int組成的結構體,我們不知道如何對其進行排序,所以我們的sort函數提供了一個參數,用於接受比較函數,在例子中提供的函數依據結構體中的a值進行比較,那麼sort就會依據這個算法進行排序。

發佈了60 篇原創文章 · 獲贊 37 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章