Decorative mode (Decorator)

Source: Internet
Author: User

Original: http://blog.csdn.net/zhangerqing/article/details/8239539

Decoration mode is to add some new functions to an object, and is dynamic, require decorative objects and decorated objects to implement the same interface, decorative objects hold the object of the decoration objects, the diagram is as follows:

The source class is a decorated class, and the decorator class is a decorative class that can dynamically add some functionality to the source class, with the following code:[Java]View plain copy public interface sourceable {public void method (); }[Java]View plain copy public class Source implements sourceable {@Override public void method () {Sys       Tem.out.println ("The original method!"); }   }[Java]  View Plain  copy public class decorator implements sourceable {          private Sourceable source;               public decorator (sourceable source) {            super ();            this.source = source;       }       @ override       public void method ()  {            system.out.println ("before decorator!");            source.method ();            system.out.println ("after decorator!");        }  }  

Test class: [Java] view plain copy public class Decoratortest {public static void main (string[] args) {           sourceable Source = new Source ();           sourceable obj = new Decorator (source);       Obj.method (); }   }

Output:

Before decorator!
The original method!
After decorator!

Application Scenarios for Adorner mode:

1, need to extend the functionality of a class.

2, dynamic for an object to add functionality, but also can be dynamically revoked. (Inheritance cannot do this, the inherited functionality is static and cannot be dynamically deleted.) )

Cons: Produce too many similar objects, not easy to debug.

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.