I. Definition
Decorative mode (decorator pattern) is a more common pattern, defined as follows: Dynamically adding some additional responsibilities to an object. Decorative mode is more flexible than generating subclasses in terms of adding functionality.
The general class diagram of the decorative pattern is shown below.
In the class diagram, there are four roles to note:
1. Component Abstract Component
Component is an interface, or abstract class, that defines our very core object, which is the original object.
2, Concretecomponent specific components
Concretecomponent is the core, the most primitive, the most basic interface or the implementation of the abstract class, you have to decorate it.
3, Decorator decorative role
is generally an abstract class, what to do with it. Implement interface or abstract method, it may not have an abstract method, in its properties must have a private variable point to component abstract artifacts.
4, the specific decorative role
Concretedecoratora and Concretedecoratorb are two specific decorative classes, and you have to decorate your core, the most primitive, the most basic things into something else.
Second, the sample code is as follows:
1. Abstract component
Public abstract class Component {
//abstract method public
abstract void operate ();
}
2. Concrete Components
public class Concretecomconent extends Component {
//specific implementation
@Override public
Void Operate () {
System.out.println ("Do something ...");
}
3, the abstract decorates the person
Public abstract class Decorator extends Component {
private Component Component = null;
Public decorator (Component Component) {
this.component = Component;
}
@Override public
Void Operate () {
this.component.operate ();
}
}
4, the specific decoration class
public class Decoratora extends decorator {public
Decoratora (Component Component) {
super (Component);
}
public void Method1 () {
System.out.println ("method1 decoration");
}
public void Operate () {
this.method1 ();
Super.operate ();
}
public class Decoratorb extends decorator {public
Decoratorb (Component Component) {
super (Component);
} Public
void Method2 () {
System.out.println ("method2 decoration");
}
public void Operate () {
this.method2 ();
Super.operate ();
}
5, Scene class
public class Client {public
static void Main (string[] args) {
Component cc = new Concretecomconent ();
CC = new Decoratora (cc);
CC = new Decoratorb (cc);
Cc.operate ();
}