nikolai traikov: I'm not even close to be an expert at this, as some people that replies here, but maybe i can help you..
You are missing some code there, but i think the idea is: Say tomorrow you want to change Motif to something else.. Using the first example, changing 'new PMWidgetFactory();' for the new implementation of the factory should suffice. But, in the second example, your change will expand to every place in which you use Motif!, and, even if you where using interfaces for the components, you still would have the job of changing the creation of every individual Motif component to the creation of the new ones.. using the abstract factory.. you just need to know how to instantiate an implementation for it... and even then.. you could just accept the interface of the factory as a parameter for the constructor of the classes that use it and decouple the implementation even more.
Of course, you don't allways need to do something like this.. there are many scenarios where a pattern implementation is overkill.
If i'm wrong or mssing something, please, feel the need to correct me!!!. Regards.
I'm a bit new to interfaces. I'm not quite sold on them yet. Maybe someone here can help.
For example, I can implement one in my new class and fulfill all of its implementation requirements. I can then remove all references to the interface but keep the details of my implementation and my class still works the same. In other words, my class will work the same with or without the interface implementation references. So why keep the references?
For a single type of class, you are not missing anything.
However, consider the following class where Animal is an Interface:
privatefinal List<Animal> animals;
// Initially the hospital has no animals to treat.
this.animals = new ArrayList<Animal>();
void add(final Animal animal)
for(final Animal animal : animals)
This AnimalHospital can accept any kind of animal for treatment - provided the animal's class (e.g. Cat, Dog, etc.) implements the Animal interface.
If, at a later date, someone creates a new animal class (such as a DuckBilledPlatypus) that implements the Animal interface then that animal can also be treated at the hospital without any change to the hospital code. As long as it's an Animal then the AnimalHospital can handle it.
The same is also hold true if someone later extended the Dog to create a Doberman sub-class of dog.
That is power that interfaces bring to your code.
Flat View: This topic has 17 replies
on 2 pages