Say I have the following interface:
ICarProvider
And the following classes implementing it:
RedCarProvider:ICarProvider
BlueCarProvider:ICarProvider
GreenCarProvider:ICarProvider
Now, what I would like to do is this:
Depending on the settings of the user, create a single instance of one (only one) of these classes and use that throughout the entire session of the application. So my logic should only know the interface and where to get the instance.
Is there a pattern for this?
Thanks!
It's called the factory pattern.
Singleton Factory
http://www.wikijava.org/wiki/Singleton_Factory_patterns_example
Singleton Factory method
Creating singleton factory
Abstract Factory pattern. Read more on wikipedia.org
In software development, a factory is the location in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage. This allows for new derived types to be introduced with no change to the code that uses the base class.
That sounds like the some sort of factory pattern.
I can't refrain myself from being sceptical about the need for a pattern to describe something so trivial.
That what you have presented seems to be a factory patter, but you should not create a class only for describing the properties of an object, sometime is better to use an map for those.
Related
Having 2 classes implementing the same interface, how to register them?
The first registration works well:
iocContainer.Register<IEcContract, EcContract>(Lifestyle.Transient);
But if I register the second class with the same interface, it throws an error. I am using Simple Injector.
What do you expect from the container? Which instance should it return?
If you for some reason need to resolve all the instances (in a collection), see swatsonpicken's answer.
If you need a specific implementation, you need a way to decide which one.
Some DI libraries let you name the instances and then ask the container for one of the named instances. Simple Injector does not support it.
So if you need to switch between implementations with Simple Injector, consider writing a custom factory which always returns the implementation you need.
I don't know this IoC container, but others use a scheme like this:
container.RegisterCollection<IEcContract>(new[] { typeof(EcContract), typeof(OtherClass)});
Maybe check the documentation for your IoC container and see if there's a RegisterCollection (or similar) method.
Should a Singleton class be allowed to have children? Should we seal it? What are the pro's and con's?
For being able to inherit from a Singleton class, we would have to make the constructor protected instead of private. Now, that will be fine in c#, but the protected word in java gives both child-classes and package-classes access to the constructor. Which means not only classes that inherit from our Singleton can access the constructor but other classes in the same package can do it.
I'm a bit confused about all this facts. Maybe I am making a big fuss about nothing to worry about too much? Until now, I never had any necessity of trying to inherit from a Singleton, so maybe this is just an academic question!
Thanks
Yes, Singletons should be sealed. No, they should not be inherited.
The reason is that the primary (really only) behaviour of a Singleton is to create an instance of itself at some predetermined time. Since this functionality is static, it can't be overridden, so it would have to be duplicated instead. Once you start duplicating, you have multiple instances of a singleton, which doesn't really make sense.
Either that or you end up with race conditions or other conflicts as the "derived" singletons fight for control over the global instance, which not only doesn't make sense, it's dangerous.
There are some hackish workarounds to the Singleton inheritance problem, but that is what they are - hacks. The Singleton pattern is not really suitable for inheritance.
A better solution is to use an IoC Container framework to handle the "Singleton" (lifetime) aspect of the class. At that point you can use a POJO and simply inherit from it.
EDIT: Some links that may help:
List of .NET Dependency Injection Containers (IOC)
Open Source Inversion of Control Containers (Java)
Dependency Injection in .NET (book)
Mark Seemann's .NET blog - Dependency Injection category
Look for ones that handle lifetime management. You want to be able to configure the container (which acts like a generic factory) so that requests for instances of "Singleton" classes always return the same instance (at least for the same container). You generally only have one container instance at the highest level of your application.
Hmm, sounds like a question many of us got asked at school when learning about Singletons. I'd suggest reading the following links.
http://msmvps.com/blogs/jon_skeet/archive/2006/01/20/singleton-inheritance.aspx
http://msdn.microsoft.com/en-us/library/84eaw35x.aspx
Many would strongly discourage inheriting from a singleton, but real-life programming often requires exactly such an approach. I personally would say, don't inherit from a singleton as a rule of thumb, but don't lock yourself into a design which blocks off such an approach. A pragmatic development approach is always the best approach...
If you can extend from a singleton, then it means that you can have more than one instance of it. This contradicts the whole singleton idea. Just make it a "normal" class and write the code around it accordingly that you instantiate it only once and use the same instance forever. If you need it to be. Dependency injection can help a lot in this.
If you want to use inheritance in conjunction with the singleton pattern, you should put the inheritable state and behaviour into an abstract base class and define the singletons as (final) subclasses.
Currently I have created a ABCFactory class that has a single method creating ABC objects. Now that I think of it, maybe instead of having a factory, I could just make a static method in my ABC Method. What are the pro's and con's on making this change? Will it not lead to the same? I don't foresee having other classes inherit ABC, but one never knows!
Thanks
Having a single, static method makes this much more difficult to test whereas having an instantiable object allows this to be easier to test. Also, dependency injection is later more of an option with the non-static solution.
Of course, if you don't need any of this, then these are not good arguments.
The main advantage of the factory method is the ability to hide reference to a specific class behind an interface. Since static methods can not be a part of the interface, static factory methods are basically the same as the constructor method itself. The only useful application of the static factory methods is to provide access to a private constructor - what is commonly used for singleton-pattern implementation.
In reality, if you want to get the benefits of a factory class, you need the static method in it's own class. This will allow you to later create new factory classes, or reconfigure the existing one to get different behaviors. For example, one factory class might create Unicorns which implement the IFourHoovedAnimal interface. You might have an algorithm written that does things with IFourHoovedAnimal's and needs to instantiate them. Later you can create a new factory class that instead instantiates Pegasus's which also implement IFourHoovedAnimal's. The old algorithm can now be reused for Pegasus's just by using the new factory! To make this work both the PegasusFactory and the UnicornFactory must inherit from some common base class(usually an abstract class).
So you see by placing the static method in it's own factory class, you can swap out factory classes with newer ones to reuse old algorithms. This also works for improving testability, because now unit tests can be fed a factory that creates mock objects.
I have done the latter before (static factory method on the class that you are creating instances of) for very small projects, but it was only because I needed it to help refactor some old code, but keep changes to a minimum. Basically in that case I had factored out a chunk of code that created a bunch of ASP.NET controls, and stuff all those controls into a user control. I wanted to make my new user control property based, but it was easier for the old legacy code to create the user control with a parameter based constructor.
So I created a static factory method that took all the parameters, and then instanced the user control and set it's properties based on the parameters. The old legacy code used this static method to create the user control, and future code would use the "prettier" properties instead.
For concrete classes, factory methods are really just a method of indirection around creating the actual type (which isn't to say they aren't useful, but as you've found, the factory method could really be anywhere).
Where the factory method really shines though is when your method creates instances of an interface type.
The "D" in Uncle Bob's SOLID Principles of Object Oriented Design is "The Dependency Inversion Priciple" Depend on abstractions, not on concretions.
An extreme following of that principle could have your main class create all your factories, with each factory using other factories via interfaces. The only appearance of "new" (creating concrete objects) would be in your main class, and your factories. All your objects would work with interfaces (abstractions), with the concrete dependencies obtained from supplied factory implementations.
You could then very easily adjust, or provide multiple Main classes customised for different scenarios.
Overuse of design patterns are dangerous, and creational design patterns make sense when you have class hierarchies with defined interfaces, or need to build rather complex objects. If you have a simple design, use simple solutions. Therefore, in your case, Factory Method would be enough
Yes, you are right, it is another design pattern :)
Why are we implementing, for example ICloneable or IDisposable. I'm not asking what ICloneable or IDisposable do, but I want to learn what's a good reason to implement these interfaces rather than just writing a method which disposes or clones our objects?
Using interfaces keeps the use of those pieces of functionality consistent. That way, when another class wants to / needs to use your class, it can act on it as a cloneable, disposable object without worrying about your particular implementation details.
By implementing a well known interface, you can have polymorphism, which enable you to write generic code that can act on any instance of a class that implementes a given interface.
You can check the Wikipedia article on polymorphism for more.
Because you may want the same code to operate on instances of different classes. For example, a form cleanup routine wants to iterate over all components and dispose them. In order for it to do this, it needs to refer to the components through a type: either a common base class or an interface. Single inheritance means that a common base class isn't always feasible (suppose my form has both a FileStream and a Button -- what common base class could they have that the cleanup routine would access them through?); hence interfaces.
Adding to more interface wisdom, interfaces can be used as contracts between consumer code and service code. Instead of saying this is object that we will be dealing with, with interfaces the agreement is, this is how the object i return looks. In code, it could be something like:
service code
public IEnumerable<int> GetNumbers(){ return new []{1,2,3,4,5}; }
client code :
var result = serviceProxy.GetNumbers();
Here the service code can change implementation to return any class that satisfies IEnumerable without breaking client code.
Besides all this you have got other applications like IoC DI, Unit Testing, Object Mocking. All this reaping benefits of polymorphic goodness.
Among other reasons, read about the using block.
Phoebus gave a great answer, but to add a bit more.
It forces you to write the methods that are expected for cloning or making something that can be disposed. If you had to write just the method, would you always include all the necessary methods, or would the signature always be the same?
If there is a new framework, and they add something, to help ensure that the operations are done correctly, by having interfaces then it forces you to implement any new changes, as your application will no longer compile.
In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently.
Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface.
Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.
An interface separates what's done from how it's done. Clients deal with the interface type, without having to know what the implementation class is, because they can rely on the contract it enforces.
This is important for situations that generate dynamic proxies. Clients need not know that they're dealing with a proxy, which gives you the freedom to inject whatever behavior you need. It's a common technique for aspect-oriented programming.
It is possible, given only an interface, to create an object from this?
Something like:
var obj = new IWidget();
(I know this code isn't right - VS stays cannot create an instance of IWidget)
I'm in a context where my project has references to the interfaces, and I want to create concrete objects and return them from a method - but I can't figure out how to create the objects purely from the interfaces.
You can't create an object from an interface. You can create an object from a class that uses that interface.
For example:
IList<string> x = new IList<string>();
will not work.
IList<string> x = new List<string>();
will.
Interfaces cannot be created, only objects that use the interface can be created.
That code is actually correct for COM objects, due to compiler wizardry. Normally it's not though.
The problem is, how is the compiler meant to know which implementation to create? There could be any number around. You might want to consider having a factory for the interface, or possibly using dependency injection (e.g. with Spring.NET or Castle Windsor).
This will not be possible purely from the interfaces (and shouldn't be, what if there is more than one implementation of it?). It sounds like what you want to do is expose an interface, but not the implementation. Is that correct?
You essentially would want a Factory Pattern. This pattern involves making a method that returns the interface, but internally instantiates a concrete type. It lets you hide the concrete type from anyone using the interface.
If you go a step further you could use Inversion of Control (IoC). I don't know what the best option is for doing this in .Net, but one option is Spring.Net. You use a configuration file to define all of the different setups for your concrete objects, and then have spring automatically "inject" those instances into your classes that use the interface.
No would be the short answer. But I guess you could use an IoC container to inject an implemtation.
You might be looking for a Dependency Injection framework.