开发者

Default Strategy. Strategy Pattern C#

Is it normal to use default strategy like in my code below:

public abstract class ClContext
{
    protected sealed class InitialAlgorithm : IClAlgorithm
    {
        public void Initialize()
        {
            return;
        }
        public void Execute()
        {
            return;
        }
        public Byte[] Result
        {
            get { return new Byte[1]{0}; }
        }
    }
    protected IClAlgorithm algorithm;

    protected ClContext(IClAlgorithm algorithm = null)
    {
        this.algorithm = algorithm ?? new ClContext.InitialAlgorithm();
    }

    public void Execute()
    {
        this.algorithm.Execute();
    }
}

And is it also normal to provide auto-implemented property like:

public IClAlgorithm开发者_StackOverflow社区 Algorithm 
{
    get;
    set;
}

I'm just curious from a design point of view wheter it's acceptable.

Thanks!


I can't imagine a scenario where this design would actually be useful - your class depends on a strategy that's passed in via its constructor and may later be changed via a property setter. Not passing the dependency should not allow the caller to create an instance of your class.

You should only provide a "default" strategy if it is actually doing something useful, and even then I would not tie them together, but have a factory method create your class with the strategy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜