Today we talk about the design pattern of the decorative design pattern, this in my door IO flow has been used, first of all, look at the definition of decorative design patterns
Defined:
dynamically add some extra functionality to an object, and in terms of new features, the adornment mode is more flexible than the generation of subclasses.summed up the decorative design pattern 2 functions:
2 Effects1: Add functionality to the object,2: Add features are dynamic
the adorner pattern has the following characteristics:
it must have an ornamental object. It must have the same interface as the object being decorated. It can add extra functionality to the object being decorated. In a nutshell: Maintain interfaces, enhance performance
now it's more intuitive to implement the following codeFor example, mobile phone can only call, then I would like to call before the ring bell, the phone hangs can continue to listen to the song//function of the telephone,
Public interface Phone {public void Call ();}
the implementation class for a specific phone
public class iphone implements phone {public iphone () {super ();} @Overridepublic void Call () {System.out.println ("calling");}}
//Decorate the functions of the extension, but to keep the phone function
Public abstract class Phonedecorator implements phone {private phone phone;public phonedecorator (phone phone) {super (); th Is.phone = phone;} @Overridepublic void Call () { phone.call ();}}
The realization of the specific decoration class, and add the function
public class Ringdecorator extends Phonedecorator {public ringdecorator (phone phone) {super (phone);} @Overridepublic void Call () {System.out.println ("I want my phone to listen to ringtones"); Super.call ();}}
Music specific decorative class implementation and add the ability to play music
public class Musicdecorate extends Phonedecorator {public musicdecorate (phone phone) {super (phone);} @Overridepublic void Call () {Super.call (); System.out.println ("Mobile phone can listen to music");}}
Test class
public class Decoratortest {public static void main (string[] args) {Phone phone = new IPhone ();p hone.call (); System.out.println ("*************************"); Phonedecorator PD = new Ringdecorator (phone);pd. Call (); System.out.println ("*************************");PD = new Musicdecorate (phone);pd. Call (); System.out.println ("*************************");//Now it's the ring before the call. After you hang up the phone, you can listen because PD = new Musicdecorate (New Ringdecorator Phone));pd. Call ();}}
Results:
Call
*************************
I want my cell phone to listen to ringtones.
Call
*************************
Call
Phone can listen to music
*************************
I want my cell phone to listen to ringtones.
Call
Phone can listen to music
Java Decorative design pattern