【发布时间】:2013-02-12 11:31:20
【问题描述】:
我正在重构一个软件,试图使其更易于测试/DI 友好,并使其更具可扩展性。原始代码依赖于继承,但我认为装饰器会是一种更灵活的设计,因为我希望组件的最终用户能够在我正在创建的某些层下方插入层。
但是,由于基类中的某些代码将this 传递给某些方法,因此我遇到了麻烦。使用继承这不会是一个问题,因为this 将引用顶层类型,但我在尝试弄清楚如何使用装饰器使其工作时遇到了麻烦。这是一个例子:
public interface INode
{
bool IsReadOnly { get; }
void DoSomething();
}
public class Node : INode
{
public Node(ISomeFactory someFactory)
{
if (someFactory == null)
throw new ArgumentNullException("someFactory");
this.someFactory = someFactory;
}
private readonly ISomeFactory someFactory;
public bool IsReadOnly { get { return false; } }
public void DoSomething()
{
// Some implementation code here
// This factory doesn't get an instance of the decorator type
// when it is in use - this is a problem
var someInstance = someFactory.Create(this);
// More code here...
}
}
public class LockableNode : INode
{
public LockableNode(INode node, ILockingService lockingService)
{
if (node == null)
throw new ArgumentNullException("node");
if (lockingService == null)
throw new ArgumentNullException("lockingService");
this.innerNode = node;
this.lockingService = lockingService
}
private readonly INode innerNode;
private readonly ILockingService lockingService;
public bool IsReadOnly { get { return lockingService.IsReadOnly; } }
public void DoSomething()
{
if (this.IsReadOnly)
throw new InvalidOperationException("Node is read-only");
this.innerNode.DoSomething();
}
}
然后我的工厂做这样的事情:
var someFactory = new SomeConcreteFactory();
var lockingService = new LockingService();
var node = new Node(someFactory);
var lockableNode = new LockableNode(node, lockingService);
return lockableNode;
我的评论中概述的问题是我试图装饰的代码中的某些地方,当前对象作为参数传递给其他方法,并且在使用时我需要装饰器对象的实例和当前对象不是。没有在装饰器类中重新实现将this 传递到工厂的代码,有什么办法可以解决这个问题吗?
【问题讨论】:
-
假设基节点被多个装饰器装饰,那么应该将哪一个传递给这个工厂?
-
最外面的实例是我所追求的,与继承的情况相同。
标签: c# design-patterns decorator