What
Decorator: dynamically add some additional responsibilities to an object. The decorator mode is more flexible than the subclass generation function.
Why
The decorator mode is suitable for dynamically adding and deleting roles to objects. For example, in the QQ Show, we can select our own image and dynamically add clothes and decorations to make our image feel tall. Decorator applies to the following situations:
1. Add roles to a single object dynamically and transparently without affecting other objects.
2. Deal with scenarios where responsibilities can be revoked.
3. When the subclass method cannot be used for expansion.
How
In the following scenarios, faceq can be used to create a cartoon image. If this function is implemented, you can use the decorator mode.
Basic dress up class
Public class face {private string name; public face () {} public face (string name) {This. name = Name;} public void show () {system. out. println ("start to dress up face:" + name );}}
Face dressing
public class FaceFeature extends Face{ private Face face; public FaceFeature(){ } public void decorator(Face face){ this.face=face; } @Override public void show() { face.show(); }}
Round face
Public class roundfacefeature extends facefeature {@ override public void show () {system. Out. println ("add face"); Super. Show ();}}
Square face
Public class squarefacefeature extends facefeature {@ override public void show () {system. Out. println ("add face"); Super. Show ();}}
Mouth dress
public class Mouth extends Face { private Face face; public Mouth(){ } public void decorator(Face face){ this.face=face; } @Override public void show() { face.show(); }}
Smiling mouth
Public class smilemouth extends mouth {@ override public void show () {system. Out. println ("add smile"); Super. Show ();}}
Shut up
Public class closedmouth extends mouth {@ override public void show () {system. Out. println ("add and shut up. "); Super. Show ();}}
Call the above dress-up class
public static void main(String[] args){ Face face=new Face("test"); RoundFaceFeature roundFaceFeature=new RoundFaceFeature(); SmileMouth smileMouth=new SmileMouth(); roundFaceFeature.decorator(face); smileMouth.decorator(roundFaceFeature); smileMouth.show(); }
The UML diagram of the above Code is as follows:
Discuss
In the preceding example, the face class serves as both a responsibility interface and a specific dress object. facefeature and mouth are two dress classes. In Java JDK, there is also a typical decorator mode. in Java Io classes, decorator modes are used in outputstream, inputstream, reader, and writer, if you have time, analyze it carefully.
Design Pattern learning-decorator