Decorator Pattern)
Finally, I knocked on one side of the decorator model that I learned for many days. Here I will record it for future reference.
The book defines the Paster mode as follows: The Paster mode dynamically attaches the responsibility to the object. To expand the function, the Paster provides a more flexible alternative than inheritance.
In my own understanding, it is a group that inherits the combination of the same abstract class, and then one uses the other as a member variable to wrap it up, that is, to decorate it, abstract classes contain common abstract methods. All methods are encapsulated in their own methods. The encapsulated methods are called first, and their attributes are added to them.
The decorator and the decorator must both come from the same abstract class !!!
I just knocked on the example program. If it is used in the project, I will add it. I will use a drink example to introduce it:
Abstract class of beverage, providing abstract cost () methods.
public abstract class Beverage {String description;public String getDescription() {return description;}public abstract double cost();}
A mixed coffee:
public class HousBlend extends Beverage{public HousBlend() {description = "HousBlend Cofee";}@Overridepublic double cost() {return 10;}}
Abstract class of coffee seasoning:
public abstract class CondimentDecorator extends Beverage{public abstract String getDescription();}
The specific seasoning will be wrapped in the modifier as a member variable in the constructor:
public class Mocha extends CondimentDecorator {Beverage beverage;public Mocha(Beverage beverage) {this.beverage = beverage;}@Overridepublic String getDescription() {return beverage.getDescription() + "Mocha";}@Overridepublic double cost() {return beverage.cost() + 1;}}
Test example:
Public class Test {public static void main (String args []) {Beverage coffee = new HousBlend (); System. out. println (coffee. getDescription () + "," + coffee. cost () + ""); coffee = new Mocha (coffee); System. out. println (coffee. getDescription () + "," + coffee. cost () + ""); coffee = new Mocha (coffee); System. out. println (coffee. getDescription () + "," + coffee. cost () + "Yuan ");}}
Result:
HousBlend coprocessor, 10.0 yuan
HousBlend CofeeMochaMocha, $12.0
HousBlend CofeeMochaMochaMocha, $13.0
Because it has not been used yet, I don't have a deep understanding of it. But I know this mode and will accept it more quickly when I use this mode.