I am brushing up on my design patterns at the moment and got a little confused when I came across this tutorial:
http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs
If you look at listing 7 onwards, the author says it is using the decorator pattern. However, is one of the main principles of this pattern to wrap objects and ADD responsibilities and behaviour?
I think it looks more like and adapter pattern as it is adapting the MVC specific ModelStateDictionary to work with a more flexible IValidationDictionary so that different implementations can be used with the service if WPF etc were used instead. There is new responsibility or behaviour added.
Do I have this correct or not? If I'm wrong can anyone please explain why?
Thanks
I agree with you, that looks to me like the Adapter Pattern, that is, the ModelStateDictionary is abstracted behind the interface IValidationDictionary (the adapter interface) using a concrete type (the adapter) such that the implementation can be changed later.
The Decorator Pattern usually provides additional functionality via composition, exposing the same interface as the decorated type. This is usually done via sub-classing or through interface implementation.
An example of a decorator would be:
you have a repository class that fetches "objects" from the database
you have a repository decorator class that can cache objects without needing to fetch them from the database each time. This decorator class provides the cache fetching and retrieving through composition by sub-classing the original repository class and overriding the Get() method to first check the cache for the item (and Save() would be overridden to also update the cache as well as the database).
I think you're correct, and that there's an error in the post. From the article:
The Decorator pattern enables you to wrap an existing class in a new
class in order to implement an interface.
That's not exactly true - decorators do allow you to wrap one implementation inside another, but the intention usually isn't to implement another interface, but to "decorate" the instance with new functionality. The adapter pattern allows you to take two dissimilar interfaces, and modify one instance to be have like another.
Related
When implementing the repository pattern, in conjunction with entity framework, why do I see many examples using an interface for their repository class? A specific example of a reference of this is here.
What's the point of the interface? Why not just the class? Will there really need to be more than one class subscribing to that very specific interface, for just Employees, for example?
It's a frequently used pattern, quite often used specifically for unit testing, not really specific to entity framework, or repository pattern, or even any data access kind. Another great benefit is that it gives the chance to latter provide an alternate implementation without change the code using it.
Consider for example this code, that uses the dependency injection pattern:
public class EmployeeService
{
private readonly IEmployeeRepository employeeRepository;
public EmployeeService(IEmployeeRepository employeeRepository)
{
this.employeeRepository=employeeRepository;
}
public IEnumerable<Employee> GetAllEmployees()
{
IEnumerable<Employee> employeeList=this.employeeRepository.GetAll();
//Optionally do some processing here
return employeeList;
}
}
By having the interface in the repository, note that you now can work entirely using the interface, without ever mentioning the actual repository, this is the real value of it. It gives mainly two benefits:
If you want to write an automated unit test for this class, you may give it a fake implementation of the IEmployeeRepository, which would not go to the real database, but instead return a hardcoded list, so that you can test your method without worrying about the DB for now. This is called a 'Mock', and is often the main reason of putting that interface there. There are also a couple of libraries that automate that process, all relying on the fact that they generate a fake class implementing an interface. By far, that's the most common reason for putting an interface like that.
You may decide sometime in the future that you want to replace entity framework with something else, or, say, want to implement a repository to something different than a relational DB. In this case, you would write another repository, implementing the very same interface, but doing something completely different. Given that the services using it rely only on the interface that code will work entirely unmodified as long as the same contract is respected (of course, the code that actually creates the repo and gives it to the service must change, but that's another history). That way the same service works the same no matter where it reads/saves the data.
I'm trying to wrap my head around repository pattern and dependency injection concepts for my ASP.NET MVC applications.
I ran across the article Repository Pattern with Entity Framework, and really liked how simple the code is. There doesn't appear to be that much code and it's all completely generic. That is, there's no need for multiple repositories for the different objects in the database as most people appear to be doing. This is just what I want.
However, the code is written for code first, which I'm not planning to use.
Questions:
Is there a good reason why the same code couldn't be used for applications that don't use code first?
Can someone recommend a better approach for my applications that don't use code first? (Keeping in mind that I'm absolutely sold on this generic pattern.)
Any other tips to help me move forward?
You can make a repository interface for any underlying data store. You can simply define an interface like so:
public interface IRepository
{
IQueryable<T> GetQueryable<T>();
void Insert<T>(T item);
}
Then, you can implement a class behind this which will implement it. It doesn't have to be code-first; you can back it with an ObjectContext created from an EDMX file, for example.
The key here is in creating the right abstraction. You can easily do that with an interface, and then implement it however you want behind the scenes.
Because you're using dependency injection, the implementation doesn't matter as much, as long as you've defined the contract correctly, the implementation (and testing of it) should be simple. And if it doesn't work, or you want a different data store altogether, you just tell your dependency injector to use a different implementation, the contract doesn't change.
The same can be said for any abstraction you create; you can have an interface that reads and writes data (like the article you reference does), you just have to pull the abstraction out.
Have a look on this. I think this link will help you most
http://www.codeproject.com/Tips/572761/Generic-repository-pattern-using-EF-with-Dependenc
In this link Generic repository pattern is used with dependency injection in MVC project without using code first approach.
I first made a new repository interface for each of my entities e.g. IClientRepository. I then made a class for each entity e.g. SqlClientRepository. I did this for a lot of my entities and then realized that they all had the same methods: Add, Update, Delete, GetAll.
So I realized that I should probably just make the one interface instead of making a separate one for each.
The problem is that now my dependency injection won't work since I can only map the interface to one repository:
Bind<IClientRepository>().To<SqlClientsRepository>().WithConstructorArgument("connectionString", WebConfigurationManager.ConnectionStrings["MyDb"].ConnectionString);
The only work-around I can see is to combine all of the repositories or go back to my first attempt. Using the first attempt would also allow me to change the return types for certain entities e.g. IClientRepository.Add() could return the new client's id, and some other entities might not need that.
Appreciate any thoughts.
You could have your ClientRepository implement both your BaseRepository and a specific IClientRepository. That way your Base can have the usual Add/Remove etc and your IClientRepository could have specialized methods (or be empty in some cases probably). Your IoC could resolve using your IClientRepository.
This is how i do it:
public class CustomerRepository : BaseRepository<Customer>, ICustomerRepository {...}
and
unityContainer.RegisterType<ICustomerRepository, CustomerRepository>();
Good luck :)
A common approach for repositories is to create a base interface like "IRepository" with the common CRUD methods or methods that all repos can use. Then for each specific repository create a new interface that derives from the base interface but includes the domain-specific methods for that repo. The same thing can be done for a base Repository implementation and the more specific implementation classes. This way you have a common place for common functionality, but you still have specific interfaces for each concrete domain-specific repository implementation.
It's hard to say for sure without knowing what you are trying to accomplish. In my latest project, there is one repository per class, IRepository<T>. That might get you out of your IoC binding trouble.
one solution is to make the Interface generic. this way, it's general enough, while still being flexible.
I love design patterns, the problem is that some can be really tedious to implement.
For example, decorating an object that has 20+ members is just plain annoying.
So, I wanted to create a nice library of design patterns to be applied to classes (either as base classes or attributes) to make implementation of these patterns much quicker and eaiser.
The problem is...I'm not quite sure where to start - because I am mostly unfamiliar with attributes and reflection.
I would like to utilize attributes to mark Singletons (similar to the Export tag), Multitons, and Decorators...if at all possible. But I don't even know where to start in order to create a singleton attribute that alters the functionality of its instances.
My limited research has led me to believe that using reflection/late binding through an attribute and gaining access to all marked classes in the assembly, would allow you to hack together a singleton...but I'm still not entirely sure how that would be done.
A framework I found, called Ninject 1.0, created a Singleton attribute - but the library is so extensive and undocumented, that I am currently unable to follow its logic.
I feel like a library with this sort of functionality would be a great contribution to many developers out there. So, it would be greatly appreciated if someone could provide some sample code that gets me pointed in the right direction to create one of these patterns as an attribute - whose code isn't overly involved. Or if someone would be willing to walk me through Ninject's singleton attribute implementation so I may work off of that...
Thank you for your time and consideration.
I think you have a slight confusion on what design patterns mean.
A pattern is really a common way of doing things, designed to solve a particular problem.
You don't really use patterns for patterns' sake. More patterns usage doesn't automatically means good. You use a pattern to solve a type problem -- and hopefully that pattern is the recognized best-practice way to solve that problem. Don't try to appy a pattern to your code because you can.
Now, after all this, it can really be seen that what you are planning to do is not the right way of going about implementing pattern(s). You don't mark code with attributes etc. and then call them patterns. The pattern is your code. Your code is the pattern. For example, you don't mark a publisher/subscriber pattern on a class unless it really implements publish/subscribe functionalities. For example, you don't mark a class with "Singleton" and then it becomes a singleton pattern; using the Singleton pattern requires you to code your program (and your classes) around that design.
You may, however, mark code or classes with certain attributes that can aid in checking whether the code/classes conform to a particular pattern.
For example, you may implement a type checker that goes through all your class, check if anything is marked "publisher" and see if that class implements the "IPublisher" interface. Or your type checker can check if any class is marked "Singleton" whether the constructor allows construction of more than one instance at any one time.
But attributes and reflection is typically not the tools to implement a pattern.
In C#, where there is no multiple inheritance, the way you implement patterns is sometimes through the base class only. For example, you may implement a "singleton" pattern by declaring a "SingletonObject" base class which limits itself to only one instantiation. Then you derive any class that you want to be singletons from this base class. For example, you may implement a "publish/subscribe" pattern by declaring IPublisher and ISubscriber interfaces.
Now, if you really just want to just use the Decorator pattern on C# classes (as per the title of your question), what you are looking for is an automatic wrapper object generator. You can based your wrapper on an ExpandoObject, loop through the properties of the base object, and add properties to the ExpandoObject that simply delegates back to the base object. Then add new properties to the ExpandoObject on top of your base object. Voila! You get your auto-Decorator-Pattern wrapper class generator.
so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.