← Back to Advanced Java Course | Chapter 6: Design Patterns | Lesson 13 of 14

Java का Template Method Pattern

Template Method pattern किसी base class में किसी algorithm का पूरा skeleton define करता है, कुछ individual steps को subclasses पर छोड़ते हुए जो algorithm की structure बदले बिना सिर्फ उन steps को override करें।
Syntax
java
abstract class Template {
    final void templateMethod() {
        step1();
        step2();
    }
    abstract void step1();
    abstract void step2();
}

What is the Template Method Pattern?

Template Method pattern किसी base class के method में किसी algorithm का पूरा skeleton define करता है, इसके कुछ individual steps को subclasses पर छोड़ते हुए, जो algorithm की overall structure बदले बिना सिर्फ उन steps को override करती हैं।

उदाहरण: What is the Template Method Pattern?

java
public class Main {
	static abstract class Recipe {
		final void make() { // skeleton
			boilWater();
			addMainIngredient();
		}
		void boilWater() { System.out.println("Boiling water"); }
		abstract void addMainIngredient();
	}
	static class Tea extends Recipe {
		void addMainIngredient() { System.out.println("Adding tea leaves"); }
	}
	public static void main(String[] args) {
		new Tea().make();
	}
}

Defining the Algorithm Skeleton

template method आमतौर पर final चिह्नित होता है ताकि subclasses पूरे sequence को न बदल सकें, सिर्फ अपने individual implementations को, हर subclass में algorithm के shape को consistent रखते हुए।

उदाहरण: Defining the Algorithm Skeleton

java
public class Main {
	static abstract class Recipe {
		final void make() { step1(); step2(); } // final -- subclasses can't reorder this
		void step1() { System.out.println("Step 1"); }
		abstract void step2();
	}
	static class Custom extends Recipe {
		void step2() { System.out.println("Custom step 2"); }
	}
	public static void main(String[] args) {
		new Custom().make();
	}
}

Overriding Specific Steps

base class में abstract declared steps को हर subclass को implement करना चाहिए, हर subclass को shared structure और किसी भी concrete steps को बिना बदले reuse करते हुए algorithm के बिल्कुल उन्हीं हिस्सों को customize करने देते हुए।

उदाहरण: Overriding Specific Steps

java
public class Main {
	static abstract class Report {
		final void generate() { header(); body(); }
		void header() { System.out.println("Header"); }
		abstract void body(); // must be implemented by every subclass
	}
	static class SalesReport extends Report {
		void body() { System.out.println("Sales data"); }
	}
	public static void main(String[] args) {
		new SalesReport().generate();
	}
}

Hook Methods

एक hook method का base class में एक default implementation होता है जिसे कोई subclass template के behavior को प्रभावित करने के लिए optionally override कर सकती है, जैसे किसी optional step को skip करना, बिना इसे override करना ज़रूरी हुए।

उदाहरण: Hook Methods

java
public class Main {
	static abstract class Recipe {
		final void make() {
			step1();
			if (wantsExtra()) extra(); // optional hook
		}
		void step1() { System.out.println("Step 1"); }
		boolean wantsExtra() { return false; } // default, overridable
		void extra() { System.out.println("Extra step"); }
	}
	static class Custom extends Recipe {
		boolean wantsExtra() { return true; }
	}
	public static void main(String[] args) {
		new Custom().make();
	}
}

Template Method vs Strategy

Template Method inheritance का उपयोग करता है, एक subclass base class में define किए किसी fixed algorithm के specific steps को override करते हुए, जबकि Strategy composition का उपयोग करता है, runtime पर इसके बजाय एक पूरी तरह अलग algorithm object को swap करते हुए।

उदाहरण: Template Method vs Strategy

java
public class Main {
	static abstract class TemplateExample { // inheritance -- subclass overrides one step
		final void run() { System.out.println("Fixed structure, step overridden: " + step()); }
		abstract String step();
	}
	interface StrategyExample { String algorithm(); } // composition -- swap the whole algorithm object
	public static void main(String[] args) {
		new TemplateExample() { String step() { return "custom"; } }.run();
		StrategyExample strategy = () -> "different algorithm";
		System.out.println(strategy.algorithm());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. template method को final declare न करना, जिससे कोई subclass algorithm का order बदल सकती है।
  2. सिर्फ template method को call करने के बजाय step methods को बाहर से call करना।
  3. base class के constructor से किसी overridable step को call करना, जो subclass fields के initialized होने से पहले ही subclass code चला सकता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.