装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。装饰模式的类图如下:
在装饰模式中的角色有:
(1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
(2)具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。
(3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
(4)具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。
具体代码实现:
//创建一个Shape接口。
public interface Shape {
public void draw();
}
//创建实现接口的实体类。
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape:"+"Circle");
}
}
//创建实现接口的实体类。
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape:"+"Rectangle");
}
}
//创建实现了 Shape 接口的抽象装饰类。
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape)
{
this.decoratedShape = decoratedShape;
}
public void draw()
{
decoratedShape.draw();
}
}
//创建扩展了 ShapeDecorator 类的实体装饰类。
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw()
{
decoratedShape.draw();
setRedBorder(decoratedShape);
}
public void setRedBorder(Shape decoratedShape) {
System.out.println("Border color: Red");
}
}
//使用 RedShapeDecorator 来装饰 Shape 对象。
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape cirle = new Circle();
Shape redcircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
cirle.draw();
System.out.println("\nCirclr with red border");
redcircle.draw();
System.out.println("\nRectangle of red border");
redRectangle.draw();
}
}
输出结果:
Circle with normal border
Shape:Circle
Circlr with red border
Shape:Circle
Border color: Red
Rectangle of red border
Shape:Rectangle
Border color: Red
使用场景:对象由主体+许多可选的部件或者功能构成,使用继承或者接口会产生很多类,且很难扩展。