According to the NetEase Cloud Classroom Java Development Course Study
-Decoration Mode Introduction
Decorative mode dynamically attaches more responsibility to an object in a manner that is transparent to the customer. In other words, customers do not feel that the object is different before and after decoration. The decorative pattern can extend the function of an object without using the creation of more subclasses (this pattern is used in Java for IO streams).
-Roles in decorative mode:
1. Abstract component (componet) role: gives an abstract interface to standardize the preparation of objects that receive additional responsibility.
plainly define an interface
2. Specific component (concretecomponent) Role: Define a class that will receive additional responsibilities
instantiation of this interface
3. Decorative (decorator) Role: Holds an instance of a (Component) object and defines an interface that is consistent with the abstract component.
invokes an interface, instantiating an object
4. Specific decoration (concretedecorator) role: Responsible for adding additional functionality to component objects.
inherit decorator to add functionality to the object. Here's a simple code demo
Defines an interface in which there is a method.
Package com.test.decorate;
Public interface Component {public
void Dothinga ();
}
2. Instantiate this interface
Package com.test.decorate;
public class Concreatecomponent implements Component {
@Override public
void Dothinga () {
System.out.println ("Do A Thing!");
}
3. Create a decorative class:
Package com.test.decorate;
public class Decorator implements Component {
private Component Component = null;
Public decorator (Component Component) {
this.component = Component;
}
@Override public
void Dothinga () {
component.dothinga ();
}
}
Add additional functionality
Package com.test.decorate;
public class Concreatedecorator extends decorator {public
concreatedecorator (Component Component) {
super ( component);
TODO auto-generated constructor stub
}
@Override public
void Dothinga () {
super.dothinga ();
DOTHINGB ();
}
private void Dothingb () {
System.out.println ("Do B Thing");
}
Add one more feature:
package com.test.decorate; public class ConCreateDecorator1 extends decorator {public ConCreateDecorator1 (Component Component) {super (
component);
TODO auto-generated Constructor stub} @Override public void Dothinga () {Super.dothinga ();
DOTHINGC ();
private void Dothingc () {System.out.println ("do C thing"); }
}