c# - What can be done to fix a decorator whose root class requires the decorator instance? -
c# - What can be done to fix a decorator whose root class requires the decorator instance? -
i refactoring piece of software seek create more testable/di friendly , create more extensible. original code relied on inheritance, thinking decorator more flexible design because want end user of component able insert layers below of layers creating.
however, have run wall because of code in base of operations class passes this
of methods. using inheritance wouldn't problem because this
reference top layer type, having problem trying work out how create work decorator. here example:
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 { { homecoming false; } } public void dosomething() { // implementation code here // mill doesn't instance of decorator type // when in utilize - 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 { { homecoming lockingservice.isreadonly; } } public void dosomething() { if (this.isreadonly) throw new invalidoperationexception("node read-only"); this.innernode.dosomething(); } }
then mill this:
var somefactory = new someconcretefactory(); var lockingservice = new lockingservice(); var node = new node(somefactory); var lockablenode = new lockablenode(node, lockingservice); homecoming lockablenode;
the problem outlined comment places in code trying decorate, current object beingness passed parameter other methods , need instance of decorator object when in utilize , current object when not. short of re-implementing code passes this
mill in decorator class, there can done prepare this?
make actual dosomething
method needs decorated object parameter:
node
public void dosomething() { this.dosomethingwith(this) } public void dosomethingwith(inode it) { // ... var someinstance = somefactory.create(it); // ... }
lockablenode
public void dosomething() { this.innernode.dosomethingwith(this); } public void dosomethingwith(inode it) { this.innernode.dosomethingwith(it); }
edit: of course, have alter interface well.
public interface inode { bool isreadonly { get; } void dosomething(); void dosomethingwith(inode it); }
c# design-patterns decorator
Comments
Post a Comment