设计模式-装饰模式(Decorator)

 

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

角色和职责:

1.抽象组件(Component)-Car:

   为统一接口,也是装饰类和被装饰类的统一接口

2.具体组件(concrete Component)-RunCar:

    抽象组件的具体实现

3.抽象装饰角色(Decorator)-Decorator:

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

4.具体装饰(concrete Decorator)-FlyCarDecorator、SwimCarDecorator:

   负责具体的装饰

 

UML图:

具体代码如下:

/**
 * 汽车基类
 */
public interface Car {
    void run();
}
/**
 * 会跑的汽车
 */
public class RunCar implements Car{
    @Override
    public void run() {
        System.out.println("汽车会跑");
    }
}
/**
 * 装饰基类,实现和Car相同的方法
 */
public abstract class Decorator implements Car{
    protected Car car;
    public Decorator(Car car){
        this.car =car;
    }
}
/**
 * 会飞的汽车
 */
public class FlyCarDecorator extends Decorator{
    public FlyCarDecorator(Car car) {
        super(car);
    }

    @Override
    public void run() {
        this.car.run();
        this.run1();
    }

    private void run1(){
        System.out.println("还会飞");
    }
}
/**
 * 会游的汽车
 */
public class SwimCarDecorator extends Decorator{
    public SwimCarDecorator(Car car) {
        super(car);
    }

    @Override
    public void run() {
        this.car.run();
        this.run1();
    }

    private void run1(){
        System.out.println("还会游");
    }
}
public class Main {
    public static void main(String[] args) {
        Car runCar = new RunCar();//会跑的汽车
        runCar.run();
        System.out.println("----------------------------");

        Car flyRunCar = new FlyCarDecorator(runCar);//装饰会跑的汽车,变成会跑又会飞的汽车
        flyRunCar.run();
        System.out.println("----------------------");

        Car swimFlyRunCar = new SwimCarDecorator(flyRunCar);//装饰会跑会飞的汽车,变成会跑会飞会游的汽车
        swimFlyRunCar.run();
    }
}

结果:

汽车会跑
----------------------------
汽车会跑
还会飞
----------------------
汽车会跑
还会飞
还会游

 

具体源码:https://github.com/qjm201000/design_pattern_decorator.git

 

posted @ 2018-12-03 22:55  qjm201000  阅读(133)  评论(0编辑  收藏  举报