• Post Reply Bookmark Topic Watch Topic
  • New Topic

Template Method  RSS feed

 
Keshan Pillay
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone! Thank you for looking at my thread.

I'm in the middle of an assignment for a cs course on OOP, and I have to use template method to accomplish a particular task.
I was wondering if someone could explain the template method to me in simple terms or link me somewhere where it's explained well.
I've googled it and the notes online don't make much sense to me.

My current task: I have Shape superclass, and various shape type subclasses. The paint method is defined in Shape, and implemented in the subclasses. Now, one of the constructors in Shape, allow for text to be printed on the shape being displayed. What I need to do is, assume that someone else can edit my subclasses, but not my Shape class (they only have the byte code for it ;D ) and If a shape has text, I have to guarantee that it's displayed, and that the text cannot be changed or removed by the subclasses.
I'm pretty certain I have to use the template method for this, so like I said, if anyone could explain it to me or such that would be wonderful and most appreciated.

Many thanks,
Keshan Pillay =]

EDIT: I apologise if this is in the wrong board, but I don't know what level of Java this is, but I'm pretty sure it's not beginner =D
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A template method is a method in a superclass that calls a method from the subclass -- i.e., an abstract method in the superclass, which must be implemented by any subclass -- to do part of its work. For example, imagine the "paintThisShape()" method in Shape. At one point, it needs the text to paint, so it calls the abstract getText() method. Each subclass can override that method, supplying whatever text it wants. Some might supply fixed text, others might supply text that's different for every object, etc. So Shape.paintThisShape() calls getText() which is implemented as (for example) Circle.getText() -- and everybody's happy.
 
Keshan Pillay
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply! Hmm, I kind of understand...but how does this guarantee that the shapes MUST have the text?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!