Last active
September 16, 2015 04:56
-
-
Save dreamline2/5830cfa811a8a27a9866 to your computer and use it in GitHub Desktop.
singleton example -> create plus and minus to operate num
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 operate = (function(){ | |
// num is local variable, and we can via return api to manipulate num, no other external methods to manipulate num. | |
var num; | |
function createNum() { | |
var num = new Number(0); | |
return num; | |
} | |
return { | |
getNum: function () { | |
if (!num) { | |
num = createNum(); | |
} | |
console.log(num) | |
return num; | |
}, | |
plus: function () { | |
if (!num) { | |
num = createNum(); | |
} | |
num++; | |
console.log(num) | |
}, | |
minus: function () { | |
if (!num) { | |
num = createNum(); | |
} | |
num--; | |
console.log(num) | |
} | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
singleton 稱為單體模式 ,為最常見的封裝模式!
主要是為提供了兩大功能