concept
Decorator Pattern (Decorator Pattern), also known as Wrapper Pattern (Wrapper Pattern) refers to the addition of functions to objects without changing the original objects. This type of design pattern belongs to the structural pattern, which serves as a wrapper for existing classes.
The decorator pattern mainly includes four roles:
- Abstract component (Component) : It can be an interface or abstract class, which acts as the original object of the decorated class and specifies the behavior of the decorated object
- Concrete component (ConcreteComponent) : a concrete object that implements or inherits Component, which is the decorated object
- Abstract decorator (Decorator) : A general decorator that decorates ConcreteComponent. There must be a property in it pointing to the Component abstract component
- Concrete decorator (ConcreteDecorator) : The concrete realization class of Decorator
achieve
Let's take the example of pie with eggs and ham:
1. Create abstract components
public abstract class Pancake {
abstract String name();
}
2. Create specific components
public class BasePancake extends Pancake {
@Override
String name() {
return "素煎饼";
}
}
3. Create an abstract decorator
public abstract class PancakeDecorator extends Pancake{
private Pancake pancake;
public PancakeDecorator(Pancake pancake) {
this.pancake = pancake;
}
String name(){
return this.pancake.name();
}
}
4. Create a concrete decorator
public class EggDecorator extends PancakeDecorator {
public EggDecorator(Pancake pancake) {
super(pancake);
}
String name(){
return super.name()+"+鸡蛋";
}
}
public class SausageDecorator extends PancakeDecorator {
public SausageDecorator(Pancake pancake) {
super(pancake);
}
String name(){
return super.name()+"+火腿肠";
}
}
5. Test
public class DecoratorTest {
public static void main(String[] args) {
Pancake pancake=new BasePancake();
//加鸡蛋
pancake=new EggDecorator(pancake);
//再加鸡蛋
pancake=new EggDecorator(pancake);
//再加香肠
pancake=new SausageDecorator(pancake);
System.out.println(pancake.name());
}
}
operation result:
scenes to be used
- Extend the functionality of a class
- Dynamic increase function, dynamic cancellation
Use in source code
In the Mybatis source code we mentioned earlier, there is a cache interface Cache:
it can be understood from the name, for example, FifoCache is a first-in first-out cache, BlockingCache is a blocking cache, etc., all adopt the decorator mode
The difference between decorator mode and proxy mode
- The decorator emphasizes the expansion of its own functions, and the agent mode emphasizes the control of the agent process
to sum up
advantage
- Different effects can be achieved by using different decorations and the permutation and combination of these decorations
- Dynamically extend functions to an object without changing the original object
Disadvantage
- It will be more complicated when multi-layer decoration