var Singleton = function (name, age) {
this.name = name;
this.age = age;
this.show = function () {
console.log(`name:${this.name} age:${this.age}`)
}
}
Singleton.getInstance = function () {
var instance = null;
return function (name, age) {
// 第一次执行默认对象不存在
if (!instance) {
instance = new Singleton(name, age)
}
// 否则就是再次创建,可以不写else简化代码
return instance
}
}()
// var getSingle = function (fn) {
// var result;
// return function () {
// return result || ( result = fn.apply(this, arguments) );
// }
// };
// console.log(getSingle(Singleton.getInstance('张三',18)))
var instance1 = Singleton.getInstance('张三', 18);
instance1.show() // name:张三 age:18
var instance2 = Singleton.getInstance('李四', 20)
instance2.show() // name:张三 age:18
instance1 === instance2 // true
// var Student = function (name, age) {
// this.name = name;
// this.age = age;
// this.show = function () {
// console.log(`name:${this.name} age:${this.age}`)
// }
// }
// var createSingleStudent = function () {
// return new Student('张三',18)
// }
// var Dog = function (name, age) {
// this.name = name;
// this.age = age;
// this.show = function () {
// console.log(`name:${this.name} age:${this.age}`)
// }
// }
// var createSingleDog = function () {
// return new Dog('张三',18)
// }
// //单例模式抽象,分离创建对象的函数和判断对象是否已经创建
// var getSingle = function (fn) {
// var result;
// return function () {
// return result || ( result = fn.apply(this, arguments) );
// }
// };
// var createStudent1= getSingle(createSingleStudent)()
// var createStuden2 = getSingle(createSingleStudent)()
// console.log(createStudent1==createStuden2)
console