Design mode [8] - Manual Geng taught me to write decorator mode

Decorator mode

I've learned several design patterns before. Continue today

Decorator mode is a structural mode, which is used to wrap and encapsulate the current class object. It is hoped that the function of the object can be expanded without modifying the current class object and class definition.

When calling, the decorated object is used instead of the original object., Provides additional functionality.

I wonder if you have seen the video of Geng's homemade piano kebab car[ https://www.bilibili.com/vide... ], it was originally a piano, but in order to play the piano and bake the string at the same time, it was transformed and decorated into a special piano, providing additional kebab function. Typical decorator mode

Objective: in order to flexibly expand the functions of class objects.

It mainly includes the following roles:

  • Abstract component: the abstraction of the decorated original class, which can be an abstract class or an interface.
  • Concrete component: concrete abstract class
  • Abstract decorator: General abstractor
  • Concrete Decorator: concrete implementation class of Decorator. Theoretically, each concrete Decorator extends a function of Component object.

Advantages and disadvantages

advantage:

  • Compared with class inheritance, wrapped objects are easier to expand and more flexible
  • Decoration class and decorated class are independent of each other, and the coupling degree is relatively low
  • Fully observe the opening and closing principle.

Disadvantages:

  • When the level of package object is deep, it is difficult to understand.

realization

First, free up an Instrument interface class Instrument:

public interface Instrument {
    void play();
}

Play two kinds of musical instruments, Piano and Guitar, and realize the musical instrument interface:

public class Piano implements Instrument{
    @Override
    public void play() {
        System.out.println("Play the piano by hand");
    }
}
public class Guitar implements Instrument{
    @Override
    public void play() {
        System.out.println("Play guitar by hand");
    }
}

Whether manual Geng wants to barbecue while playing the guitar, barbecue while playing the piano, or take a bath while playing the piano, no matter what needs, we abstract a decorator class and specialize in packaging and decoration of musical instruments.

public class InstrumentDecorator implements Instrument{
    protected Instrument instrument;

    public InstrumentDecorator(Instrument instrument) {
        this.instrument = instrument;
    }

    @Override
    public void play() {
        instrument.play();
    }
}

The above is an abstract decoration class. We have to do some practical actions to make a barbecue function.

public class BarbecueInstrumentDecorator extends InstrumentDecorator {
    public BarbecueInstrumentDecorator(Instrument instrument) {
        super(instrument);
    }

    @Override
    public void play() {
        instrument.play();
        barbecue();
    }

    public void barbecue(){
        System.out.println("Handmade Geng is barbecue");
    }
}

Test:

public class DecoratorDemo {
    public static void main(String[] args) {
        Instrument instrument = new Piano();
        instrument.play();
        System.out.println("----------------------------------------");
        InstrumentDecorator barbecuePiano = new BarbecueInstrumentDecorator(new Piano());
        barbecuePiano.play();
        System.out.println("----------------------------------------");
        InstrumentDecorator barbecueGuitar = new BarbecueInstrumentDecorator(new Guitar());
        barbecueGuitar.play();
    }
}

The test results are as follows. You can see that you can only do one thing when you don't decorate. The objects after decoration can play musical instruments or barbecue. You can't help but sigh: it turns out that Geng is a master of design mode:

Play the piano by hand
----------------------------------------
Play the piano by hand
 Handmade Geng is barbecue
----------------------------------------
Play guitar by hand
 Handmade Geng is barbecue

To summarize

Design pattern is not a silver bullet, but a good practice evolved in software engineering or programming. We can't design patterns for design patterns. Learning theory is just to use it better and know when to use it and when not to use it.

The decorator mode is designed to expand its functions without destroying the original structure. In fact, it is widely used in the Java IO source code, such as:

DataInputStream dis = new DataInputStream(
                    new BufferedInputStream(
                            new FileInputStream("test.txt")
                            )
                    );

First pass FileInputStream to BufferedInputStream to create a decoration object, then pass the decoration object to DataInputStream and decorate it again. Finally, FileInputStream is packaged as DataInputStream. Interested students can turn to the source code.

[about the author]:
Qin Huai, the official account of Qin Huai grocery store, is not in the right place for a long time.

Sword finger Offer all questions PDF

Open source programming notes

Keywords: Java Design Pattern

Added by anonymouse on Thu, 06 Jan 2022 04:05:26 +0200