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就会依据这个算法进行排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值