-
-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
单例模式 #458
Comments
ES6 class实现 class Singleton {
constructor(name, age) {
if (!Singleton.instance) {
this.name = name
this.age = age
Singleton.instance = this
}
return Singleton.instance
}
}
console.log(new Singleton("Taobao", 18) === new Singleton("Baidu", 15)) // true |
//创建型模式的一种
//保证一个类仅仅只有一个实例对象,并且提供一个对该实例对象的全局访问点
//保证全局只有一个实例,无论创建多少个实例对象,都始终指向同一个实例
//js方式实现
//借助辅助方法实现单例
function getSingle(fn) {
let instance = null; // 用于存储单例实例的变量
return function (...args) {
// 返回一个新的函数,该函数接收任意数量的参数
if (instance != null) {
// 如果已经创建了实例
return instance; // 直接返回这个实例
} else {
instance = new fn(...args); // 如果没有实例,使用提供的参数创建一个新的实例
return instance; // 返回新创建的实例
}
};
}
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `hello ${this.name}`;
}
}
const p1 = new Person();
const p2 = new Person();
console.log(p1 === p2);
const instPerson = getSingle(Person);
const p3 = new instPerson("Alice");
const p4 = new instPerson("Bob");
console.log(p3, p4);
export class Person {
private name: string;
private age: number;
private static instance: Person;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public static getInstance(name: string, age: number) {
if (Person.instance === null) {
Person.instance = new Person(name, age);
} else {
return Person.instance;
}
}
}
const p1 = Person.getInstance("tom", 18);
const p2 = Person.getInstance("tom2", 19);
console.log("====================================");
console.log(p1 === p2);
console.log("===================================="); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
个人写法不习惯用class语法糖
The text was updated successfully, but these errors were encountered: