设计模式之 - 装饰器

2021-01-13  本文已影响0人  Renew全栈工程师

装饰器模式,利于后面新功能增加或者删除,支持各种组合操作,这就是装饰器模式的强大

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Renew全栈工程师 - 设计模式之装饰器模式</title>
</head>
<body>

<script>
    class NormalReader {
        constructor(text) {
            this.text = text.split(/[\r\n]/g);
            this.index = 0;
        }

        readLine() {
            if (this.index >= this.text.size) return;

            return this.text[this.index++];
        }
    }

    class Decorator {
        constructor(reader) {
            this.reader = reader;
        }

        readLine() {
            return this.reader.readLine();
        }
    }

    class ColoredReader extends Decorator {
        readLine() {
            const str = super.readLine();

            if (!str) return;

            const s = document.createElement("span");

            s.style.color = "red";

            s.innerHTML = str;

            return s.outerHTML;
        }
    }

    class BoxedReader extends Decorator {
        readLine() {
            const str = super.readLine();

            if (!str) return;

            const s = document.createElement("div");

            s.style.width = "100px";

            s.style.background = "#000";

            s.style.marginTop = "100px";

            s.innerHTML = str;

            return s.outerHTML;
        }
    }

    const reader = new BoxedReader(new ColoredReader(new NormalReader("a\nb\nc")));

    let str;

    while ((str = reader.readLine())) {
        document.body.innerHTML+=str;
    }

</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读