成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

十種 JavaScript 設計模式

開發 前端
設計模式是針對常見軟件問題的高級面向對象解決方案。模式是關于對象的可重用設計和交互。在討論復雜的設計解決方案時,每個模式都有一個名稱并成為詞匯表的一部分。

介紹

設計模式是針對常見軟件問題的高級面向對象解決方案。模式是關于對象的可重用設計和交互。在討論復雜的設計解決方案時,每個模式都有一個名稱并成為詞匯表的一部分。

在本教程中,我為每個 GoF 模式提供了 JavaScript 示例。大多數情況下,它們遵循原始圖案設計的結構和意圖。這些示例演示了每種模式背后的原則,但并未針對 JavaScript 進行優化。

01.Abstract Factory 

Abstract Factory創建由共同主題相關的對象。在面向對象編程中,工廠是創建其他對象的對象。抽象工廠抽象出新創建的對象共享的主題。

圖片

function Employee(name) {
    this.name = name;


    this.say = function () {
        console.log("I am employee " + name);
    };
}


function EmployeeFactory() {


    this.create = function (name) {
        return new Employee(name);
    };
}


function Vendor(name) {
    this.name = name;


    this.say = function () {
        console.log("I am vendor " + name);
    };
}


function VendorFactory() {


    this.create = function (name) {
        return new Vendor(name);
    };
}


function run() {
    var persons = [];
    var employeeFactory = new EmployeeFactory();
    var vendorFactory = new VendorFactory();


    persons.push(employeeFactory.create("Joan DiSilva"));
    persons.push(employeeFactory.create("Tim O'Neill"));
    persons.push(vendorFactory.create("Gerald Watson"));
    persons.push(vendorFactory.create("Nicole McNight"));


    for (var i = 0, len = persons.length; i < len; i++) {
        persons[i].say();
    }
}

02.Builder 

Builder 模式允許客戶端僅通過指定類型和內容來構建復雜對象,細節完全對客戶隱藏。

圖片

function Shop() {
    this.construct = function (builder) {
        builder.step1();
        builder.step2();
        return builder.get();
    }
}


function CarBuilder() {
    this.car = null;


    this.step1 = function () {
        this.car = new Car();
    };


    this.step2 = function () {
        this.car.addParts();
    };


    this.get = function () {
        return this.car;
    };
}


function TruckBuilder() {
    this.truck = null;


    this.step1 = function () {
        this.truck = new Truck();
    };


    this.step2 = function () {
        this.truck.addParts();
    };


    this.get = function () {
        return this.truck;
    };
}


function Car() {
    this.doors = 0;


    this.addParts = function () {
        this.doors = 4;
    };


    this.say = function () {
        console.log("I am a " + this.doors + "-door car");
    };
}


function Truck() {
    this.doors = 0;


    this.addParts = function () {
        this.doors = 2;
    };


    this.say = function () {
        console.log("I am a " + this.doors + "-door truck");
    };
}


function run() {
    var shop = new Shop();
    var carBuilder = new CarBuilder();
    var truckBuilder = new TruckBuilder();
    var car = shop.construct(carBuilder);
    var truck = shop.construct(truckBuilder);


    car.say();
    truck.say();
}

03、Factory Method 

Factory Method 按照客戶的指示創建新對象。在 JavaScript 中創建對象的一種方法是使用 new 運算符調用構造函數。 

然而,在某些情況下,客戶端不知道或不應知道要實例化多個候選對象中的哪一個。 

Factory Method 允許客戶端委托對象創建,同時仍然保留對要實例化的類型的控制。

圖片

var Factory = function () {
    this.createEmployee = function (type) {
        var employee;


        if (type === "fulltime") {
            employee = new FullTime();
        } else if (type === "parttime") {
            employee = new PartTime();
        } else if (type === "temporary") {
            employee = new Temporary();
        } else if (type === "contractor") {
            employee = new Contractor();
        }


        employee.type = type;


        employee.say = function () {
            console.log(this.type + ": rate " + this.hourly + "/hour");
        }


        return employee;
    }
}


var FullTime = function () {
    this.hourly = "$12";
};


var PartTime = function () {
    this.hourly = "$11";
};


var Temporary = function () {
    this.hourly = "$10";
};


var Contractor = function () {
    this.hourly = "$15";
};


function run() {


    var employees = [];
    var factory = new Factory();


    employees.push(factory.createEmployee("fulltime"));
    employees.push(factory.createEmployee("parttime"));
    employees.push(factory.createEmployee("temporary"));
    employees.push(factory.createEmployee("contractor"));


    for (var i = 0, len = employees.length; i < len; i++) {
        employees[i].say();
    }
}

04、Adapter

Adapter模式將一個接口(對象的屬性和方法)轉換為另一個接口。Adapter允許編程組件協同工作,否則由于接口不匹配而無法協同工作。適配器(Adapter)模式也稱為包裝器模式。

圖片

// old interface


function Shipping() {
    this.request = function (zipStart, zipEnd, weight) {
        // ...
        return "$49.75";
    }
}


// new interface


function AdvancedShipping() {
    this.login = function (credentials) { /* ... */ };
    this.setStart = function (start) { /* ... */ };
    this.setDestination = function (destination) { /* ... */ };
    this.calculate = function (weight) { return "$39.50"; };
}


// adapter interface


function ShippingAdapter(credentials) {
    var shipping = new AdvancedShipping();


    shipping.login(credentials);


    return {
        request: function (zipStart, zipEnd, weight) {
            shipping.setStart(zipStart);
            shipping.setDestination(zipEnd);
            return shipping.calculate(weight);
        }
    };
}


function run() {


    var shipping = new Shipping();
    var credentials = { token: "30a8-6ee1" };
    var adapter = new ShippingAdapter(credentials);


    // original shipping object and interface


    var cost = shipping.request("78701", "10010", "2 lbs");
    console.log("Old cost: " + cost);


    // new shipping object with adapted interface


    cost = adapter.request("78701", "10010", "2 lbs");


    console.log("New cost: " + cost);
}

05、Decorator

Decorator模式動態地擴展(裝飾)對象的行為。在運行時添加新行為的能力是由 Decorator 對象實現的,它“將自身包裝”在原始對象周圍。多個裝飾器可以向原始對象添加或覆蓋功能。

圖片

var User = function (name) {
    this.name = name;


    this.say = function () {
        console.log("User: " + this.name);
    };
}


var DecoratedUser = function (user, street, city) {
    this.user = user;
    this.name = user.name;  // ensures interface stays the same
    this.street = street;
    this.city = city;


    this.say = function () {
        console.log("Decorated User: " + this.name + ", " +
            this.street + ", " + this.city);
    };
}


function run() {


    var user = new User("Kelly");
    user.say();


    var decorated = new DecoratedUser(user, "Broadway", "New York");
    decorated.say();
}

06、Facade

Facade 模式提供了一個接口,使客戶免受一個或多個子系統中復雜功能的影響。這是一個看似微不足道但功能強大且極其有用的簡單模式。它通常出現在圍繞多層架構構建的系統中。

圖片

var Mortgage = function (name) {
    this.name = name;
}


Mortgage.prototype = {


    applyFor: function (amount) {
        // access multiple subsystems...
        var result = "approved";
        if (!new Bank().verify(this.name, amount)) {
            result = "denied";
        } else if (!new Credit().get(this.name)) {
            result = "denied";
        } else if (!new Background().check(this.name)) {
            result = "denied";
        }
        return this.name + " has been " + result +
            " for a " + amount + " mortgage";
    }
}


var Bank = function () {
    this.verify = function (name, amount) {
        // complex logic ...
        return true;
    }
}


var Credit = function () {
    this.get = function (name) {
        // complex logic ...
        return true;
    }
}


var Background = function () {
    this.check = function (name) {
        // complex logic ...
        return true;
    }
}


function run() {
    var mortgage = new Mortgage("Joan Templeton");
    var result = mortgage.applyFor("$100,000");


    console.log(result);
}

07、Proxy

代理模式為另一個對象提供代理或占位符對象,并控制對另一個對象的訪問。

圖片

function GeoCoder() {


    this.getLatLng = function (address) {


        if (address === "Amsterdam") {
            return "52.3700° N, 4.8900° E";
        } else if (address === "London") {
            return "51.5171° N, 0.1062° W";
        } else if (address === "Paris") {
            return "48.8742° N, 2.3470° E";
        } else if (address === "Berlin") {
            return "52.5233° N, 13.4127° E";
        } else {
            return "";
        }
    };
}


function GeoProxy() {
    var geocoder = new GeoCoder();
    var geocache = {};


    return {
        getLatLng: function (address) {
            if (!geocache[address]) {
                geocache[address] = geocoder.getLatLng(address);
            }
            console.log(address + ": " + geocache[address]);
            return geocache[address];
        },
        getCount: function () {
            var count = 0;
            for (var code in geocache) { count++; }
            return count;
        }
    };
};


function run() {


    var geo = new GeoProxy();


    // geolocation requests


    geo.getLatLng("Paris");
    geo.getLatLng("London");
    geo.getLatLng("London");
    geo.getLatLng("London");
    geo.getLatLng("London");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("London");
    geo.getLatLng("London");


    console.log("\nCache size: " + geo.getCount());


}

08、Mediator

Mediator模式通過封裝這些對象的交互方式來提供對一組對象的集中管理權。此模型對于需要管理復雜條件的場景很有用,在這種情況下,每個對象都知道組中任何其他對象的任何狀態更改。

圖片

var Participant = function (name) {
    this.name = name;
    this.chatroom = null;
};


Participant.prototype = {
    send: function (message, to) {
        this.chatroom.send(message, this, to);
    },
    receive: function (message, from) {
        console.log(from.name + " to " + this.name + ": " + message);
    }
};


var Chatroom = function () {
    var participants = {};


    return {


        register: function (participant) {
            participants[participant.name] = participant;
            participant.chatroom = this;
        },


        send: function (message, from, to) {
            if (to) {                      // single message
                to.receive(message, from);
            } else {                       // broadcast message
                for (key in participants) {
                    if (participants[key] !== from) {
                        participants[key].receive(message, from);
                    }
                }
            }
        }
    };
};


function run() {


    var yoko = new Participant("Yoko");
    var john = new Participant("John");
    var paul = new Participant("Paul");
    var ringo = new Participant("Ringo");


    var chatroom = new Chatroom();
    chatroom.register(yoko);
    chatroom.register(john);
    chatroom.register(paul);
    chatroom.register(ringo);


    yoko.send("All you need is love.");
    yoko.send("I love you John.");
    john.send("Hey, no need to broadcast", yoko);
    paul.send("Ha, I heard that!");
    ringo.send("Paul, what do you think?", paul);
}

09、Observer

Observer模式提供了一種訂閱模型,其中對象訂閱一個事件并在事件發生時得到通知。這種模式是事件驅動編程的基石,包括 JavaScript。Observer模式促進了良好的面向對象設計并促進了松散耦合。

圖片

function Click() {
    this.handlers = [];  // observers
}


Click.prototype = {


    subscribe: function (fn) {
        this.handlers.push(fn);
    },


    unsubscribe: function (fn) {
        this.handlers = this.handlers.filter(
            function (item) {
                if (item !== fn) {
                    return item;
                }
            }
        );
    },


    fire: function (o, thisObj) {
        var scope = thisObj || window;
        this.handlers.forEach(function (item) {
            item.call(scope, o);
        });
    }
}


function run() {


    var clickHandler = function (item) {
        console.log("fired: " + item);
    };


    var click = new Click();


    click.subscribe(clickHandler);
    click.fire('event #1');
    click.unsubscribe(clickHandler);
    click.fire('event #2');
    click.subscribe(clickHandler);
    click.fire('event #3');
}

10、Visitor

Visitor模式定義了對對象集合的新操作,而不更改對象本身。新邏輯駐留在一個名為 Visitor 的單獨對象中。

圖片

var Employee = function (name, salary, vacation) {
    var self = this;


    this.accept = function (visitor) {
        visitor.visit(self);
    };


    this.getName = function () {
        return name;
    };


    this.getSalary = function () {
        return salary;
    };


    this.setSalary = function (sal) {
        salary = sal;
    };


    this.getVacation = function () {
        return vacation;
    };


    this.setVacation = function (vac) {
        vacation = vac;
    };
};


var ExtraSalary = function () {
    this.visit = function (emp) {
        emp.setSalary(emp.getSalary() * 1.1);
    };
};


var ExtraVacation = function () {
    this.visit = function (emp) {
        emp.setVacation(emp.getVacation() + 2);
    };
};


function run() {


    var employees = [
        new Employee("John", 10000, 10),
        new Employee("Mary", 20000, 21),
        new Employee("Boss", 250000, 51)
    ];


    var visitorSalary = new ExtraSalary();
    var visitorVacation = new ExtraVacation();


    for (var i = 0, len = employees.length; i < len; i++) {
        var emp = employees[i];


        emp.accept(visitorSalary);
        emp.accept(visitorVacation);
        console.log(emp.getName() + ": $" + emp.getSalary() +
            " and " + emp.getVacation() + " vacation days");
    }
}

結論

當我們結束我們的 JavaScript 設計模式之旅時,很明顯這些強大的工具在制作可維護、可擴展和高效的代碼方面發揮著至關重要的作用。

通過理解和實施這些模式,您不僅會提升您的編程技能,還會為您自己和您的團隊成員創造更愉快的開發體驗。

請記住,設計模式不是一種放之四海而皆準的解決方案。分析項目的獨特需求和約束以確定哪些模式將帶來最大價值至關重要。

不斷學習和試驗不同的設計模式將使您能夠做出明智的決策并為您的項目選擇最佳方法。

將設計模式整合到您的工作流中可能需要投入時間和精力,但從長遠來看,這是值得的。

當您掌握編寫優雅、模塊化和高效的 JavaScript 代碼的藝術時,您會發現您的應用程序變得更加健壯,您的調試過程更易于管理,并且您的整體開發體驗更加愉快。

因此,繼續探索 JavaScript 設計模式的世界,并希望您的代碼更易于維護、可擴展和高效。

責任編輯:華軒 來源: web前端開發
相關推薦

2025-02-10 08:30:00

JavaScrip開發設計模式

2024-09-03 10:40:38

2025-06-16 08:22:23

2024-01-22 08:15:42

API協議設計

2023-06-18 12:21:42

分布式系統模式架構設計

2017-12-11 16:25:25

2024-09-02 10:07:52

2024-03-26 13:35:19

模型架構框架

2016-03-18 07:21:56

網站體驗設計錯誤

2024-11-13 13:20:44

2010-09-07 13:12:17

2024-01-02 11:38:41

體驗交互設計

2021-02-19 14:07:03

JavaScript編程開發

2019-08-15 14:11:31

LVS負載均衡調度算法

2010-07-16 16:45:56

職場培訓

2010-08-30 16:18:05

2020-08-13 07:00:00

工具技術管理

2018-09-25 23:21:13

2024-08-22 08:54:40

2010-09-13 17:17:04

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 黄篇网址 | 国产不卡一区在线观看 | 久久精品国产99国产精品 | 日韩久久久久久久久久久 | 高清av在线| 激情av在线 | 欧美成人一区二区 | 欧美中文一区 | 欧美xxxx性| 精品国产乱码久久久久久88av | 男人av的天堂 | 亚洲欧美日韩国产综合 | 久久久精品一区 | 国产欧美视频一区 | 欧美2区| 欧美一区二区三区视频 | 精品亚洲一区二区 | 成人精品一区二区三区中文字幕 | 男女网站免费观看 | 在线激情视频 | 日韩高清成人 | 欧美成人免费 | 欧美日韩中文字幕在线 | 日韩中文字幕一区二区 | 成人免费一区二区三区视频网站 | 国产综合第一页 | 中文字幕在线不卡播放 | 精品视频久久久久久 | 欧美另类视频 | 午夜精品久久久久久久久久久久 | 一级黄a视频 | 久久精品视频网站 | 日韩中文字幕免费在线 | 亚洲精品日韩在线观看 | 91电影在线播放 | 麻豆av一区二区三区久久 | 中文在线一区二区 | 日韩综合网 | 91免费视频 | 亚洲福利一区 | 国产精品久久久久久吹潮 |