Understanding Decorator Design Pattern in C# - c#

I just started to learn Decorator Design Pattern, unfortunately i had to go through various refrences to understand the Decorator pattern in a better manner which led me in great confusion. so, as far as my understanding is concern, i believe this is a decorator pattern
interface IComponent
{
void Operation();
}
class Component : IComponent
{
public void Operation()
{
Console.WriteLine("I am walking ");
}
}
class DecoratorA : IComponent
{
IComponent component;
public DecoratorA(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("in the rain");
}
}
class DecoratorB : IComponent
{
IComponent component;
public DecoratorB(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("with an umbrella");
}
}
class Client
{
static void Main()
{
IComponent component = new Component();
component.Operation();
DecoratorA decoratorA = new DecoratorA(new Component());
component.Operation();
DecoratorB decoratorB = new DecoratorB(new Component());
component.Operation();
Console.Read();
}
}
But can the below code also be Decorator Pattern?
class Photo
{
public void Draw()
{
Console.WriteLine("draw a photo");
}
}
class BorderedPhoto : Photo
{
public void drawBorder()
{
Console.WriteLine("draw a border photo");
}
}
class FramePhoto : BorderedPhoto
{
public void frame()
{
Console.WriteLine("frame the photo");
}
}
class Client
{
static void Main()
{
Photo p = new Photo();
p.Draw();
BorderedPhoto b = new BorderedPhoto();
b.Draw();
b.drawBorder();
FramePhoto f = new FramePhoto();
f.Draw();
f.drawBorder();
f.frame();
}
}
My Understanding
From the second example given by me, we can call all the three methods, but from the first example i wont be able to get access to all the three methods by creating a single object.

It should be a comment, but I have too many words.
For example, you have an object and interface, like Repository : IRepository.
public interface IRepository
{
void SaveStuff();
}
public class Repository : IRepository
{
public void SaveStuff()
{
// save stuff
}
}
and client, which probably was written by someone else
class RepoClient
{
public void DoSomething(IRepository repo)
{
//...
repo.SaveStuff();
}
}
And once you decided, that ALL calls to repository should be logged. But you have a problem: the Repository class is from an external library and you don't want to change that code. So you need to extend the Repository's behavior that you use. You write RepositoryLogDecorator : IRepository, and inside on each method do the logging, like
public class RepositoryLogDecorator : IRepository
{
public IRepository _inner;
public RepositoryLogDecorator(IRepository inner)
{
_inner = inner;
}
public void SaveStuff()
{
// log enter to method
try
{
_inner.SaveStuff();
}
catch(Exception ex)
{
// log exception
}
// log exit to method
}
}
So, before you could use client as
var client = new RepoClient();
client.DoSomething(new Repository());
but now you can use
var client = new RepoClient();
client.DoSomething(new RepositoryLogDecorator(new Repository()));
Note, that this is a very simple example. In real projects, where object created primary with DI container, you will be able to use decorator by changing some config.
So, decorator is used to extend functionality of object without changing object or client.
Another benefit of decorator: your decorator does not depend on Repository implementation. Only depends from an interface IRepository. Why this is an advantage? If somehow you decide to write you own implementation of IRepository
public class MyAwesomeRepository : IRepository
{
public void SaveStuff()
{
// save stuff, but AWESOME!
}
}
you will be able to automatically decorate this with decorator, which already exist
var client = new RepoClient();
client.DoSomethig(new RepositoryLogDecorator(new MyAwesomeRepository()));
Want to see example from real software? (just as sample, code is ugly, I know) => go here

There is this PatternCraft series on Youtube that explains Design Patterns with Starcraft, you should check the video about Decorators here.
In the video above the author gives an example with a Marine and WeaponUpgrade.
In the game you will have a Marine and then you can upgrade its weapon:
marine = new WeaponUpgrade(marine);
Note that you still have a marine there, it is not a new unit, it is the same unit with things that modifies its attributes.
public class MarineWeaponUpgrade : IMarine
{
private IMarine marine;
public MarineWeaponUpgrade(IMarine marine)
{
this.marine = marine;
}
public int Damage
{
get { return this.marine.Damage + 1; } // here
set { this.marine.Damage = value; }
}
}
You do that by creating a class that implements the same interface as your unit and access your unit properties to modify values.
There is a Kata on CodeWars challenging you to complete the Weapon and Armor decorators for a marine.

Per GOF page Decorator desing pattern:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
In your second example you are using inheritance to extend behaviour of a class, I believe this is technically not a Decorator design pattern.

The decorator pattern allows you to add a specific behavior to an individual object of a given type without affecting other instances of that same type.
In your second example, which is normal inheritance, all instances of the class inherit the modified behavior.

The second example is not a decorate pattern, since an essential ingredient to decorator pattern is that the object accepts one of its kind and possibly enhance it.
An instances of this in the first example is
public DecoratorA(IComponent c)
{
component = c;
}
Also, the goal of the decorator pattern is to create "one" object, then decorate it by passing it through different filters or decorators.
Hence the line
DecoratorA decoratorA = new DecoratorA(new Component());
Should be
DecoratorA decoratorA = new DecoratorA(component );

Related

C# - Select and use different types of objects in a uniform way

This is my first time posting here and I'm rather new to programming, so I might not be fully understanding concepts which I intend to make use of such as interfaces or polymorphism.
I'm currently building a little game in which the player can select different types of objects and I'm struggling with coming up with a robust selection system. The way it works now is through an interface, which is implemented by every type of object the player can select.
public interface ISelectable
{
void DoSomething();
}
Then, this interface is used to call the implemented methods on the current selection based on different events such as mouse clicks or keys pressed.
public class Selector
{
public ISelectable selection;
public PerformAction()
{
selection.DoSomething();
}
}
The methods are implemented in different ways depending on the type of object. However, I've come across certain situations where I don't need a type of object to respond to an event, thus not needing to implement the method defined on the interface.
public class ObjectType1 : ISelectable
{
public void DoSomething() { /*Implemented*/ };
}
public class ObjectType2 : ISelectable
{
public void DoSomething() { /*Not needed*/ };
}
This has led me to believe that this may not be a correct approach to this. Therefore, I have a few questions:
Can my approach be fixed or improved so that it makes more sense and I don't encounter the situation described before again?
If not, is there a "correct" or simpler way to do this kind of selection system?
Thank you in advance. I will try to respond as fast as possible if any further clarification is needed.
Why does your ObjectType2 implement the interface ISelectable? You can remove it when it does not need it.
Or if you want a general interface, you can try these interface definitions:
public interface ISomeEmptyInterface
{
}
public interface ISelectable : ISomeEmptyInterface
{
void DoSomething();
}
Change the selector class:
public class Selector
{
public ISomeEmptyInterface myObj;
public void PerformAction()
{
if(myObj is ISelectable)
{
(myObj as ISelectable).DoSomething();
}
}
}
Classes implement the individual interface:
public class ObjectType1 : ISelectable
{
public void DoSomething()
{
Console.WriteLine("ObjectType1 is called");
};
}
public class ObjectType2 : ISomeEmptyInterface
{
// no any implementation
}
A simple program:
Selector sel1 = new Selector();
sel1.myObj = new ObjectType1();
sel1.PerformAction();
// output "ObjectType1 is called"
Selector sel2 = new Selector();
sel2.myObj = new ObjectType2();
sel2.PerformAction();
// not thing happened
This disadvantage is that your Selector must know what other sub ISomeEmptyInterface interfaces are.

Reduce increasing Constructor service parameters

I'm still new to using Autofac and I'm bothered by the constructor injection method that I'm using. Here's the scenario:
I currently have two classes which inherits the IForms interface. Each of the classes has its own interface as well
public interface IForms
{
long CreateNewForm(FormData data);
FormData RetrieveFormById(long id);
}
public interface IFormA : IForms
{ }
public interface IFormB : IForms
{ }
Now I have a class which handles this which is like this:
public class ApplicationForms : IApplicationForms
{
private readonly IFormA _formA;
private readonly IFormB _formB;
public ApplicationForms(IFormA formA, IFormB formB)
{
_formA = formA;
_formB = formB;
}
public void SubmitApplicationForm(FormData data)
{
switch(data.FormType)
{
case FormType.FormA:
_formA.CreateNewForm(data);
break;
case FormType.FormB:
_formB.CreateNewForm(data);
break;
}
}
}
Now there's a possibility that there will be 2 more forms coming in (ex. FormC, FormD, FormE). What will happen here is that there will be 3 more constructor parameters in the ApplicationForms constructor.
Is there a way to like combine all the constructor parameters into one parameter? I can see that it will definitely look ugly in the end.
The problem you're describing is that you have many forms, but at runtime you need one specific form, and so you don't want to inject all of the forms. That might be a good scenario for an abstract factory.
We often represent the factory as an interface with a single method, but we can also do it with a delegate:
public delegate IForm GetFormByTypeFunction(FormType formType);
Now your class looks like this:
public class ApplicationForms : IApplicationForms
{
private readonly GetFormByTypeFunction _getFormByType;
public ApplicationForms(GetFormByTypeFunction getFormByType)
{
_getFormByType = getFormByType;
}
public void SubmitApplicationForm(FormData data)
{
var form = _getFormByType(data.FormType);
form.CreateNewForm(data);
}
}
Now the question is how to implement the factory. It might still have a switch statement or something that doesn't seem too elegant, but that's okay. The point of the factory is that however it works, the business of creating and/or selecting an implementation is moved out of the class that depends on the implementation.
You can register a delegate with Autofac like this:
builder.Register<GetFormByTypeFunction>(context => formType =>
{
switch (formType)
{
case FormType.Type1:
{
return context.Resolve<FormOne>();
}
case FormType.Type2:
{
return context.Resolve<FormTwo>();
}
default:
throw new InvalidOperationException("Unknown form type");
}
});
Now you don't need to resolve all of the IForm implementations up front because you can resolve the one you want directly from the container once you know which one you want.
That might seem "wrong" because you're resolving from the container. But you're not resolving directly from the container. You're depending on a factory. That factory can be replaced with any other implementation which means that your class does not depend on the container.
This sort of factory is also super easy to mock. Technically it's not even a mock. It's just an implementation of the factory that returns a mock.
var formMock = new Mock<IForm>();
var factory = new GetFormByTypeFunction(formType => formMock.Object);
Since there is a common IForms interface, then you can inject an enumeration.
This looks like a good candidate for strategy pattern.
I would suggest refactoring the base interface to be able to identify what type of form it is
public interface IForms {
FormType FormType { get; }
long CreateNewForm(FormData data);
FormData RetrieveFormById(long id);
}
and update the dependent class
public class ApplicationForms : IApplicationForms {
private readonly IEnumerable<IForms> forms;
public ApplicationForms(IEnumerable<IForms> forms) {
this.forms = forms;
}
public void SubmitApplicationForm(FormData data) {
var form = forms.FirstOrDefault(_ => _.FormType == data.FormType);
if(form != null)
form.CreateNewForm(data);
//...
}
}
This assumes that when registering the derived interfaces that you associate it with the base IForms interface.
var builder = new ContainerBuilder();
builder.RegisterType<FormA>().As<IForms>();
builder.RegisterType<FormB>().As<IForms>();
builder.RegisterType<FormC>().As<IForms>();
//...
Now no matter how many more forms are added the class can perform without modification.

Apply constraint to class, adhere to interface

I have the requirement to be able to perform many conversions of external models to my own internal models.
I have decided to apply the Adapter pattern, but I want to make it as generic as possible. So effectively, I want it to be handle both "single" POCO's, but if i need to pass/adapt a collection then this also must work eg:
IEnumerable<IAdaptee> OR IList<TAdaptee>
and return my own adapted object(s):
IEnumerable<IAdapted> OR IList<TAdapted>
I want to do something like the following:
public interface IGenericAdapter
{
TAdapted Adapt<TAdapted,TAdaptee>(TAdaptee adaptee);
}
Where I am coming unstuck is when I build my "Adapter" class, and then implement the above interface, I am getting constraint mismatch errors. This of course, makes sense, because If i am applying constraints to the classes which implement the interface, and the interface doesn't have them, then of course errors occur.
So:
public class AToBAdapter
{
public TAdapted Adapt<TAdapted,TAdaptee>(TAdaptee adaptee)
where TAdapted: IList<FooAdapted>
where TAdaptee: IList<FooAdaptee>
{
// I want my constraints to be active here, as I need to perform specific operations here
}
}
The above works fine in and of itself, which is fine. But I want to hide all this behind a generic interface that I can use whenever it suits.
Of course, Once i add this it fails due to no constraints on the interface, yet constraints on the implementing class.
public class AToBAdapter:IAdapterGeneric
What's the magic bullet here which will enable me to build a truly generic Adapter - I'm guessing certain constraints on the interface? casting? but need assistance on the best course of action.
Thanks,
Chud
If you have access to your external models, you could use an interface as a marker:
public interface IAdaptee { }
public interface IAdapted { }
And use those interfaces as your adapter interface constraints:
public interface IGenericAdapter<out TAdapted, in TAdaptee>
where TAdaptee : IAdaptee
where TAdapted : IAdapted
{
TAdapted Adapt(TAdaptee adaptee);
}
You could pass this adapter into a helper method for adapting multiple objects (assuming the adapt logic stays the same for multiple):
public IEnumerable<TAdapted> AdaptMultiple<TAdapted, TAdaptee>
(IEnumerable<TAdaptee> adaptees, IGenericAdapter<TAdapted, TAdaptee> adapter)
where TAdaptee : IAdaptee
where TAdapted : IAdapted
{
return adaptees.Select(adapter.Adapt);
}
For example, we can construct the following concrete classes:
public class ConcreteAdaptee : IAdaptee { }
public class ConcreteAdapted : IAdapted { }
public class ConcreteAdapter : IGenericAdapter<ConcreteAdapted, ConcreteAdaptee>
{
public ConcreteAdapted Adapt(ConcreteAdaptee adaptee)
{
// Adapt Logic
return new ConcreteAdapted();
}
}
And adapt them as such:
IGenericAdapter<ConcreteAdapted, ConcreteAdaptee> adapter = new ConcreteAdapter();
var adaptee = new ConcreteAdaptee();
var adapted = adapter.Adapt(adaptee);
var adaptees = new List<ConcreteAdaptee>();
var adapteds = AdaptMultiple(adaptees, adapter);
consider the following example :
interface IDog
{
void Bark();
}
interface ICat
{
void Meow();
}
class SomeDog : IDog
{
public void Bark()
{
Console.WriteLine(#"bark bark");
}
}
class SomeCat : ICat
{
public void Meow()
{
Console.WriteLine(#"meow meow");
}
}
class CatToDogAdapter : IDog
{
private ICat cat;
public CatToDogAdapter(ICat cat)
{
this.cat = cat;
}
public void Bark()
{
cat.Meow();
}
}
new Dog().Bark(); // bark bark
new CatToDogAdapter().Bark();// meow meow
this is how adapter works.
Let say you have a model MyAdaptedData and you recive data containing HotelName, Name,PropertyName from agoda , booking and tripadviser
for each booking model you need to write adapter
AgodaAdapter : MyAdaptedData{
public AgodaAdapter(AgodaModel agodaModel){
....
}
public stirng HotelName{
get{
return agodaModel.HotelNamebyAgoda;
}
}
....
}
Same for booking and tripadvisor.
Adapter pattern helps you to retrieve necessary data from external models.
Then you need to create specific adapter depending on the adaptee type. Use Factory method pattern
MyAdaptedData AdaptersFactory(object adaptee){
if(adaptee is AgodaModel)
return new AgodaAdapter(adaptee);
....
if(adaptee is XBookingModel)
return new XBookingAdapter(adaptee);
}

Please explain the utility of abstract methods in C#

Just the 5 minute overview would be nice....
public abstract class MyBaseController {
public void Authenticate() { var r = GetRepository(); }
public abstract void GetRepository();
}
public class ApplicationSpecificController {
public override void GetRepository() { /*get the specific repo here*/ }
}
This is just some dummy code that represents some real world code I have (for brevity this is just sample code)
I have 2 ASP MVC apps that do fairly similar things.
Security / Session logic (along with other things) happens the same in both.
I've abstracted the base functionality from both into a new library that they both inherit. When the base class needs things that can only be obtained from the actual implementation I implement these as abstract methods. So in my above example I need to pull user information from a DB to perform authentication in the base library. To get the correct DB for the application I have an abstract GetRepository method that returns the repository for the application. From here the base can call some method on the repo to get user information and continue on with validation, or whatever.
When a change needs to be made to authentication I now only need to update one lib instead of duplicating efforts in both. So in short if you want to implement some functionality but not all then an abstract class works great. If you want to implement no functionality use an interface.
Just look at the Template Method Pattern.
public abstract class Request
{
// each request has its own approval algorithm. Each has to implement this method
public abstract void Approve();
// refuse algorithm is common for all requests
public void Refuse() { }
// static helper
public static void CheckDelete(string status) { }
// common property. Used as a comment for any operation against a request
public string Description { get; set; }
// hard-coded dictionary of css classes for server-side markup decoration
public static IDictionary<string, string> CssStatusDictionary
}
public class RequestIn : Request
{
public override void Approve() { }
}
public class RequestOut : Request
{
public override void Approve() { }
}
Use of abstract method is very common when using the Template Method Pattern. You can use it to define the skeleton of an algorithm, and have subclasses modify or refine certain steps of the algorithm, without modifying its structure.
Take a look at a "real-world" example from doFactory's Template Method Pattern page.
The .NET Stream classes are a good example. The Stream class includes basic functionality that all streams implement and then specific streams provide specific implementations for the actual interaction with I/O.
The basic idea, is to have the abstract class to provide the skeleton and the basic functionality and just let the concrete implementation to provide the exact detail needed.
Suppose you have an interface with ... +20 methods, for instance, a List interface.
List {interface }
+ add( object: Object )
+ add( index:Int, object: Object )
+ contains( object: Object ): Bool
+ get( index : Int ): Object
+ size() : Int
....
If someone need to provide an implementation for that list, it must to implement the +20 methods every time.
An alternative would be to have an abstract class that implements most of the methods already and just let the developer to implement a few of them.
For instance
To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods
AbstractList: List
+ get( index: Int ) : Object { abstract }
+ size() : Int { abstract }
... rest of the methods already implemented by abstract list
In this situation: get and size are abstract methods the developer needs to implement. The rest of the functionality may be already implemented.
EmptyList: AbstractList
{
public overrride Object Get( int index )
{
return this;
}
public override int Size()
{
return 0;
}
}
While this implementation may look absurd, it would be useful to initialize a variable:
List list = new EmptyList();
foreach( Object o: in list ) {
}
to avoid null pointers.
Used it for a home-made version of Tetris where each type Tetraminos was a child class of the tetramino class.
For instance, assume you have some classes that corresponds to rows in your database. You might want to have these classes to be considered to be equal when their ID is equal, because that's how the database works. So you could make the ID abstract because that would allow you to write code that uses the ID, but not implement it before you know about the ID in the concrete classes. This way, you avoid to implement the same equals method in all entity classes.
public abstract class AbstractEntity<TId>
{
public abstract TId Id { get; }
public override void Equals(object other)
{
if (ReferenceEquals(other,null))
return false;
if (other.GetType() != GetType() )
return false;
var otherEntity = (AbstractEntity<TId>)other;
return Id.Equals(otherEntity.Id);
}
}
I'm not a C# guy. Mind if I use Java? The principle is the same. I used this concept in a game. I calculate the armor value of different monsters very differently. I suppose I could have them keep track of various constants, but this is much easier conceptually.
abstract class Monster {
int armorValue();
}
public class Goblin extends Monster {
int armorValue() {
return this.level*10;
}
}
public class Golem extends Monster {
int armorValue() {
return this.level*this.level*20 + enraged ? 100 : 50;
}
}
You might use an abstract method (instead of an interface) any time you have a base class that actually contains some implementation code, but there's no reasonable default implementation for one or more of its methods:
public class ConnectionFactoryBase {
// This is an actual implementation that's shared by subclasses,
// which is why we don't want an interface
public string ConnectionString { get; set; }
// Subclasses will provide database-specific implementations,
// but there's nothing the base class can provide
public abstract IDbConnection GetConnection() {}
}
public class SqlConnectionFactory {
public override IDbConnection GetConnection() {
return new SqlConnection(this.ConnectionString);
}
}
An example
namespace My.Web.UI
{
public abstract class CustomControl : CompositeControl
{
// ...
public abstract void Initialize();
protected override void CreateChildControls()
{
base.CreateChildControls();
// Anything custom
this.Initialize();
}
}
}

Binding an interface to 2 different concrete objects in ninject based on the method attribute

I have 2 different concrete objects, lets save ConcreteOne and ConcreteTwo. Each of these implement an interface ILooseyGoosey. I would like ninject to call a different method depending on the attribute on that method.
This is what I have so far:
public class ConcreteOne : ILooseyGoosey
{
public void SomeMethod() { };
}
public class ConcreteTwo : ILooseyGoosey
{
public void SomeMethod() { } ;
}
public interface ILooseyGoosey
{
[CallConcreteTwo()]
void SomeMethod();
}
This is what I have defined in my Ninject module:
public override void Load()
{
Bind<ILooseyGoosey>().To<ConcreteOne>().InjectMethodsWhere(mi => mi.GetCustomAttributes(true).Where(a => a.GetType() == typeof(CallConcreteTwoAttribute)).Count() == 0);
Bind<ILooseyGoosey>().To<ConcreteTwo>().InjectMethodsWhere(mi => mi.GetCustomAttributes(true).Where(a => a.GetType() == typeof(CallConcreteTwoAttribute)).Count() > 0);
}
I get the error of:
System.NotSupportedException : Error registering service ILooseyGoosey: Multiple default bindings declared for service.
Found 2 default bindings:
The problem is that you are assigning one interface to two implementations without any conditional logic. The logic you are applying is only applied to which methods are injected. Ninject has no idea which binding to use since you are indicating that they are both default.
Not sure if you still need the answer, meta data based approach is the way to go. You'd want to bind in the meta data way in Ninject 2.0. Refer Contextual bindings with Ninject 2.0
Not written by me. Please see: http://www.ninject.org/wiki.html
Ninject
Download it Extensions Contribute Visit the Dojo Speak up Sponsors Merchandise
Version:
»Ninject
»MVC3
Multi injectionEdit PagePage History
Ninject allows you to inject multiple objects bound to a particular type or interface. For example, if we have our IWeapon interface, and two implementations, Sword and Dagger:
public interface IWeapon
{
string Hit(string target);
}
public class Sword : IWeapon
{
public string Hit(string target)
{
return "Slice " + target + " in half";
}
}
public class Dagger : IWeapon
{
public string Hit(string target)
{
return "Stab " + target + " to death";
}
}
Here we have the Samurai class. You can see that its constructor takes an array of IWeapon.
public class Samurai
{
readonly IEnumerable allWeapons;
public Samurai(IWeapon[] allWeapons)
{
this.allWeapons = allWeapons;
}
public void Attack(string target)
{
foreach (IWeapon weapon in this.allWeapons)
Console.WriteLine(weapon.Hit(target));
}
}
We can create bindings from the IWeapon interface to the Sword and Dagger types.
class TestModule : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind().To();
Bind().To();
}
}
Finally, a kernel is created with the module we defined above. We ask Ninject for an instance of a Samurai. Now, when you ask the Samurai to attack, you will see it has been given an array of all the types bound to IWeapon.
class Program
{
public static void Main()
{
Ninject.IKernel kernel = new StandardKernel(new TestModule());
var samurai = kernel.Get();
samurai.Attack("your enemy");
}
}
And you’ll see:
Stab your enemy to death
Slice your enemy in half
The kernel also exposes a GetAll method which lets you generate the same output by doing:
class Program
{
public static void Main()
{
Ninject.IKernel kernel = new StandardKernel(new TestModule());
IEnumerable weapons = kernel.GetAll();
foreach(var weapon in weapons)
Console.WriteLine(weapon.Hit("the evildoers"));
}
}
Continue reading: Object Scopes
Enkari
Ninject is the illegitimate brainchild of Nate Kohari. Copyright ©2007-2012 Enkari, Ltd and the Ninject project contributors.

Categories