默认策略。策略模式 C#
使用下面的代码中的默认策略是否正常:
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();
}
}
提供自动实现的属性是否也正常:
public IClAlgorithm Algorithm
{
get;
set;
}
我只是从设计的角度好奇它是否可以接受。
谢谢!
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 Algorithm
{
get;
set;
}
I'm just curious from a design point of view wheter it's acceptable.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法想象这种设计实际上有用的场景 - 您的类取决于通过其构造函数传入的策略,并且稍后可以通过属性设置器进行更改。不传递依赖项不应允许调用者创建您的类的实例。
你应该只提供一个“默认”策略,如果它实际上在做一些有用的事情,即使这样,我也不会将它们捆绑在一起,而是让一个工厂方法使用该策略创建你的类。
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.