A preliminary study of the Java design pattern in decorator mode

Source: Internet
Author: User

Definition: Dynamically add some extra responsibilities to an object, just like painting on a wall. Using the decorator mode, it is more flexible to achieve the expansion of the function by the method of generating subclasses.
Design: Often can use inheritance to achieve the expansion of the function, if these need to expand the variety of functions, it is bound to generate a lot of subclasses, increase the complexity of the system, while the use of inheritance to achieve functional expansion, we must be able to foresee these expansion functions, these functions are compile-time determined, is static.

Important: The decorator has a common superclass with the decorator, and the purpose of the inheritance is to inherit the type, not the behavior


In fact, Java's I/O API is implemented using decorator.

Definition is adorner public interface Human {public void wearclothes ();  public void Walktowhere ();        }//define adorner public abstract class Decorator implements Human {private Human Human;      Public Decorator (Human Human) {This.human = Human;      } public void Wearclothes () {human.wearclothes ();      } public void Walktowhere () {human.walktowhere (); }}//The following defines three kinds of decorations, this is the first, the second third function is refined in turn, that is, the adorner's function is more and more public class Decorator_zero extends Decorator {public Decorator      _zero (Human Human) {super (Human); } public void GoHome () {System.out.println ("into the house.      "); } public void Findmap () {System.out.println ("Den looking for map.      "); } @Override public void Wearclothes () {//TODO auto-generated method stub super.wearclothes          ();      GoHome (); } @Override public void Walktowhere () {//TODO auto-generated method stub Super.walKtowhere ();      Findmap (); }} public class Decorator_first extends Decorator {public Decorator_first (Human Human) {super (Human      ); } public void Goclothespress () {System.out.println ("Go to the closet and look for it.      "); } public void Findplaceonmap () {System.out.println ("Look up on map.      "); } @Override public void Wearclothes () {//TODO auto-generated method stub super.wearclothes          ();      Goclothespress (); } @Override public void Walktowhere () {//TODO auto-generated method stub Super.walktowhere          ();      Findplaceonmap ();      }} public class Decorator_two extends Decorator {public decorator_two (Human Human) {super (Human); } public void Findclothes () {System.out.println ("found a d&g.      "); } public void Findthetarget () {System.out.println ("Find the mysterious garden and castle on the map.      "); } @Override public void WEarclothes () {//TODO auto-generated Method Stub super.wearclothes ();      Findclothes (); } @Override public void Walktowhere () {//TODO auto-generated method stub Super.walktowhere          ();      Findthetarget ();           }}//definition is decorator, the adorner initial state some own decoration public class person implements Human {@Override public void wearclothes () { TODO auto-generated Method Stub System.out.println ("What to wear.      "); } @Override public void Walktowhere () {//TODO auto-generated method stub System.out.printl N ("Where to go?")      "); }}//Test class, you'll see how similar I/O operations to Java are, public class Test {public static void main (string[] args) {Human PE          Rson = new Person ();          Decorator Decorator = new Decorator_two (new Decorator_first (new Decorator_zero (person));          Decorator.wearclothes ();      Decorator.walktowhere ();   }  }

Operation Result:

The fact is to go into the house to find clothes, and then find a map such a process, through the decorator's three-storey decoration, the details become rich.

Key points:
1, Decorator abstract class, holding the human interface, the method is all delegated to the interface call, the purpose is to give the interface implementation of the class is a subclass to call.
2, decorator the subclass of abstract class (specific decorator), there is a construction method called super (human), this sentence embodies that the abstract class relies on the implementation of the subclass is abstract dependent on the principle of implementation. Because the structure inside the parameters are human interface, as long as the human implementation class can be passed in, that is, show Decorator dt = new Decorator_second (New Decorator_first Zero (human)); The appearance of this structure. So when calling Dt.wearclothes ();d t.walktowhere (), and because each of the specific decorator classes first calls the Super.wearclothes and Super.walktowhere () methods, And the super has been passed by the construction and pointed to a specific decorator class (this can be changed according to the order), then the call is a decorative class method, and then call its own decorative method, that is, a decorative, chain-like behavior similar to filtering.
3, the specific decoration of the class, you can define the initial state or the initial self-decoration, the following decorative behavior on the basis of a step-by-step embellishment, decoration.
4, the design principle of the decorator mode is: open to the expansion, the modification is closed, this sentence reflected in my if I want to expand the behavior of the decorator class, without modifying the adorner abstract class, simply inherit the adorner abstract class, to achieve additional decoration or call behavior can be decorated by the packaging. Therefore: the extension manifests in the inheritance, the modification manifests in the subclass, but is not the concrete abstract class, this fully manifests the dependence inversion principle, this is oneself understands the decorator pattern.


Said not clear, some imaginative achievement here inexpressible feeling, see several times code, and then knock it out to run, basically understand.


The following example also helps to understand the process and role of decoration

Now you need a hamburger, the main body is chicken leg fort, you can choose to add lettuce, sauce, chili and so many other ingredients, in this case you can use the decorator mode.


Hamburg base class (adorned, equivalent to the human above)

Package decorator;        Public abstract class Humburger {                protected  String name;                Public String GetName () {            return name;        }                public abstract double GetPrice ();        }    

Chicken Leg Fort Class (the initial state of the decorator, some of its own simple decoration, equivalent to the person above)

Package decorator;        public class Chickenburger extends Humburger {public                Chickenburger () {            name = "Chicken Leg fort";        }            @Override public        Double GetPrice () {            return;}        }    

The base class of the ingredients (decorator, used for multi-layered decoration of Hamburg, each layer of decoration added some ingredients, equivalent to the above decorator)

Package decorator;        Public abstract class condiment extends Humburger {public                abstract String getName ();            

Lettuce (the first layer of the decorator, equivalent to the Decorator_zero above)

Package decorator;        public class Lettuce extends condiment {                Humburger humburger;                Public lettuce (Humburger humburger) {            This.humburger = Humburger;        }            @Override public        String getName () {            return humburger.getname () + "add lettuce";        }            @Override public        Double GetPrice () {            return humburger.getprice () +1.5;        }        }    

Pepper (The second layer of the decorator, equivalent to the decorator_first above)

Package decorator;        public class Chilli extends condiment {                Humburger humburger;                Public chilli (Humburger humburger) {            This.humburger = Humburger;                    }            @Override public        String getName () {            return humburger.getname () + "add Pepper";        }            @Override public        Double GetPrice () {            return humburger.getprice ();  Pepper is free Oh        }        }    

Test class

Package decorator;        public class Test {            /**       * @param args       *        /public static void main (string[] args) {            Humburger Humburger = new Chickenburger ();            System.out.println (Humburger.getname () + "  Price:" +humburger.getprice ());            Lettuce lettuce = new lettuce (humburger);            System.out.println (Lettuce.getname () + "  Price:" +lettuce.getprice ());            chilli chilli = new chilli (humburger);            System.out.println (Chilli.getname () + "  Price:" +chilli.getprice ());            Chilli chilli2 = new chilli (lettuce);            System.out.println (Chilli2.getname () + "  Price:" +chilli2.getprice ());        }        }    

Output

Chicken Leg Fort  Price: 10.0    Chicken leg Fort plus lettuce  Price: 11.5    Chicken leg Fort plus Chili  Price: 10.0    Chicken leg fort with lettuce and chili  Price: 11.5  

  

A preliminary study of the Java design pattern in decorator mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.