Created
November 14, 2019 06:49
-
-
Save KalpasWang/7d332e7bc0c8672f4697648faa7937e5 to your computer and use it in GitHub Desktop.
工廠模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var corolla = CarMaker.factory('Compact'); | |
var solstice = CarMaker.factory('Convertible'); | |
var cherokee = CarMaker.factory('SUV'); | |
corolla.drive(); // "Vroom , I have 4 doors" | |
soIstice.drive(); // "Vroom , I have 2 doors" | |
cherokee.drive(); // "Vroom , I have 17 doors" | |
// 父建構式 | |
function CarMaker(){} | |
//父建樣式的一個方法 | |
CarMaker.prototype.drive = function() { | |
return "Vroom, I have " + this.doors + " doors"; | |
}; | |
// 靜態的工廠方法 | |
CarMaker.factory = function (type) { | |
var constr = type, | |
newcar; | |
// 建構式不存在則拋出错误 | |
if ( typeof CarMaker[constr] !== “function" ) { | |
throw { | |
name : " Error ", | |
message : constr + " doesn't exist"; | |
}; | |
} | |
// 到這裡我們已經知道建構式存在了 | |
// 我們讓它繼承父建構式,但僅此一次 | |
if ( typeof CarMaker[constr].prototype.drive !== " function" ) { | |
CarMaker[constr].prototype = new CarMaker(); | |
} | |
// 建立新實體 | |
newcar = new CarMaker[constr](); | |
// 選擇性的呼叫一些方法 , 然後回傳 | |
return newcar; | |
}; | |
// 定義具體的 car maker | |
CarMaker.Compact = function() { | |
this.doors = 4; | |
}; | |
CarMaker.Convertible = function() { | |
this.doors = 2; | |
}; | |
CarMaker.SUV = function() { | |
this.doors = 24; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment