单例模式 确保一个类仅有一个实例,并提供一个访问它的全局访问点
class Window{
constructor(name){
this.name=name;
}
static getInstance(){ //static 为类上色方法,不能通过实例来访问
if(!this.instance){
this.instance = new Window();
}
return this.instance;
}
}
let s1 = Window.getInstance();
let s2 = Window.getInstance();
console.log(s1);
console.log(s2);
console.log(s1===s2);
复制代码
透明单例 本例违反了单一职责原则
let Window = (function (){
let window;
let Window = function (name){
if(window){
return window;
}else{
this.name = name;
return (window=this)
}
}
return Window;
})();
let w1 = new Window().this;
let w2 = new Window().this;
复制代码
把类的实例创建和单例逻辑分开
function Window (name){
this.name = name;
}
function Dialog(title, content){
this.title=title;
this.content = content;
}
Window.prototype.getName=()=>{
console.log(this.name);
}
let CreactSingle = function (Counstructor){
let instance;
return function (){
if (!instance) {
instance = new Counstructor(...arguments);
}
return instance;
}
}
let createWindow = CreactSingle(Window);
let w1 = new createWindow('w1')
let w2 = new createWindow('w2')
console.log(w1===w2);
复制代码
复杂层次对象的可读性要求 实例 jquery
let $={};
$.define = function(namespace, fn){
let namespaces = namespace.split('.');
let fnName = namespaces.pop();
let current =$;
for (let i = 0; i < namespaces.length;i++){
let namespace = namespaces[i];
if (!current[namespace]){
current[namespace]={};
}
current = current[namespace];
}
current[fnName]=fn;
}
$.define('dom.addClass', function(){
console.log('dom.addClass')
})
$.define('dom.attr', function () {
console.log('dom.attr')
})
$.dom.addClass()
$.dom.attr()
复制代码
实例 模态框
class Login{
constructor(){
this.element = document.createElement('div');
document.body.appendChild(this.element);
}
static getInstance(){
if (!this.instance){
this.instance = new Login();
}
return this.instance;
}
}
复制代码
实例 redux 只有一个state
function createStore(){
let state;
let listeners =[];
function subscribe(listener){
listeners.push(listener);
}
function getState(){
return state;
}
function dispatch(){
state = reducer(state, action)
}
return {
subscribe,
getState,
dispatch
}
}
let reducer = function(){
}
let store = createStore(reducer);
复制代码