4 JavaScript設計モード--工場モード/単例モード/アダプタモード
1101 ワード
class Product{
constructor(name){
this.name = name
}
init(){
console.log('init')
}
fn1(){
console.log('fn1')
}
fn2(){
console.log('fn2')
}
}
class Creator{
creater(name){
return new Product(name)
}
}
let creater = new Creator()
let p = creater.creater('apple')
p.init()
p.fn1()
p.fn2()
class SingleObject{
login(){
console.log('login...')
}
}
//
SingleObject.getInstance = (function(){
let instance
return function(){
if(!instance){
instance = new SingleObject()
}
return instance
}
}())
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log('obj1 === obj2',obj1 === obj2) //obj1 === obj2 true
// SingleObject, 。 ES6 。TS
let obj3 = new SingleObject()
obj3.login()
console.log('obj3 === obj2',obj3 === obj2)