Difference between revisions of "Template Method"

From CDOT Wiki
Jump to: navigation, search
(Code Samples)
(Code Samples)
Line 6: Line 6:
 
== UML Diagram ==
 
== UML Diagram ==
  
== Code Samples ==
+
== Pseudo Code ==
 
 
Java:
 
  
 
<pre>
 
<pre>
abstract class CheckBackground {
+
abstract class AbstractRenderer
 
+
{
    public abstract void checkBank();
+
// Define the order in which the graphical routines should be executed
    public abstract void checkCredit();
+
void render()
    public abstract void checkLoan();
+
{
    public abstract void checkStock();
+
// First draw the graphics
    public abstract void checkIncome();
+
drawGraphics();
 
+
  //work as template method
+
// Then draw the GUI on top of the graphics
    public void check() {
+
drawGUI();
        checkBank();
+
}
        checkCredit();
+
        checkLoan();
+
void drawGraphics();
        checkStock();
+
void drawGUI();
        checkIncome();  
 
    }
 
 
}
 
}
 
+
class LoanApp extends CheckBackground {
+
class Renderer extends AbstractRenderer
    private String name;
+
{
 
+
void drawGraphics()
    public LoanApp(String name) {
+
{
        this.name = name;
+
// Draw the graphics here
    }
+
}
   
+
    public String getName() {
+
void drawGUI()
        return name;
+
{
    }
+
// Draw the graphical user interface here
 
+
}
    public void checkBank() {
 
        //ck acct, balance
 
        System.out.println("check bank...");
 
    }
 
 
 
    public void checkCredit() {
 
        //ck score from 3 companies
 
        System.out.println("check credit...");
 
    }
 
 
 
    public void checkLoan() {
 
        //ck other loan info
 
        System.out.println("check other loan...");
 
    }
 
 
 
    public void checkStock() {
 
        //ck how many stock values
 
        System.out.println("check stock values...");
 
    }
 
 
 
    public void checkIncome() {
 
        //ck how much a family make
 
        System.out.println("check family income...");
 
    }
 
 
}
 
}
 
</pre>
 
</pre>

Revision as of 17:12, 19 March 2007

Template Method

Template Method, a class behavioral pattern, provides the general steps of a method while deferring the implementation to its subclasses. Used to encapsulate algorithms, it can help reduce code duplication and maximizes the reuse of subclasses. Generally, an abstract base class is created, defining a template method of an algorithm. Later on, the subclasses can alter and implement the behavior.

UML Diagram

Pseudo Code

abstract class AbstractRenderer
{
	// Define the order in which the graphical routines should be executed
	void render()
	{
		// First draw the graphics
		drawGraphics();
 
		// Then draw the GUI on top of the graphics
		drawGUI();	
	}
 
	void drawGraphics();
	void drawGUI();
}
 
class Renderer extends AbstractRenderer
{
	void drawGraphics()
	{
		// Draw the graphics here
	}
 
	void drawGUI()
	{
		// Draw the graphical user interface here
	}
}

References

Links

BTP600