免责声明:我喜欢这个 项目中使用dependency injection,并有全线松耦合基于接口的设计,但使用依赖注入已经在这个项目中被击落。另外SOLID设计原则(和一般design patterns)是我工作的外国事物,我自己对他们中的许多人都是新手。因此,在为此问题提出更好的设计时,请考虑 。有更好的设计选择吗?
下面是我正在处理的代码的简化版本,因此它可能看起来有点麻烦。如果是的话,我表示歉意。考虑下面的类:
// Foo is a class that wraps underlying functionality from another
// assembly to create a simplified API. Think of this as a service layer class,
// a facade-like wrapper. It contains a helper class that is specific to
// foo. Other AbstractFoo implementations have their own helpers.
public class Foo : AbstractFoo
{
private readonly DefaultHelper helper;
public override DefaultHelper Helper { get { return helper; } }
public Foo()
{
helper = new Helper("custom stuff");
}
public override void Operation1(string value)
{
Console.WriteLine("Operation1 using " + value);
}
public override void Operation2()
{
Console.WriteLine("Operation2");
}
}
// Helper derives from a default implementation and allows us to
// override it's methods to do things specific for the class that
// holds this helper. Sometimes we use a custom helper, sometimes
// we use the default one.
public class Helper : DefaultHelper
{
private readonly string customStuff;
public Helper(string value)
{
customStuff = value;
}
public override void DoSomethingHelpful()
{
Console.WriteLine("I was helpful using " + customStuff);
}
}
说这两个类的使用方法如下:
// foo referenced and used in one part of code
var foo = new Foo();
foo.Operation2(); // or foo.Operation1();
// some other point in the program where we don't have a reference to foo
// but do have a reference to the helper
helper.DoSomethingHelpful();
但是我现在发现,我还需要执行foo.Operation1
在一些实现helper.DoSomethingHelpful();
?潜在的解决方法我想到的将是:
- 有foo和助手有双向关系。因此,在DoSomethingHelpful我们可以称之为foo.Operation2
- 有富实现IHelp界面和移动“帮手”的代码到富
- 使用授权,并通过该方法操作2为
Action<string>
委派到助手的构造函数。
这些方法都没有似乎是理想的(虽然我非常确定我不喜欢选项1和很担心可维护性与选项3如果我们发现以后,我们需要通过在更多的代表)。这让我想知道Helper
/Foo
组合的初始设计是否有问题。思考?
我想你的意思是'DefaultHelper'而不是'DefualtHelper'。 – ja72 2012-04-04 14:35:15
@ ja72,拼写从来不是我的强项,我更新了这个错字。 – Matt 2012-04-04 14:37:46
+1免责声明...有一个伟大的笑声。 – scottheckel 2012-04-04 14:39:57