java 装饰器模式实现代码

时间:2022-01-10 04:56:57

java 装饰器模式实现代码

上图展示的是io流中的一个装饰者模式的代码结构

1、实现装饰器模式

汽车厂生产汽车实例,4S店可以喷漆换颜色。

1.1、公共接口

public interface Car {
void skin();
}

1.2、接口实现

实现汽车出厂色

public class Corolla implements Car {

    @Override
public void skin() {
System.out.println("超级无敌灰色");
}
}

1.3、装饰器

装饰构件可以通过装饰器完成装饰

public abstract class FourS implements Car {

    private Car car;

    public FourS(Car car) {
this.car = car;
} @Override
public void skin() {
car.skin();
}
}

1.4、装饰构件

喷枪红

public class RedSprayPaint extends FourS {

    public RedSprayPaint(Car car) {
super(car);
} @Override
public void skin() {
super.skin();
System.out.println("花2000块钱喷红色的漆");
}
}

喷枪白

public class WhiteSprayPaint extends FourS {

    public WhiteSprayPaint(Car car) {
super(car);
} @Override
public void skin() {
super.skin();
System.out.println("花1000块钱喷白色的漆");
}
}

1.5、测试装饰器

public class Main {
public static void main(String[] args) throws IOException {
System.out.println("====================出厂颜色====================");
Car corolla = new Corolla();
corolla.skin();
System.out.println("====================换颜色====================");
RedSprayPaint red = new RedSprayPaint(new WhiteSprayPaint(corolla));
red.skin();
}
}