Decorator mode for design mode

Source: Internet
Author: User

Brief introduction:

Decorator decorator, is to dynamically add some additional responsibilities to an object, the object and the adorner object needs to implement the same interface, the adorner in the method implementation of the method to invoke the target object to implement and add additional operations.

Usage scenarios:

Refine the complex functionality, scatter it into different adorners, and then dynamically combine the features as needed.

Class Diagram:

Example code:

The interface that the adorner is required to implement with the target object:

 Public Interface Component {    publicvoid  operation ();}

The Real implementation class:

 Public class Implements Component {    @Override    publicvoid  operation () {        System.out.println ( "I am doing the real thing");}    }

Adorner A:

 Public class Implements Component {    private  Component Component;      Public Decoratora (Component Component) {        Super();         this. Component = component;    }    @Override    publicvoid  operation () {        component.operation ();        System.out.println ("I am doing the extra thing A");     }

Adorner B:

 Public class Implements Component {    private  Component Component;      Public Decoratorb (Component Component) {        Super();         this. Component = component;    }    @Override    publicvoid  operation () {        component.operation ();        System.out.println ("I am doing the extra thing B");     }

Client:

 Public Static void Main (string[] args) {        new decoratorb ( new Decoratora (new  Concretecomponent ()));        Component.operation ();    }

Operation Result:

I am doing the real thing
I am doing the extra thing A
I am doing the extra thing B

Decorator mode for design mode

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.