Is this a valid example for decorator pattern?
I would like to know is this example a valid example for decorator pattern? if not what
is correction or change needed here, please suggest.
We have a Container class representing container and for it i want to add features at
run time. features like wheel and lid are used in the example.
Client code:
private void button2_Click(object sender, EventArgs e)
{
IContainer container = new MovableConatiner(new Container());
string features = container.getFeatures();
container = new LidConatiner(container);
features = container.getFeatures();
}
API code:
public interface IContainer
{
string getFeatures();
}
public class Container : IContainer
{
public string getFeatures()
{
return "Container";
}
}
// a decorator to add wheels
public class MovableConatiner : IContainer
{
protected IContainer container;
public MovableConatiner(IContainer container)
{
this.container = container;
}
public string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format("{0} , four wheels", features) :
features;
return features;
}
}
// a decorator to add lid to contaner
public class LidConatiner : IContainer
{
protected IContainer container;
public LidConatiner(IContainer container)
{
this.container = container;
}
public string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format("{0} , Lid", features) :
features;
return features;
}
}
its as per my understand so i would like to verify my understanding.
While your implementation doesn't ideally reflects the structure or the Decorator pattern, from my point of view it solves the same problem that Decorator is targeted to solve. Your solution is just not as strict and safe for future modifications as "ideal" Decorator implementation.
You simplified implementation removing "unnecessary" for you abstractions. But while you might think they are unnesessary at the moment, they will become very useful in the future when your application grows and get few dozens of components and decorators. it's easy to get lost who is who currently.
In the link I provided there is very simple description of main participants of the Decorator pattern, and there is a sample code, very similar to yourth, but complete. I won't copy-paste it here to show you corrent implementation.
I just want to stress that if you don't understand the need of some abstractions in Design patterns, you better leave them, or read once more how to use it instead of just removing them.
UPDATE: point in favour of abstractions:
All common logic must be implemented in one place and reused. Code duplication is very-very bad. I think everybody agrees that this is fundamental principle of well-organized code.
Now let's analyze your implementation of Decorator pattern without extracting abstract base class for decorators. Compare the implementation of your MovableContainer and LidContainer classes - do you see anything similar? I hardly see any difference at all actually. Ok, let's find what's common:
both have constructors, receiving component to decorate.
both store reference to IContainer which is decorated
both retrieve component's features in the getFeatures() method
both check component's features for empty and if not - append some string (the only difference is string itself)
All this logic should be extracted to base class. You already should udnerstand that base class for your two decorators is required.
Let's go further. Let's imagine every possible decorator for every possible container. As implies from the Decorator pattern definition, it's obvious that some logic is common for all decorators: they all store reference to the decorating object. Is that enough for extracting base class (single property - that's not hard to copy-paste it to both decorators you have)? Definitely enough!
If you like real-life examples, here it is. You've implemented few decorators, let's say 100 (2 is still enouth, 100 just exadurates the problem). And they you realize that some decelopers doesn't know how to use them properly - they just pass NULLs to your decorators. Their code works fine, then created decorators are passed somewhere else, or stored to DB etc. And then at some magical points, your code is failing in various places later. It's hard to every time find where that NULL came from, which part of application created such object. You decide to add NULL-check in the constructor to disallow passing NULLs and make initial code fail to immediately fix the problem. Ouch, we need to fix all 100 constructors! And merge your changes with changes of 10 more developers who are working everybody on his decorator. That's not a good perspective.
If this example didn't convince you and you are still ready to copy-paste code 100 times, imagine that you are developing a reusable library and other developers from other companies also implement decorators derived from your IContainer. You have no way to fix constructors of their decorators and ensure they won't provide you with invalid object containint NULL internally. On contrary if you had a base class for Decorator, you just needed to fix it - and all implementations both yourth and 3rd party get that functionality. If you think you don't implement a reusable library - consider other developers working in your team as 3rd party - it's always useful and not so different - don't require them to change their code because you need some fix.
Finally I provide the way I would refactor your code (I didn't want to do it at the beginning to let you come to this on your own):
public interface IContainer
{
string getFeatures();
}
public class Container : IContainer
{
public string getFeatures()
{
return "Container";
}
}
public abstract class ContainerDecorator : IContainer
{
protected IContainer container;
protected ContainerDecorator(IContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public abstract string getFeatures();
}
public class StringFormatDecorator : ContainerDecorator
{
private readonly string _format;
public StringFormatDecorator(IContainer container, string format) : base(container)
{
_format = format;
}
public override string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format(_format, features) : features;
return features;
}
}
// a decorator to add wheels
public class MovableConatiner : StringFormatDecorator
{
public MovableConatiner(IContainer container) : base(container, "{0} , four wheels")
{
}
}
// a decorator to add lid to contaner
public class LidConatiner : StringFormatDecorator
{
public LidConatiner(IContainer container) : base(container, "{0} , Lid")
{
}
}
Such code not only improves core reuse, but also prevents others from using your decorators in wrong way because of lost border between containers and decorators. It's much harder to declare parameterless decorator now and almost impossible to use it. You can't "decorate" one container with another container which is non-sense, but possible in your implementation when some new developer creates his own container without knowing your initial intentions.
Now doing things wrong becomes much more complex.
Related
Hi i am trying to apply the SOLID Principle to my code until i came across the interface and Dependency Inversion.
i am just having trouble with the constructor of FlightValidator class.
please can do advice?enter code here
you can get the full project here: https://www.sendspace.com/file/zk022f
i am confused on this class. in how do i create an instance of it?
public class FlightValidator
{
private IValidator _validator;
private GeneralFlightValidation _generalFlightValidation;
private BasicFlightValidation _basicFlightValidation;
private int flightRuleType;
public FlightValidator(IValidator _validator,
int flightRuleType
)
{
this._validator = _validator;
this.flightRuleType = flightRuleType;
}
public void GetFlightRule(ScheduledFlight scheduledFlight)
{
switch(this.flightRuleType)
{
case (short)FlightRuleType.STANDARD:
{
this._validator.FlightValidator(scheduledFlight);
break;
}
case (short)FlightRuleType.BASIC:
{
this._validator.FlightValidator(scheduledFlight);
break;
}
default:
{
this._validator.FlightValidator(scheduledFlight);
break;
}
}
}
}
public enum FlightRuleType : int
{
STANDARD,
BASIC
}
i am confused on this class. in how do i create an instance of it?
You can just pass the dependency to the constructor:
IValidator validator = ...
FlightValidator flightValidator = new FlightValidator(validator);
or, if you're using an IoC container (e.g. Unity):
FlightValidator flightValidator = container.Resolve<FlightValidator>();
Anyway, I find your code a bit confusing. Your FlightValidator class depends on an IValidator, which itself has a FlightValidator method (very bad name for a method by the way)... So what is the FlightValidator class good for, if it just calls another thing that does the flight validation?
What you're looking at here is Dependency Injection. The general idea is to remove the dependency from the class and injecting said dependency via the constructor. This allows your class to have less responsibilities, promotes re-use, which results in a more agile solution.
To instantiate this class, you can use poor man's dependency injection, like this:
IValidator myValidator = new SomeValidator();
FlightValidator flightValidator = new FlightValidator(myValidator, 69);
For a more elegant approach, you can use Inversion of Control.
I have a spec translator, like below.
//all specifications implement this base class
public abstract class SpecBase
{
public abstract void Translate(IContext context);
}
//spec translator implementation
public interface ISpecTranslator
{
void Translate(IContext context);
}
I need to inject the dependency of the SpecTranslator constructor. I have two ways to express the depenency.
Solution 1
public class SpecTranslator:ISpecTranslator
{
IList<SpecBase> specs;
public SpecTranslator(IList<SpecBase> specs)
{
this.specs = specs;
}
}
Please note using IList<SpecBase> works for now, but seems solution 2 provides more protection.
Solution 2:
public class SpecTranslator:ISpecTranslator
{
ISpec spec;
public SpecTranslator(ISpec spec)
{
this.spec = spec;
}
}
public interface ISpec
{
IList<SpecBase> specs {get;}
}
However, the implementation of ISpec have the same problem when using constructor dependency injection.
Any idea on pros and cons on these two solutions, or other solutions?
It seems in order to "translate" (analyze) the list of specs, the contents of the ISpec instance given need to be destructured in all cases. A list has to be obtained and seen through. No matter how many layers of abstraction you weave in, the SpecTranslator will finally need a list.
In your case I'd think of ISpec as a factory. If the list is not lazily calculated there is no value in it.
Also, simplicity is an important design principle. As ISpec does not add any capability or architectural freedom it does not carry its own weight.
All of our reports are created from object graphs that are translated from our domain objects. To enable this, we have a Translator class for each report, and have been using Dependency Injection for passing in dependencies.
This worked great, and would yield nice classes structured like this:
public class CheckTranslator : ICheckTranslator
{
public CheckTranslator (IEmployeeService empSvc
, IPaycheckService paySvc)
{
_empSvc = empSvc;
_paySvc = paySvc;
}
public Check CreateCheck()
{
//do the translation...
}
}
However, in some cases the mapping has many different grouping options. As a result, the c-tor would turn into a mix of class dependencies and parameters.
public class CheckTranslator : ICheckTranslator
{
public CheckTranslator (IEmployeeService empSvc
, IPaycheckService paySvc
, bool doTranslateStubData
, bool doAttachLogo)
{
_empSvc = empSvc;
_paySvc = paySvc;
_doTranslateStubData = doTranslateStubData;
_doAttachLogo = doAttachLogo;
}
public Check CreateCheck()
{
//do the translation...
}
}
Now, we can still test it, but it no longer really works with an IoC container, at least in a clean fashion. Plus, we can no longer call the CreateCheck twice if the settings are different for each check.
While I recognize it's a problem, I don't necessarily see the right solution. It seems kind of strange to create a Factory for each class ... or is this the best way?
Shot in the dark here, but could you move those parameters to the method instead?
In other words:
public Check CreateCheck(bool doTranslateStubData, bool doAttachLogo)
{
//do the translation...
}
Do those parameters have to be passed in via the constructor?
(Note - if your response to this is "there are too many methods for that to be practical", then part of the problem may be that the abstraction is too coarse).
Another option (it's really hard to say without understanding the domain model and injection patterns) would be to introduce a parameter object that is itself managed by the injector:
public interface ICheckConfiguration
{
bool AttachLogo { get; }
bool TranslateStubData { get; }
}
Then inject this with the constructor:
public CheckTranslator (IEmployeeService empSvc, IPaycheckService paySvc,
ICheckConfiguration config)
{
// etc.
}
This should be enough. You can then create a concrete CheckConfiguration class that takes those two bool properties in its constructor, and configure your container to create different instances of the parameter object (interface) based on a higher-level DI parameter.
The last thing I think I should mention is that just because you're using DI doesn't mean that everything has to be managed by the container. It's not such a bad thing to create CheckTranslator objects in an ad-hoc fashion if there's only one kind of "translator". As long as the translator still depends on abstractions, which it does here, then maybe you shouldn't be injecting it at all, just let higher-level DI-enabled classes create them ad-hoc.
I am finally getting my feet wet with Dependency Injection (long overdue); I got started playing with Unity and run into an issue with the strategy pattern. I can use the container to return to me specific implementations of a strategy based on a name, but what I don't see is how I am supposed to get the right strategy in the context.
Let's illustrate on a simple example: the context is a car, which has an IEngine (the strategy), with 2 implementations, FastEngine and SlowEngine. The code would look along these lines:
public interface IEngine
{
double MaxSpeed
{
get;
}
}
internal class FastEngine:IEngine
{
public double MaxSpeed
{
get
{
return 100d;
}
}
}
internal class SlowEngine:IEngine
{
public double MaxSpeed
{
get
{
return 10d;
}
}
}
public class Car
{
private IEngine engine;
public double MaximumSpeed
{
get
{
return this.engine.MaxSpeed;
}
}
public Car(IEngine engine)
{
this.engine = engine;
}
}
My problem is the following: how should I go about instantiating a fast car or a slow car? I can use the container to provide me with each implementation, and I can set a "default" implementation to use:
IUnityContainer container = new UnityContainer();
container.RegisterType<IEngine, FastEngine>();
container.RegisterType<IEngine, FastEngine>("Fast");
container.RegisterType<IEngine, SlowEngine>( "Slow" );
var car = container.Resolve<Car>();
Assert.AreEqual(100, car.MaximumSpeed);
but what I would like is to be able to request a car with a specific implementation of the strategy - something like
var car = container.Resolve<Car>(??? use "Fast" or "Slow ???);
Can I use the container to do that? Or should I write a Factory which uses the container? Any guidance would be appreciated - I am not sure I am thinking right about this!
A common pattern in DI is that at run-time there's only going to be a single implementation of a given abstraction. That just makes life a whole lot easier, as you don't need to deal with the ambiguity such as the one you describe.
However, sometimes, you need to vary an implementation based on context, such as the example you give. Many DI Containers provide ways where you can provide a qualifying parameter, but that means that you will end up tightly coupling your code to a specific DI Container.
A much better solution would be to introduct an Abstract Factory that can provide what you need. Something like
public interface ICarFactory
{
Car Create(IEngine engine);
}
If you need to inject more Strategies, perhaps the Builder design pattern might fit even better.
In any case, the point is that instead of registering a lot of different Cars in the container, you would instead register a single ICarFactory implementation.
In your client code, you would use the injected ICarFactory to create a Car instance based on a particular IEngine.
var car = factory.Create(engine);
This question is a result of a post by Jeffery Palermo on how to get around branched code and dependency injection http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/
In his post, Jeffery has a class (public class OrderProcessor : IOrderProcessor) that takes 2 interfaces on the constructor. One is a validator IOrderValidator and an IOrderShipper interface. His method code branches after only using methods on the IOrderValidator interface and never uses anything on the IOrderShipper interface.
He suggests creating a factory that will call a static method to get the delegate of the interface. He is creating a new object in his refactored code which seems unnecessary.
I guess the crux of the issue is we are using IoC to build all our objects regardless if they're being used or not. If you instantiate an object with 2 interfaces and have code that could branch to not use one of them, how do you handle it?
In this example, we assume _validator.Validate(order) always returns false and the IOrderShipper.Ship() method is never called.
Original Code:
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
private readonly IOrderShipper _shipper;
public OrderProcessor(IOrderValidator validator, IOrderShipper shipper)
{
_validator = validator;
_shipper = shipper;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
_shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipper : IOrderShipper
{
public OrderShipper()
{
Thread.Sleep(TimeSpan.FromMilliseconds(777));
}
public void Ship(Order order)
{
//ship the order
}
}
Refactored Code
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
public OrderProcessor(IOrderValidator validator)
{
_validator = validator;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
IOrderShipper shipper = new OrderShipperFactory().GetDefault();
shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipperFactory
{
public static Func<IOrderShipper> CreationClosure;
public IOrderShipper GetDefault()
{
return CreationClosure(); //executes closure
}
}
And here is the method that configures this factory at start-up time (global.asax for ASP.NET):
private static void ConfigureFactories()
{
OrderShipperFactory.CreationClosure =
() => ObjectFactory.GetInstance<IOrderShipper>();
}
I just posted a rebuttal of Jeffrey Palermos post.
In short, we should not let concrete implementation details influence our design. That would be violating the Liskov Substitution Principle on the architectural scale.
A more elegant solution lets us keep the design by introducing a Lazy-loading OrderShipper.
I'm running late for a meeting, but a few quick points...
Sticking to the code branching of using only one dependency, there are two branches to propose:
Applying DDD practices, you would not have an OrderProcessor with a dependency on IOrderValidator. Instead, you'd make the Order() entity be responsible for its own validation. Or, stick to your IOrderValidator, but have its dependency within the OrderShipper() that is implemented - since it will return any error codes.
Ensure the dependencies being injected are constructed using a Singleton approach (and configured as Singleton in the IoC container being used). This resolves any memory concerns.
Like someone else that mentioned here, the point is to break the dependency on concrete classes and loosely couple the dependencies using Dependency Injection with some IoC container in use.
This makes future refactoring and swapping out legacy code far easier on a grand scale by limiting the technical debt incurred in the future. Once you have a project near 500,000 lines of code, with 3000 unit tests, you'll know first hand why IoC is so important.