We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
单例模式,就是保证一个类仅有一个实例,并且提供一个访问它的全局访问点,就是getInstance方法。单例模式又分为懒汉模式和饿汉模式。 懒汉式:只有用到需要实例的地方才实例。
const singleton = (function() { var instance = null //定义实例 var a = 1; function singleton() { // xxx this.name = 'hello' } function getInstance() { if(instance == null) { instance = new singleton() } return instance } function getData() { // xxx return a; //外部直接访问a访问不到,只有通过这种方式 } return { getInstance, getData } })() console.log(singleton.a) //undefined console.log(singleton.getData()) // 1 console.log(singleton. getInstance().name) // hello
饿汉式:调用就创建
const singleton = (function() { var a = 1; function singleton() { // xxx this.name = 'hello' } var instance = new singleton() //定义实例 function getInstance() { return instance } function getData() { // xxx return a; //外部直接访问a访问不到,只有通过这种方式 } return { getInstance, getData } })() console.log(singleton.a) //undefined console.log(singleton.getData()) // 1 console.log(singleton. getInstance().name) // hello
每天学习一点点~~
The text was updated successfully, but these errors were encountered:
No branches or pull requests
单例模式,就是保证一个类仅有一个实例,并且提供一个访问它的全局访问点,就是getInstance方法。单例模式又分为懒汉模式和饿汉模式。
懒汉式:只有用到需要实例的地方才实例。
饿汉式:调用就创建
每天学习一点点~~
The text was updated successfully, but these errors were encountered: