The template method uses inheritance to perform cutting. When the coupling requirement is high and the inheritance cannot be used, you can
Horizontal cutting, that is, bridging mode.
The above simple example shows how it works.
Obviously, it has the same capabilities as the template method, but does not use inheritance.
Public class payment {
Private double amount;
Public double getamount (){
Return amount;
}
Public void setamount (double value ){
Amount = value;
}
Private implementor IMP;
Public void seibd (implementor s ){
IMP = s;
}
Public String gosale (){
String x = "unchanged process 1 ";
X + = imp. Action (); // variable process
X + = Amount + ", querying inventory status"; // attributes and unchanged process 2
Return X;
}
}
Interface implementor {
Public String action ();
}
Class cashpayment implements implementor {
Public String action (){
Return "cash payment ";
}
}
Call:
Public class test {
Public static void main (string [] ARGs ){
Payment o = new payment ();
O. seibd (New cashpayment ());
O. setamount (555 );
System. Out. println (O. gosale ());
}
}
Assuming that the system has been put into operation, the user puts forward new requirements and requires credit card payment and cheque payment.
Why?
Public class creditpayment implements implementor {
Public String action (){
Return "pay by credit card, contact the payment institution ";
}
}
Class checkpayment implements implementor {
Public String action (){
Return "pay by cheque, contact Finance Department ";
}
}
Call:
Public class test {
Public static void main (string [] ARGs ){
Payment o = new payment ();
O. seibd (New cashpayment ());
O. setamount (555 );
System. Out. println (O. gosale ());
O. seibd (New creditpayment ());
O. setamount (555 );
System. Out. println (O. gosale ());
O. seibd (New checkpayment ());
O. setamount (555 );
System. Out. println (O. gosale ());
}
}
This reduces system coupling. During system upgrade, the original code does not need to be changed.