1. Template mode is to use the virtual class as a base class to perform almost the same part of the operation to extract the same parts, the different parts of their own implementation!
2. The following gives simple chestnuts:
What I'm going to do is put the elephant and the fox in the fridge and put the elephant and the fox in the same steps: Open the refrigerator and turn off the refrigerator, this operation is done in the base class, and the difference lies in the specific operation part:
One, the elephant is too fat, to measure and slice to put in the refrigerator
Two, the fox is too smelly, to wash clean and dry
So the program is as follows:
1. Base class: Basicfridgeoperation.java
PackageCom.learn.templateMode;/*** Created by Garfield on 9/15/2016.*/ Public Abstract classbasicfridgeoperation {Private voidOpenfridge () {System.out.println ("Open the fridge door"); } /*** Different parts about one of the whole steps * The subclass would make different implements*/ protected Abstract voidOperatefridge (); Private voidClosefridge () {System.out.println ("Close the fridge door"); } /*** The same operation steps*/ Public voidoperation () {Openfridge (); Operatefridge (); Closefridge (); }}
2, put into the Elephant class: Operateelephant.java
PackageCom.learn.templateMode;/*** Created by Garfield on 9/15/2016.*/ Public classOperateelephantextendsbasicfridgeoperation {/*** Same function but different implement*/ protected voidOperatefridge () {System.out.println ("Measure the Elephant"); System.out.println ("Slice up the Elephant"); System.out.println ("Put the elephant in"); }}
3, put the Fox class: Operatefox.java
PackageCom.learn.templateMode;/*** Created by Garfield on 9/15/2016.*/ Public classOperatefoxextendsbasicfridgeoperation {/*** Same function but different implement*/ protected voidOperatefridge () {System.out.println ("Clean up the fox"); System.out.println ("Dry The Fox"); System.out.println ("Put the fox in"); }}
4, test: Operationtest.java
PackageCom.learn.templateMode;/*** Created by Garfield on 9/15/2016.*/ Public classOperationtest { Public Static voidMain (string[] args) {System.out.println ("====== begin to deal with the elephant========="); Basicfridgeoperation basicfridgeoperation=Newoperateelephant (); Basicfridgeoperation.operation (); System.out.println ("====== begin to deal with the fox========="); Basicfridgeoperation BasicFridgeOperation2=NewOperatefox (); Basicfridgeoperation2.operation (); }}
5, output Result:
====== begin to deal with the elephant=========open the fridge doormeasure the elephantslice of the elephantput in the Elephantclose the fridge door====== begin to deal and the fox========= open the fridge doorclean up thefoxdry t He foxput in the foxclose the fridge door
, That,s all.
Java mode: A simple understanding of template patterns