Design Pattern learning-Decorator
The WhyDecorator 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. In the following scenario, How is another application popular recently. FaceQ can be used to create its own 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 Face dressing:" + name) ;}} Face dressing class 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 F AceFeature {@ 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 () ;}} 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 p Ublic class SmileMouth extends molic {@ Override public void show () {System. out. println ("add smile"); super. show () ;}} shut up the public class ClosedMouth extends Mouth {@ Override public void show () {System. out. println ("add to 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 ();}