什么是装饰器模式(Decorator)?

95 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

  1. 意图
    动态的为一个对象添加一些额外的职责。
  2. 类图
    在这里插入图片描述
  3. 实例
interface Shape {
        /**
         * 画
         */
        void draw ();
    }

    static class Circle implements Shape {
        @Override
        public void draw() {
            System.out.println("draw circle");
        }
    }

    static class Rectangle implements Shape {
        @Override
        public void draw() {
            System.out.println("draw rectangle");
        }
    }

    static class Decorator implements Shape {
        protected Shape shape;
        public Decorator (Shape shape) {
            this.shape = shape;
        }

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

    static class RedDecorator extends Decorator {
        public RedDecorator (Shape shape) {
            super(shape);
        }

        @Override
        public void draw() {
            content();
            shape.draw();
            border();
        }

        public void border () {
            System.out.println("red border");
        }

        public void content () {
            System.out.println("content");
        }
    }
  1. 测试
public static void main(String[] args) {
        Decorator redCircle = new RedDecorator(new Circle());

        Decorator redRectangle = new RedDecorator(new Rectangle());

        redCircle.draw();
        System.out.println();
        redRectangle.draw();
    }

运行结果:

content
draw circle
red border

content
draw rectangle
red border

想看更多吗?请访问:设计模式