设计模式学习笔记(二十三)——Strategy策略

本文通过一个具体的编程示例详细解释了策略模式的概念及其应用场景。策略模式允许将一系列算法封装成独立的对象,以便在运行时自由切换不同的算法实现。
 

二十一、Strategy(策略)

情景举例:

定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

代码示例:

/* 使用Strategy的类(ok,客户)
*/
class Composition {
public:
    Composition(Compositor*);
    void Repair();
private:
    Compositor* _compositor;
    Component* _components;    // the list of components
    int _componentCount;       // the number of components
    int _lineWidth;            // the Composition's line width
    int* _lineBreaks;          // the position of linebreaks
                               // in components
    int _lineCount;            // the number of lines
};
/* Strategy的抽象父类
*/
class Compositor {
public:
    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    ) = 0;
protected:
    Compositor();
};
/*
*/
void Composition::Repair () {
    Coord* natural;
    Coord* stretchability;
    Coord* shrinkability;
    int componentCount;
    int* breaks;
 
    // prepare the arrays with the desired component sizes
    // ...
/*
*/
    // kills comiler warnings
    natural = coords;
    stretchability = coords;
    shrinkability = coords;
    componentCount = 1;
    breaks = b;
/* 注意这里:使用了Strategy模式。调用了多态的Compose算法
*/
    // determine where the breaks are:
    int breakCount;
    breakCount = _compositor->Compose(
        natural, stretchability, shrinkability,
        componentCount, _lineWidth, breaks
    );
/*
*/
    // lay out components according to breaks
    // ...
}
/* 下面是Compositor的子类,他们都分别实现了Compose算法
*/
class SimpleCompositor : public Compositor {
public:
    SimpleCompositor();
 
    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    );
    // ...
};
/*
*/
class TeXCompositor : public Compositor {
public:
    TeXCompositor();
 
    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    );
    // ...
};
/*
*/
class ArrayCompositor : public Compositor {
public:
    ArrayCompositor(int interval);
 
    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    );
    // ...
};
/*
*/
Composition* quick = new Composition(new SimpleCompositor);
Composition* slick = new Composition(new TeXCompositor);
Composition* iconic = new Composition(new ArrayCompositor(100));
/*
*/

个人理解:

Strategy模式感觉上要比State模式更简单。它们都是在不更改客户类的继承层次的前提下,达到了多态的目的。Strategy中需要注意的是,定义的算法抽象类函数(例子中的Compose函数)的申明一定要适用于所有子类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值