[Design Pattern] Verhaltensmuster: Template Method


Thomas Darimont

Premium-User
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Template Method

Java:
package de.tutorials.design.patterns.behavioral;

import org.jpatterns.gof.TemplateMethodPattern.TemplateMethod;

public class TemplateMethodExample {
	public static void main(String[] args) {
		BusinessProcess process1 = new DefaultBusinessProcess();
		process1.execute();

		System.out.println("#########");

		BusinessProcess process2 = new ExtendedBusinessProcess();
		process2.execute();
	}

	static interface BusinessProcess {
		void execute();
	}

	static class DefaultBusinessProcess implements BusinessProcess {

		@TemplateMethod
		public void execute() {
			step1();
			step2();
			step3();
		}

		protected void step1() {
			System.out.println("Default Step1");
		}

		protected void step2() {
			System.out.println("Default Step2");
		}

		protected void step3() {
			System.out.println("Default Step3");
		}
	}

	static class ExtendedBusinessProcess extends DefaultBusinessProcess {
		@Override
		protected void step2() {
			System.out.println("Extended Step2");
		}
	}

}
Ausgabe:
Code:
Default Step1
Default Step2
Default Step3
#########
Default Step1
Extended Step2
Default Step3
Gruß Tom