1.代理模式
var girl = function (name) {
this.name = name;
}
var boy = function (name, girl) {
this.name = name;
this.girl = girl;
this.sendGift = function (gift) {
console.log(this.name + " 送給 " + this.girl.name + " 的 " + gift);
}
}
var proxy = function (boy) {
this.boy = boy;
this.sendGift = function (gift) {
this.boy.sendGift(gift);
}
}
var girl1 = new girl("小蘇");
var boy1 = new boy("小任", girl1);
var biaobai = new proxy(boy1);
biaobai.sendGift("烏江榨菜");
2.單例模式:
2.1懶漢式
var singleton = (function () {
var instance;
return function getInstance() {
if (instance == null) {
instance = {
product: "單例-懶漢"
}
}
return instance;
}
})()
var product = singleton();
console.log(product);
2.2餓漢式
var singletonHungry = (function () {
var instance = { product: "單例-餓漢" };
return function () {
return instance;
}
})()
var product = singletonHungry();
console.log(product);
3.工廠模式:
var Factory = (function () {
var phone = function (name, version) {
this.name = name;
this.version = version;
}
phone.prototype.play = function () {
console.log(this.name + " " + this.version);
}
return function getInstance(name, version) {
return new phone(name, version);
}
})()
var myPhone = Factory("HUAWEI", "Mate30");
myPhone.play();
4.觀察者模式(ES5、ES6兩種寫法):
class Platform {
constructor() {
this.orders = [];
}
submit(order) {
this.orders.push(order);
}
notify(good) {
this.orders.forEach(item => {
item.callMe(good);
})
}
}
class customer {
constructor(name, good) {
this.name = name;
this.good = good;
}
callMe(good) {
if (good == this.good) {
console.log(this.name + " 的 " + this.good + " 做好了!!!");
}
}
}
var meituan = new Platform();
meituan.submit(new customer("蘇姐", "奶茶"));
meituan.submit(new customer("張三", "麻辣拌"));
meituan.notify("麻辣拌");
var DepartmentStore = (() => {
var goods = {};
function addOrder(order, declare) {
if (!goods[order]) {
goods[order] = [];
}
goods[order].push(declare);
}
function notify(order, ...args) {
for (let fn of goods[order]) {
fn(...args);
}
}
return {
addOrder,
notify
}
})()
var Person = function (name, requirement) {
var name = name;
var requirement = requirement;
return function callMe(good) {
if (good == requirement) {
console.log(name + " 的 " + requirement + " 做好了!!!")
}
}
}
DepartmentStore.addOrder("food", Person("小蘇", "奶茶"));
DepartmentStore.addOrder("food", Person("李四", "麻辣燙"));
DepartmentStore.addOrder("clothes", Person("小蘭", "連衣裙"));
DepartmentStore.notify("food", "麻辣燙");