Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This looks like the place to use the <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Template_method_pattern" rel="nofollow noreferrer">Template Method design pattern</a>. With the template method pattern, the general algorithm can be implemented and finalized in the abstract class, whereas some of the specifics can be implemented in the child classes.</p> <p>In order to implement the Template method:</p> <ul> <li>You'll need to finalize the algorithm, to control the subclassing behavior. By disallowing subclasses from overriding the template method via the final keyword, one can ensure that the sufficient checks can be implemented in the template to ensure that the invariants in the algorithm are held good.</li> <li>You'll need to allow subclasses to override the behavior that can vary. The subclass can completely override this behavior, and such methods are usually abstract in the parent class, often serving as places where subclasses can implement hooks.</li> </ul> <p>The Template method can be implemented in your example as</p> <pre><code>public abstract class AbstractStringGenerator{ // marked as final. Subclasses cannot override this behavior public final String generateLine(String input){ String result = generateLineHook(input); //do contract checking... //if new line char is not the last char, then throw contract exception... if(!result.endsWith("\n")){ throw new IllegalStateException("Result from hook does not contain new line"); } return result; } /** * This method must return a new line as it's last char * @return string output */ protected abstract string generateLineHook(String input); } public class ConcreteStringGenerator{ /** * This method overrides the beh * @return string output */ protected String generateLineHook(String input){ return "blah\n"; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload