通过单例模式的方法创建的类只能有一个实例。
实现示例一
- class Manager{
- static InitTag=false;
- constructor(info){
- if(!Manager.InitTag){
- throw new Error("this is a singleton, can't be new, please call create function!");
- }
- this.name=info.name;
- this.age=info.age;
- }
-
- static create(info){
- if(!Manager.instance){
- Manager.InitTag=true;
- Manager.instance=new Manager(info);
- Manager.InitTag=false;
- }
- return Manager.instance;
- }
-
- print(){
- console.log('name=',this.name,' age=',this.age);
- }
- }
-
- let info={name:'Andy',age:50};
- let m=Manager.create(info);
- m.print();
-
- // let b=new Manager();
- // console.log(b);
示例二使用单例实现对浏览器localstorage进行管理
- class Storage {
- static InitStorage = false;
-
- constructor() {
- if(!Storage.InitStorage){
- throw new Error("this is a singleton, can't be new, please call getInstance function!");
- }
- }
-
- static getInstance = () => {
- if (!Storage.instance) {
- Storage.InitStorage = true;
- Storage.instance = new Storage();
- Storage.InitStorage = false;
- }
- return Storage.instance;
- };
-
- setState(key, value) {
- window.localStorage.setItem(key, value);
- }
-
- getState(key) {
- return window.localStorage.getItem(key);
- }
-
- show = () => {
- console.log(window.localStorage);
- };
- }
-
- // let s = new Storage();
- // console.log(s);
- let m=Storage.getInstance();
- console.log(m);