1. Decorate and have a common super class with the decorated person
2. The purpose of inheritance is to achieve type inheritance (thus realizing the extension of behavior)
3. Behavior extension (final purpose)
scenario: have the main type or business Logic, but with personalized processing scenarios
Example : Different coffees have different prices, but the price calculation model is the same The
code is as follows
/** * Super coffee * @author john * */ public abstract class Coffe { //price public abstract double cost(); } /** * Mocha coffee (decorated) * @author john * */ public class MokaCoffe extends Coffe { @Override public double cost() { // TODO auto-generated method stub return 2.0; } } /** * Nes coffee decorator * @author john * */ public class NesCoffe extends Coffe { @Override public double cost() { // TODO auto-generated method stub return 3.0; } } /** * Seasoning component (decorator component) * @author john * */ public abstract class CompentDecorate extends Coffe { @Override public abstract double cost(); } /** * Cream Dressing (for garnish) * @author john * */ public class MilkCondiment extends CompentDecorate { private Coffe coffe; public MilkCondiment(){ } public MilkCondiment(Coffe coffe){ this.coffe = coffe; } @Override public double cost() { // TODO auto-generated method stub return 0.2+coffe.cost(); } } /** * sugar seasoning (decorator) * @author john * */ public class sugarCondiment extends CompentDecorate { private Coffe coffe; public sugarCondiment(){ } public sugarCondiment(Coffe coffe){ this.coffe = coffe; } @Override public double cost() { // TODO auto-generated method stub return 0.1+coffe.cost(); } } public class Test { public static void main(String[] args){ //coffee 2.0 Coffe mokaCoffe = new MokaCoffe(); //extended behavior (price) //Coffee with milk 0.2 mokaCoffe = new MilkCondiment(mokaCoffe); System.out.println(mokaCoffe.cost()); // sweetened coffee 0.1 mokaCoffe = new sugarCondiment(mokaCoffe); System.out.println(mokaCoffe.cost()); } }
//Run result:
[img]
[/img]