The decoration mode, also known as the wrapper mode, is an alternative to the inheritance relationship by extending the object functions in a transparent way to the client. Transparent to the client means that the interface remains unchanged.
Problem:
During the OO design and development process, we often encounter the following situation: we need to add new responsibilities for the classes we have designed, we usually define a new class to inherit the custom class. because the combination is better than inheritance (high complexity, deep inheritance depth, and other reasons, see <Design Pattern Analysis> p39). Today we will introduce the decorative pattern of the application combination.
Class diagram:
Source code:
Package com. designpatterns. decorator;
/**
* Abstract interface, which standardizes the objects preparing to receive additional responsibilities
* @ Author Suki
*/
Public interface component {
Void operation ();
}
/**
* Receive additional responsibilities. This type of classes can have multiple corresponding to only one decorator class.
* @ Author Suki
*/
Public class concretecomponent implements component {
Public concretecomponent (){}
Public void operation ()
{
System. Out. println ("concretecomponent. Operation ()");
}
}
/**
* The decoration role holds an instance of a component object and defines an interface consistent with the abstract Component Interface.
* @ Author Suki
*/
Public class decorator implements component {
Private component;
Public decorator (){}
Public decorator (Component component)
{
This. Component = component;
}
Public void operation (){
Component. Operation ();
}
}
/**
* Add additional responsibilities
* @ Author Suki
*/
Public class concretedecorator extends decorator {
Public concretedecorator (){}
Public concretedecorator (Component component)
{
Super (component );
}
Public void operation ()
{
Super. Operation ();
This. addedoperation ();
}
Public void addedoperation ()
{
System. Out. println ("concretedecorator. addedoperation ()");
}
}
/**
* Client class
* @ Author Suki
*/
Public class client {
Public static void main (string [] ARGs ){
Component = new concretecomponent ();
Decorator = new concretedecorator (component );
// The client remains unchanged, but the responsibility has been added
Decorator. Operation ();
}
}
Summary:
In the [gof95] Book: The decoration mode dynamically attaches more functions to an object. For function expansion, the decoration mode provides a flexible alternative to inheritance.
The example of the 451 page invoice system in this book is good!