装饰器模式
标签:设计模式

装饰器模式(Decorator)

装饰模式又叫做包装模式。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。

1. 装饰模式中的角色和及其职责

1.1 抽象组件角色

一个抽象接口,是**被装饰类(RunCar)装饰类(CarDecorator)**的父接口

Car

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/07/31
 */
public interface Car {
    public void show();
}

1.2 具体组件角色

是抽象组件的实现类

RunCar

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/07/31
 */
public class RunCar implements Car {
    @Override
    public void show() {
        this.run();
    }

    public void run() {
        System.out.println("Run");
    }
}

1.3 抽象装饰角色

包含一个组件的引用,并定义了与抽象组件一致的接口

CarDecorator

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/07/31
 */
public abstract class CarDecorator implements Car{
    private Car car;

    public CarDecorator(Car car) {
        this.car=car;
    }

    @Override
    public void show() {
        car.show();
    }
}

1.4 具体装饰角色

是抽象装饰角色的实现类,负责具体的装饰。

FlyCarDecorator

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/07/31
 */
public class FlyCarDecorator extends CarDecorator{

    public FlyCarDecorator(Car car) {
        super(car);
    }

    @Override
    public void show() {
        super.show();
        this.fly();
    }

    public void fly(){
        System.out.println("Fly");
    }
}

SwimCarDecorator

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/07/31
 */
public class SwimCarDecorator extends CarDecorator{

    public SwimCarDecorator(Car car) {
        super(car);
    }

    @Override
    public void show() {
        super.show();
        this.swim();
    }

    public void swim(){
        System.out.println("Swim");
    }
}


Main

package com.liuyao;

public class Main {

    public static void main(String[] args) {
        Car runCar=new RunCar();
        runCar.show();
        System.out.println("===============");
        Car flyCar= new FlyCarDecorator(runCar);
        flyCar.show();
        System.out.println("===============");
        Car swimCar = new SwimCarDecorator(flyCar);
        swimCar.show();
    }
}

//Run
//===============
//Run
//Fly
//===============
//Run
//Fly
//Swim

2. 应用场景

在Java的IO流里面使用的很多。

  • 2 min read

CONTRIBUTORS


  • 2 min read