JavaScript設計模式 - Strategy

專職寫了幾個月,雖然開始有些凌亂,現在基本上也認同:JavaScript是一門優雅的語言。

從設計模式的角度,應該能更好地理解JavaScript的不同,改善既有代碼。

那就先從比較常用的Strategy模式開始。

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.

(From https://sourcemaking.com/design_patterns/strategy)

JavaScript Example

  • 定義一組Strategy, 確保可互相替換
  • 通過替換Strategy改變程序的行爲
        const HelloWork = function (travelStrategy) {
            this.travelStrategy = travelStrategy;

            this.setTravelStrategy = function (travelStrategy) {
                this.travelStrategy = travelStrategy;
            };
            this.travel = function () {
                let strategy = this.travelStrategy();
                console.log(`${strategy}上班`);
            };
        };

        const walking = () => {
            return '我窮我走路';
        };
        const bike = () => {
            return '我環保我開新能源機動車(小電瓶)';
        };
        const subway = () => {
            return '我土豪我搭幾個億的地鐵';
        };

        const hw = new HelloWork(walking);
        hw.travel();

        hw.setTravelStrategy(bike);
        hw.travel();

        hw.setTravelStrategy(subway);
        hw.travel();

Output:

我窮我走路上班
我環保我開新能源機動車(小電瓶)上班
我土豪我搭幾個億的地鐵上班

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章