Sometimes, it is easiest to implement a basic core code that is quickly encapsulated with dedicated performance by peripheral code.
The superclass is used, but the superclass uses inheritance to improve coupling. In this case, you can also use
Decorator mode, which is a good way to replace inheritance with combinations.
1. Intention
In fact, the above intention can be attributed to "dynamically adding functions without changing the object ",
In other words, we do not want to change the original class or create a subclass to add features. In this case,
You can use the decoration mode.
2. Structure
An important feature of the modifier structure is that it inherits from an abstract class, but it uses the aggregation of this abstract class.
(That is, decorative objects can contain abstract class objects). Proper design can achieve our purpose.
Suppose we have constructed a payment-based simple factory model system. Now you need to call the method in each class
In gosale (), in addition to the original functions, a dialog box is displayed to display the factory name.
To change the system, add a decoration class decorator in the module type of the factory class, and slightly rewrite one.
The code of the factory class.
// Decoration
Public class decorator extends payment {
Private string strname;
Public decorator (string strname ){
This. strname = strname;
}
Private payment PM;
Public void setpm (Payment value ){
PM = value;
}
Public String action (){
// A prompt box is displayed before the original code is executed.
System. Out. println (strname );
Return pm. Action ();
}
}
Factory:
// This is a factory class
Public class factory {
Public static payment paymentfactory (string paymentname ){
Payment MDB = NULL;
If (paymentname. Equals ("cash "))
MDB = new cashpayment ();
Else if (paymentname. Equals ("Credit Card "))
MDB = new creditpayment ();
Else if (paymentname. Equals ("check "))
MDB = new checkpayment ();
// Return MDB;
Decorator M = new decorator (paymentname );
M. setpm (MDB );
Return m;
}
}
It can be said that this changes the performance without the user's knowledge or the original class.