The template method pattern is the behavior pattern of the class. Prepare an abstract class that implements some of the logic in concrete ways and the behavior of concrete constructors, and then declares some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic. This is the template method.
Consider an example of calculating deposit interest below. Suppose the system needs to support two types of deposit accounts, the money markets account and the term deposit (CD or Certificate of deposite) account. The interest on deposits in these two accounts is different, so in calculating the deposit interest amount of a depositor, two different types of accounts must be distinguished.
The overall behavior of the system is to calculate interest, which also determines that the top logic as a template method pattern should be interest calculation. Since interest calculation involves two steps: one is to determine the type of account, and the other is to determine the percentage of interest, so the system requires two basic methods: One basic method gives the account type, and the other basic method gives the percentage of interest. These two basic methods constitute specific logic, because the type of account is different, so the specific logic will be different.
Public abstract class account{ protected String accountnumber; Public account () { accountnumber=null; } Public account (String AccountNumber) { this.accountnumber=accountnumber; } /* * Template method, calculate interest Amount * */public final Double calculateinterest () { double interestrate= Docalculateinterestrate (); String Accounttype=docalculateaccounttype (); Double Amount=calculateamount (accounttype,accountnumber); return amount*interestrate; } /* * Basic method left for subclass implementation * **/ protected abstract String docalculateaccounttype (); protected abstract double docalculateinterestrate (); Public final double Calculateamount (String accounttype,string accountnumber) { return 7243.00D; } }
public class Cdaccount extends account{ @Override protected String docalculateaccounttype () { return ' Certificate of Deposite "; } @Override protected Double docalculateinterestrate () { return 0.065D; }}
public class Moneymarketaccount extends account{ @Override protected String docalculateaccounttype () { Return "Monkey market"; } @Override protected Double docalculateinterestrate () { return 0.045D; }}
public class client{ private static account Acct=null; public static void Main (string[] args) { acct=new moneymarketaccount (); System.out.println ("Interest from the Money" +acct.calculateinterest ()); Acct=new Cdaccount (); System.out.println ("Interest from CD Account" +acct.calculateinterest ());} }
Template method Mode