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