Decorative design mode: Decorator pattern, also known as decorator mode. The feature is that you can dynamically add new functionality to the object without changing the class, dynamically extending it at run time. The main implementation is to implement dynamic add functionality by wrapping it into another object and adding new functionality. In other words, the original object is wrapped in another class.
When implemented, you need to be aware that both the decorator and the real object use the same interface, which allows the client object to interact with the same interface when it is used.
Applicable occasions:
When you need to extend the functionality of a class and dynamically assign objects to new features.
You need to dynamically add new functionality to an object, and you need to dynamically undo these features.
When you need to add some basic functionality, the permutations combine to produce a lot of functionality.
Advantages:
Although direct inheritance can also implement the decorative mode function, the adornment mode provides more flexibility than the direct inheritance method. and can produce different results according to the different permutations and combinations.
Disadvantages:
is more complex than normal inheritance.
Generates too many classes, and if overused, increases the complexity of the project.
The UML diagram is as follows:
Here's the code:
public class Test
{
public static void Main (String args[])
{
Component com=new Component ("Sam");
Decortora a=new Decortora ();
Decortorb b=new Decortorb ();
A.add (COM);
B.add (COM);
A.show ();
System.out.println ();
B.show ();
}
}
Class Component
{
String name;
Component (String name)
{
This.name=name;
}
void Show ()
{
SYSTEM.OUT.PRINTLN (name);
}
}
Class Decortorbase
{
Component com;
void Show ()
{
System.out.println ("Decortor");
Com.show ();
}
}
Class Decortora extends Decortorbase
{
void Add (Component c)
{
Com=c;
}
void Show ()
{
System.out.println ("A");
Super.show ();
}
}
Class Decortorb extends Decortorbase
{
void Add (Component c)
{
Com=c;
}
void Show ()
{
System.out.println ("B");
Super.show ();
}
}
The results of the operation are as follows:
Contact me:[email protected]
2016-7-31
19:44
Decorative design pattern