In the Java programming language, the idea of nesting many design patterns, such as the buffer flow in the IO stream, is used to the decorator design pattern described below.
Example code:
* Abstract Component role: Defines an abstract interface to standardize the classes that prepare additional functionality * @author Admin * */public interface Drink { //Adorner's base class public String description ();p Ubli c int Price ();}
/** * Concrete Component role: the class that will be attached to the function, implementing the abstract Component role Interface * @author Admin * */public class Soyabeanmilk implements drink{ //Decorator specific class public Str ing description () {return "Soy milk";} public int Price () {return 2;}}
/** * Abstract Decorator role: an interface that holds a reference to a specific component role (decorator) and implements an abstract component role * @author Admin * */public class Decorator implements drink{ //Decorator base class P Rivate Drink drink;public Decorator (Drink Drink) {this.drink = Drink;} Public String Description () {return drink.description ();} public int Price () {return Drink.price ();}}
/** * Specific Decorative roles: implements the abstract decorator role, which is responsible for adding additional functionality to the specific artifacts. * @author Admin * */public class Sugar extends decorator{ //Decorator specific class public Sugar (Drink Drink) {super (Drink);} Public String Description () {return super.description () + "Sugar";} public int Price () {return super.price () +1;}} /** * Specific Decorative roles: implements the abstract decorator role, which is responsible for adding additional functionality to the specific artifacts. * @author Admin * */public class Blackbean extends Decorator{public Blackbean (Drink Drink) {super (Drink);} Public String Description () {return super.description () + "Black Bean";} public int Price () {return super.price () +3;}}
/** * Test Class (Test decorator mode) * @author Admin * */public class Test {public static void main (string[] args) {Drink Drink = new Soyabe Anmilk (); The decorator (soy milk) System.out.println (drink.description () + "Cost:" +drink.price ());D rink Drink1 = new Sugar (drink); Sugar is the decorator class, used to decorate soy milk System.out.println (drink1.description () + "Cost:" +drink1.price ());D rink drink2 = new Blackbean (Drink); Use black beans to decorate soy milk System.out.println (drink2.description () + "Cost:" +drink2.price ());D rink Drink3 = new Blackbean (DRINK1); Use black beans to decorate sugar soy milk System.out.println (drink3.description () + "Cost:" +drink3.price ());}
Experimental results:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java design Pattern-Decorator mode