Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

the Builder Pattern

 
Nichole Kim
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Nichole Kim
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see. Thank you!
 
Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
bparanj
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic