A Preliminary Study on the JAVA design pattern-The annotator Pattern

Source: Internet
Author: User
Tags types of functions

This model takes a long time and is hard to understand at first.

Definition: dynamically add some additional responsibilities to an object, just like painting on the wall. Using the Decorator mode is more flexible than using the subclass method to Expand functions.
Original design intention: inheritance can usually be used to expand functions. If there are many types of functions to be extended, many sub-classes will be generated to increase the complexity of the system. At the same time, when using inheritance to implement function expansion, we must be able to foresee these extended functions, which are determined at compilation and static.

 

Key points:The decorator and the decorator share a super class. The purpose of inheritance is to inherit the type, not behavior.


  In fact, Java I/O APIs are implemented using Decorator.

 

// Define the public interface Human {public void wearClothes (); public void writable towhere () ;}// define the public abstract class Decorator implements Human {private Human human Human; public Decorator (Human human) {this. human = human;} public void wearClothes () {human. wearClothes ();} public void implements towhere () {human. define towhere () ;}/// the three decorations are defined below, which is the first and the second and third functions are refined in sequence. That is, more and more public class Decorator_zero extends Decorator {pub Lic Decorator_zero (Human human) {super (human);} public void goHome () {System. out. println ("enter the house .. ");} Public void findMap () {System. out. println (" .. ") ;}@ Overridepublic void wearClothes () {// TODO Auto-generated method stubsuper. wearClothes (); goHome () ;}@ Overridepublic void returns towhere () {// TODO Auto-generated method stubsuper. extends towhere (); findMap () ;}} public class Decorator_first extends Decorator {public Decorator_first (Human human) {super (human);} public void goClothespress () {System. out. println ("go to the closet to find it .. ");} Public void findPlaceOnMap () {System. out. println (" find it on Map .. ") ;}@ Overridepublic void wearClothes () {// TODO Auto-generated method stubsuper. wearClothes (); goClothespress () ;}@ Overridepublic void implements towhere () {// TODO Auto-generated method stubsuper. extends towhere (); findPlaceOnMap () ;}} public class Decorator_two extends Decorator {public Decorator_two (Human human) {super (human);} public void findClothes () {System. out. println ("Find a D & G .. ");} Public void findTheTarget () {System. out. println (" find the mysterious garden and Castle on Map .. ") ;}@ Overridepublic void wearClothes () {// TODO Auto-generated method stubsuper. wearClothes (); findClothes () ;}@ Overridepublic void implements towhere () {// TODO Auto-generated method stubsuper. inclutowhere (); findTheTarget () ;}// defines the decorator. The decorator's initial state is decorated with its own public class Person implements Human {@ Overridepublic void wearClothes () {// TODO Auto-generated method stubSystem. out. println ("what to wear .. ") ;}@ Overridepublic void returns towhere () {// TODO Auto-generated method stubSystem. out. println (" where to go .. ") ;}}// Test class. You can see how similar the I/O operation in java is to public class Test {public static void main (String [] args) {Human person = new Person (); Decorator decorator = new Decorator_two (new Decorator_first (new Decorator_zero (person); decorator. wearClothes (); decorator. optional towhere ();}}

Running result:

In fact, it is to go into the house to find clothes, and then look for a map. Through the three-layer Decoration of the modifier, the details are enriched.

Key points:
1. the Decorator abstract class holds the Human interface, and all methods are delegated to this interface for calling. The purpose is to hand over the implementation class of this interface, that is, the subclass, for calling.
2. Subclass of the Decorator abstract class (Specific modifier), which contains a constructor that calls super (human ), this statement reflects the principle that abstract classes depend on subclass implementation, that is, abstraction depends on implementation. Because the parameters in the constructor are all Human interfaces, the Decorator dt = new Decorator_second (new Decorator_first (new Decorator_zero (Human) is displayed as long as the human implementation class can be passed in ))); the structure. Therefore, when dt. wearClothes (); dt. when using towhere (), and because each specific modifier class, first calls super. wearClothes and super. when towhere () method, and the super has been passed by the constructor and points to a specific modifier class (this can be changed as needed), the method called is the decoration class method, then, you can call your own decoration method to demonstrate a decoration, chained behavior similar to filtering.
3. For the decoration class, you can define the initial state or the initial decoration of your own. The subsequent decoration behavior is based on this step and step by step.
4. the decorator mode is designed to be open to extensions and closed to modifications. This statement is reflected in the fact that if I want to expand the behavior of the decorator class, I do not need to modify the decorator abstract class, you only need to inherit the abstract class of the modifier to implement additional decoration or behavior to wrap the modifier. Therefore, extensions are embodied in inheritance and modification in subclasses, rather than concrete abstract classes. This fully reflects the Dependency inversion principle, which is the decorator mode that you understand.


I am not clear about it. Some of them are just plain-spoken. I read the code several times and click it to run it myself. I basically understood it.


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

Now you need a hamburger, mainly chicken leg fort. You can choose to add many other ingredients, such as lettuce, sauce, chilies, and so on. In this case, you can use the modifier mode.


Hamburg-based class (decorator, equivalent to the above Human)

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 their 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 10 ;}}

Base class of ingredients (the modifier is used to decorate the hamburger in multiple layers. Each layer adds some ingredients, which is equivalent to the Decorator above)

package decorator;    public abstract class Condiment extends Humburger {            public abstract String getName();    }  

 

Lettuce (the first layer of the modifier, 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 ;}}


Chilies (the second layer of the modifier, equivalent to decorator_first)

Package decorator; public class Chilli extends Condiment {Humburger humburger; public Chilli (Humburger humburger) {this. humburger = humburger;} @ Override public String getName () {return humburger. getName () + "add chilies" ;}@ Override public double getPrice () {return humburger. getPrice (); // The chilies are free of charge }}


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 chilies price: 10.0 chicken leg Fort plus lettuce plus chilies price: 11.5


 

Author: jason0539

Weibo: http://weibo.com/2553717707

Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)

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.