Java Decoration Design Mode
Today I will talk about the decorative design pattern in the design pattern. This is already used in the I/O Stream of my portal. First, let's look at the definition of the decorative design pattern.
Definition:
Dynamically add some additional features to an object. In terms of new features, the decoration mode is more flexible than the subclass generation. In summary, the decoration design mode has two functions:
2 roles 1: Add a function for the object, 2: The add function is dynamic
The decorator mode has the following features:
It must have a decoration object. It must have the same interface as the decorated object. It can add additional functions to the decorated object. In one sentence, we will summarize: maintain interfaces and enhance performance.
Now we can use the code to make the following more intuitive: for example, if a mobile phone can only make a call, I want to hear the ring tones before making a call. After the phone hangs up, I can continue to listen to songs/calls,
public interface Phone { public void call();}Implementation class of a specific phone
Public class IPhone implements Phone {public IPhone () {super () ;}@ Overridepublic void call () {System. out. println ("call ");}}// The extension of the decoration class, but the call function must be maintained.
public abstract class PhoneDecorator implements Phone {private Phone phone;public PhoneDecorator(Phone phone) {super();this.phone = phone;}@Overridepublic void call() { phone.call();}}// Implement the specific decoration class of the ring tones and add functions
Public class RingDecorator extends PhoneDecorator {public RingDecorator (Phone phone) {super (phone) ;}@ Overridepublic void call () {System. out. println ("I want a cell phone to listen to the ring tones"); super. call ();}}// Implement the music decoration class and add the function of playing music
Public class MusicDecorate extends PhoneDecorator {public MusicDecorate (Phone phone) {super (phone) ;}@ Overridepublic void call () {super. call (); System. out. println ("You can listen to music on your phone ");}}Test class
Public class DecoratorTest {public static void main (String [] args) {Phone phone = new IPhone (); phone. call (); System. out. println ("************************"); PhoneDecorator pd = new RingDecorator (phone ); pd. call (); System. out. println ("************************"); pd = new MusicDecorate (phone ); pd. call (); System. out. println ("*************************"); // now, after you call a phone call, you can hear the call. Because pd = new MusicDecorate (new RingDecorator (phone); pd. call ();}}Result:
Call
*************************
I want a cell phone to listen to the ring tones.
Call
*************************
Call
Music listening on mobile phones
*************************
I want a cell phone to listen to the ring tones.
Call
Music listening on mobile phones