单例模式
只允许实例化一次的对象类。
class Window {
private static instance: Window;
private constructor() { }
static getInstance() {
if (!Window.instance) {
Window.instance = new Window();
}
return Window.instance;
}
}
var w1 = Window.getInstance();
var w2 = Window.getInstance();
console.log(w1 === w2);
ES5单例模式
interface Window {
hello: any
}
function Window() { }
Window.prototype.hello = function () {
console.log('hello');
}
Window.getInstance = (function () {
let window: Window;
return function () {
if (!window)
window = new (Window as any)();
return window;
}
})();
let window = Window.getInstance();
window.hello();
透明单例
let Window = (function () {
let window: Window;
let Window = function (this: Window) {
if (window) {
return window;
} else {
return (window = this);
}
}
Window.prototype.hello = function () {
console.log('hello');
}
return Window;
})();
let window1 = new (Window as any)();
let window2 = new (Window as any)();
window1.hello();
console.log(window1 === window2)
封装变化
export { }
function Window() {
}
Window.prototype.hello = function () {
console.log('hello');
}
let createInstance = function (Constructor: any) {
let instance: any;
return function (this: any) {
if (!instance) {
Constructor.apply(this, arguments);
Object.setPrototypeOf(this, Constructor.prototype)
instance = this;
}
return instance;
}
};
let CreateWindow: any = createInstance(Window);
let window1 = new CreateWindow();
let window2 = new CreateWindow();
window1.hello();
console.log(window1 === window2
使用场景
redux store
function createStore(reducer: any) {
let state: any;
let listeners: any[] = [];
function getState() {
return state;
}
function dispatch(action: any) {
state = reducer(state, action);
listeners.forEach(l => l());
}
function subscribe(listener: any) {
listeners.push(listener);
return () => {
listeners = listeners.filter(item => item != listener);
console.log(listeners);
}
}
dispatch({});
return {
getState,
dispatch,
subscribe
}
}
let store = createStore((state: any, action: any) => state);
缓存
let express = require('express');
let fs = require('fs');
let cache: Record<any, any> = {};
let app = express();
app.get('/user/:id', function (req: any, res: any) {
let id = req.params.id;
let user = cache.get(id);
if (user) {
res.json(user);
} else {
fs.readFile(`./users/${id}.json`, 'utf8', function (err: any, data: any) {
let user = JSON.parse(data);
cache.put(id, user);
res.json(user);
});
}
});
app.listen(3000);