默认策略。战略模式C#
在下面的代码中使用默认策略是否正常:默认策略。战略模式C#,c#,design-patterns,strategy-pattern,C#,Design Patterns,Strategy Pattern,在下面的代码中使用默认策略是否正常: public abstract class ClContext { protected sealed class InitialAlgorithm : IClAlgorithm { public void Initialize() { return; } public void Execute() { return;
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;
}
我只是好奇从设计的角度看它是否可以接受
谢谢 我无法想象这种设计在什么情况下会真正有用——您的类依赖于通过构造函数传入的策略,以后可能会通过属性设置器进行更改。不传递依赖项不应允许调用方创建类的实例 如果它确实在做一些有用的事情,您应该只提供一个“默认”策略,即使这样,我也不会将它们绑定在一起,而是让一个工厂方法使用该策略创建您的类。我使用
Initialize()
只是为了举例说明,但谢谢!