Hi, I am reading some tutorial re the Builder Pattern. In the example, the author declared an abstract class, and then two derived classes which are Builders, one factory class which is called Director. I have no problem with this structure. My question is: can we declare an interface instread of the abstract class for the builders? When to declare an interface, when to declare an abstract class? Thank you!
You possibly can use an interface, yes. You use an abstract class, if there is some implementation you want to reuse between subclasses (for example for the Template Method pattern). You use an interface if you want to have the option for multiple inheritance. If neither of the above is true for you, throw a coin...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
When you use Builder you can use interfaces but you will probably want to use Abstract classes instead that way you can give the methods a default (empty) implementation. Here is the reason which the example in the GoF book fails to show this, because of its simplicity. When you use Builder typically the Builder class will have lots of methods. So if you just declare an interface then all of your ConcreteBuilder classes will have to implement all of those methods, some of which don't even make sense for the particular ConcreteBuilder class. Not only are you spending more time re-writing code that you shouldn't it is kinda confusing because if I'm looking at a ConcreteBuilder class and I see that you have implemented A(), B() and C() then I'm going to expect that they all make sense for that class. Where as if that was in a super-class I would pay less attention to it. Hope this helps.
One more deciding factor to help you decide whether to use interface or abstract class is : Interface does not force the static structural relationship like abstract class. You could implement an interface anywhere in the hierarchy. Also note using abstract class might enforce semantic constraints whereas interfaces do not. Check out the article : http://www.javaworld.com/javaworld/jw-12-1998/jw-12-techniques_p.html for more on this. Bala