Discover the design pattern of learning more and more so that they learn something too little, should touch something more, go out and walk.
Decoration Mode concept:
Dynamically add some extra responsibilities to an object, and the decorative pattern is more flexible than generating subclasses for added functionality (big talk design mode)
The ability to dynamically extend an object without having to change the original class file and use inheritance. It is by creating a wrapper object, that is, decorating to wrap the real object. (Baidu Encyclopedia)
UML diagram for Decorative mode
Code for decorating mode
package com.roc.decorate; /** * Fight decoration mode This learning decoration mode we will give a small bully hit a child, suddenly met the child's mother saw, it must not be said in hitting her son Ah, can only say with her son play a play, the child is afraid of small gangsters certainly I'll say yes, mom, we're playing, but the real thing is playing. * @author */ public abstract class fight { /** * punch */ public abstract void boxing (); }
Package com.roc.decorate; Public class extends fight{ @Override publicvoid boxing () { System.out.println (" Punch ");} }
Packagecom.roc.decorate; Public classDscribefightextendstruefight{/*** You can't say it's a direct call, to describe, to describe*/ Private voidsay () {System.out.println ("Auntie, I'm having a game with xiaoming."); } Public voidBoxing () { This. Say (); Super. boxing (); System.out.println ("Great place to stay"); }}
Package com.roc.decorate; /** @author*/Publicclass Client {public staticvoid main (string[] args) { fight fight=new Dscribefight (); Fight.boxing (); }}
Understanding of decorative patterns
(1) The Decoration object and the real object have the same interface. This allows the client object to interact with the adornment object in the same way as the real object. (2) The Adornment object contains a reference to a real object (reference) (3) The Adornment object accepts all requests from the client. It forwards these requests to the real object. (4) Decorative objects can add additional functionality before or after forwarding these requests. This ensures that additional functionality can be added externally without modifying the structure of a given object at run time. In object-oriented design, the extension of functionality to a given class is usually achieved through inheritance.
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!
Decorative patterns of Java design patterns