1. Intention
The key to software reuse is to look for similarity. In many cases, similarity is manifested as business process similarity, but business
Units are special. In this case, you can define the Business Process skeleton in an operation, and
The implementation of meta extends to the subclass so that the subclass can redefine the business without changing the structure of a business flow.
Specific business units of a service flow. Here we need to reuse the structure of the business process, that is, the operation steps, and steps
The implementation (or the implementation of business units) can be completed in the subclass.
2. Use Cases
1) Implement the unchanged part of a business process at one time, and leave the variable behavior to the subclass for completion.
2) The common behaviors of each subclass should be extracted and centralized into a common parent class to avoid code duplication. First
First, identify the differences of existing services, separate different parts into new operations, and finally call these new
The template method of the operation to replace these different codes.
3) control subclass extension.
3. Structure
The structure of the template method is to use an abstract class. The key to defining the template method in the abstract class is:
Call an abstract method in a non-abstract method, which is implemented in the subclass.
Code:
Public abstract class payment {
Private double amount;
Public double getamount (){
Return amount;
}
Public void setamount (double value ){
Amount = value;
}
Public String gosale (){
String x = "unchanged process 1 ";
X + = action (); // variable process
X + = Amount + ", querying inventory status"; // attributes and unchanged process 2
Return X;
}
Public abstract string action ();
}
Class cashpayment extends payment {
Public String action (){
Return "cash payment ";
}
}
Test:
Public class test {
Public static void main (string [] ARGs ){
Payment O;
O = new cashpayment ();
O. setamount (555 );
System. Out. println (O. gosale ());
}
Assume that the system has been put into operation, and the user puts forward a new requirement to add credit card payment and check payment, you can write as follows:
Public class creditpayment extends payment {
Public String action (){
Return "pay by credit card, contact the payment institution ";
}
}
Class checkpayment extends payment {
Public String action (){
Return "pay by cheque, contact Finance Department ";
}
}
Call:
Public class test {
Public static void main (string [] ARGs ){
Payment O;
O = new cashpayment ();
O. setamount (555 );
System. Out. println (O. gosale ());
O = new creditpayment ();
O. setamount (555 );
System. Out. println (O. gosale ());
O = new checkpayment ();
O. setamount (555 );
System. Out. println (O. gosale ());
}
}