1. 程式人生 > 其它 >java 裝飾器模式實現程式碼

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();
    }
}