十、装饰器模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时不改变其结构。
通过创建一个装饰类,包装原有的类,保持原有类的方法签名不变,提供额外功能。
介绍
动态的给一个对象添加一些额外的新功能,相比生成子类更为灵活。
相比使用继承,装饰模式避免了由继承而引入的静态特征和子类臃肿的现象。
- 优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代方式,可以动态扩展一个现有类的功能。
- 缺点:多层装饰比较复杂。
实现
创建一个Shape
接口和实现该接口的实体类,然后欻功能键一个实现Shape
接口的装饰类ShapeDecorator
并把Shape
对象作为它的实例变量。RedShapeDecorator
实现ShapeDecorator
的实体类,完成功能扩展。
- 创建接口
Shape.java
public interface Shape {
void draw();
}
- 创建接口实现类
Rectangle.java
public class Rectangle implements Shape {
@override
public void draw(){
System.out.println("Shape : Rectangle");
}
}
Circle.java
public class Circle implements Shape {
@override
public void draw(){
System.out.println("Shape : Circle");
}
}
- 创建抽象的装饰类
ShapeDecorator.java
public abstract class ShapeDecorator implements Shape{
protected Shape decorateShape;
public ShapeDecorator(Shape decorateShape){
this.decorateShape = decorateShape;
}
public void draw(){
decorateShape.draw();
}
}
- 创建实体的装饰类
RedShapeDecorator.java
public class RedShapeDecorator extends ShapeDecorator{
public RedShapeDecorator(Shape decoratedShape){
super(decoratedShape);
}
@override
public void draw(){
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color : Red");
}
}
- 演示
DecoratorPatternDemo.java
public class DecoratorPatternDemo {
public static void main(String[] args){
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\n Circle of red border");
redCircle.draw();
System.out.println("\n Rectangle of red border");
redRectangle.draw();
}
}
- 输出
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red