Decorative design pattern
Overview of Decorative Design Patterns
Decorating mode is the use of an instance of a subclass of a decorated class, where the client gives an instance of the subclass to the adornment class. is an alternative to inheritance. Decorative mode can be any combination.
Advantages
Using the adornment mode, you can provide more flexible extension objects than inheritance, it can dynamically add the function of objects, and can be arbitrarily combined with these features
Disadvantages
Because they can be assembled at will, there may be some unreasonable logic.
Decorative design pattern Diagram:
Example 1:
Public interface Phone {
Public abstract void call ();
}
Public class IPhone implementsphone {
@Override
Public void call () {
System. out. println (" phone can call ");
}
}
Public Abstract class Phonedecorate implements Phone {
Private PhoneP;
Public Phonedecorate (Phone p) {
this. p = p;
}
@Override
Public void call () {
this. P. Call ();
}
}
Public class Musicphonedecorate extends phonedecorate {
Public Musicphonedecorate (Phone p) {
Super (p);
}
@Override
Public void call () {
Super. Call ();
System. out. println (" mobile phone can listen to music ");
}
}
Public class Ringphonedecorate extends phonedecorate {
Public Ringphonedecorate (PHONEP) {
Super (p);
}
@Override
Public void call () {
System. out. println (" phone can listen to ringtones ");
Super. Call ();
}
}
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.util.Scanner;
public class Phonedemo {
publicstatic void Main (string[] args) {
PHONEP = new IPhone ();
P.call ();
System.out.println ("------------");
Need: I want to listen to the ringtone before answering the phone
PHONEDECORATEPD = new Ringphonedecorate (p);
Pd.call ();
System.out.println ("------------");
Need: I want to listen to music after answering the phone
pd= new Musicphonedecorate (p);
Pd.call ();
System.out.println ("------------");
Need: I want the phone to listen to the ring ring before the answer, listen to music
Provide the decoration class, listen to the ring tone before the call, listen to music after the call
pd= New Ringphonedecorate (Newmusicphonedecorate (p));
PD. Call();
System.out.println ("----------");
Think about the use of our IO stream
InputStream is = system.in;
InputStreamReader ISR = new InputStreamReader (IS);
BufferedReader br = new BufferedReader (ISR);
BUFFEREDREADERBR = New BufferedReader (Newinputstreamreader (system.in));
BUFFEREDWRITERBW = new BufferedWriter ((New OutputStreamWriter (
(System.out)));
SCANNERSC = new Scanner (system.in);
}
}
Operation Result:
The phone can call.
------------
Phone can listen to ringtones
The phone can call.
------------
The phone can call.
Phone can listen to music
------------
Phone can listen to ringtones
The phone can call.
Phone can listen to music
----------
Design pattern: Decorative design pattern