装饰器模式代码举例(java语言版)

前言:为了解决子类膨胀问题,把被装饰的以关联的方式放入装饰类里面,装饰类添加新的功能,如果需要再扩展新功能的时候,那么可以考虑直接继承装饰类。下面是一个画圆的例子(其实ServletRequest、HttpServletRequest、ServletRequestWrapper以及HttpServletRequestWrapper就是用的装饰器模式)

JAVA语言版装饰器模式

创建接口:

public interface Shape {
    void draw();
}

接口的实现类:

public class Rectangle implements Shape{
    @Override
    public void draw() {
        System.out.println("形状:矩形");
    }
}

public class Circle implements Shape{
    @Override
    public void draw() {
        System.out.println("形状:圆形");
    }
}

创建一个装饰器类的抽象类:

public abstract class ShapeDecorator implements Shape {
    protected Shape decoratorShape;

    public ShapeDecorator(Shape decoratorShape) {
        this.decoratorShape = decoratorShape;
    }

    @Override
    public void draw() {
        decoratorShape.draw();
    }
}

创建继承抽象类的非抽象类:

public class RedShapeDecorator extends ShapeDecorator {

    public RedShapeDecorator(Shape decoratorShape) {
        super(decoratorShape);
    }

    public void draw() {
        decoratorShape.draw();
        serRedBorder();

    }

    private void serRedBorder() {
        System.out.println("线的颜色:红色");
    }
}

创建DecoratorpatternDemo类用来演示装饰器模式:

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.draw();

        System.out.println("包装后的红色圆:");
        redCircle.draw();

        System.out.println("包装后的矩形:");
        redRectangle.draw();
    }
}

输出结果:

没有包装的圆:
形状:圆形
包装后的红色圆:
形状:圆形
线的颜色:红色
包装后的矩形:
形状:矩形
线的颜色:红色

猜你喜欢

转载自blog.csdn.net/qq_35386002/article/details/89471209