Decorator Mode notes

Source: Internet
Author: User

Concept Understanding : Decorator Mode (Decorator), is to decorate something, so that he added something than the original, such as makeup, the original single eyelid, to paste a false double (here may not be very appropriate ha, MO Strange), has the eyelid effect. Back to Java, it's about strengthening the functionality of a class and extending its functionality.

Schema Origin : We want to enhance a class, because it is not recommended to modify the source code directly, the decorator mode is generated.

principle : There is a class implementation of a interface, we want to strengthen this class, so write a new class also implement this interface and the original class interface to add a reference to the new class, in the new class to rewrite the method to be strengthened and call in the method to strengthen the method, thereby implementing the enhancement.

Example: A dog can only run, I want to let it run out and fly up! (In the "Run" method to add "Fly" the additional business)

Interface animal{

public void run ();

}

Class Dog implements animal{

@override

public void Run () {

System.out.println ("The Dog is Running");

}
}

Decorated by

Class Flydog implements animal{

References to interfaces of the original class

Animal Animal = null;

Construction method

Public Flydog (Animal Animal) {

This.animal = animal;

}

Rewrite the method to be strengthened

@override

public void Run () {

Animal.run ();//The original function

System.out.println ("It's getting faster, and finally it flew up");

}

}

At this point, if you new is dog, then it will only run. If you're new to Flydog, then it's going to fly when it's finished! We successfully added "Fly" to "run".

Decorator Mode notes

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.