1.定义
动态的为对象添加一些额外的职责。单就增加功能来说,Decorator模式相比生成子类更为灵活。
2.使用场景
1、扩展一个类的功能。 2、动态增加功能,动态撤销。
例如:1、孙悟空有 72 变,当他变成"庙宇"后,他的根本还是一只猴子,但是他又有了庙宇的功能。
3.实现
/**
* 抽象组件(Component):可以是一个接口或者抽象类,充当被装饰类的原始对象,规定了被装饰对象的行为
* @author Administrator
*
*/
public interface Shape {
void draw();
}
/**
* 具体组件(ConcreteComponent):实现/继承Component的一个具体对象,即被装饰对象
* @author Administrator
*
*/
public class Circle implements Shape{
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("draw a circle");
}
}
/**
* 具体组件(ConcreteComponent):实现/继承Component的一个具体对象,即被装饰对象
* @author Administrator
*
*/
public class Rectangle implements Shape{
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("draw a rectangle");
}
}
/**
* 抽象装饰器(Decorator):通用的装饰ConcreteComponent的装饰器,其内部必然有一个属性指向Component,其实现一般是一个抽象类,主要为了让其子类按照其构造形式传入一个Component,
* 这是强制的通用行为。如果系统中装饰逻辑单一,则并不需要实现许多装饰器,可以直接省略该类,而直接实现一个具体装饰器即可
* @author Administrator
*
*/
public class ShapeDecorator implements Shape{
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
// TODO Auto-generated constructor stub
this.decoratedShape = decoratedShape;
}
@Override
public void draw() {
// TODO Auto-generated method stub
decoratedShape.draw();
}
}
/**
* 具体装饰器(ConcreteDecorator):Decorator的具体实现类,理论上,每个ConcreteDecorator都扩展了Component对象的一种功能
* @author Administrator
*
*/
public class RedShapeDecorator extends ShapeDecorator{
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
// TODO Auto-generated constructor stub
}
@Override
public void draw() {
// TODO Auto-generated method stub
super.draw();
setBorderColor(decoratedShape);
}
private void setBorderColor(Shape shape) {
System.out.println("With Red Border");
}
}
/**
* 测试类
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
Shape circle = new Circle();
circle.draw();
System.out.println("=============================");
ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
redCircle.draw();
System.out.println("=============================");
ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
redRectangle.draw();
}
}
运行结果
4.总结
装饰器类是对功能的增强,这也是装饰器模式应用场景的一个重要特点。
优点: 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点: 多层装饰比较复杂。