Upload
yandex
View
1.463
Download
4
Embed Size (px)
Citation preview
Что такое паттерны?
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"root":3,"program":4,"EOF":5,"simpleInverse":6,"statements"
terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK"
productions_: [0,[3,2],[4,2],[4,3],[4,2],[4,1],[4,1],[4,0],[7,1],[7,2],[8,
performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$)
var $0 = $$.length - 1;
switch (yystate) {
case 1: return $$[$0-1]; break;
case 2: this.$ = new yy.ProgramNode([], $$[$0]); break;
case 3: this.$ = new yy.ProgramNode($$[$0-2], $$[$0]); break;
case 4: this.$ = new yy.ProgramNode($$[$0-1], []); break;
case 5: this.$ = new yy.ProgramNode($$[$0]); break;
case 6: this.$ = new yy.ProgramNode([], []); break;
…
case 47: this.$ = [$$[$0]]; break;
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
Паттерны с нами ужена протяжении 25 лет
Наследование
Где-то в параллельной вселеннойclass Parent {
constructor(name) {
this.name = name || "Adam";
}
say() {
return this.name;
}
}
01.
02.
03.
04.
05.
06.
07.
08.
11
Где-то в параллельной вселеннойclass Child extends Parent {
constructor(name) {
super.constructor(name);
this.random = Math.random();
}
say() {
return super.say() + " (" + this.random + ")";
}
01.
02.
03.
04.
05.
06.
07.
08.
12
Всё можно свести к одной строчкеfunction inherit(C, P) {
C.prototype = new P();
}
01.
02.
03.
14
Тогда наши классы будут такимиfunction Parent(name) {
this.name = name || "Adam";
}
Parent.prototype.say = function () {
return this.name;
};
function Child(name) {}
inherit(Child, Parent);
01.
02.
03.
04.
05.
06.
07.
08.
15
Цепочка прототипов после установлениянаследования
Никогда не делайте так!function inherit(C, P) {
C.prototype = P.prototype;
}
01.
02.
03.
17
Взаимоотношения при совместномиспользовании одного прототипа
Почти «серебряная пуля»var inherit = (function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.__base = P.prototype;
C.prototype.constructor = C;
}
01.
02.
03.
04.
05.
06.
07.
08.
19
Тогда наши классы будут такимиfunction Parent(name) {
this.__constructor.apply(this, arguments);
}
Parent.prototype.__constructor = function (name) {
this.name = name || "Adam";
};
Parent.prototype.say = function () {
return this.name;
01.
02.
03.
04.
05.
06.
07.
08.
20
Тогда наши классы будут такимиfunction Child(name) {
this.__constructor.apply(this, arguments);
}
Child.prototype.__constructor = function (name) {
this.__base.__constructor.apply(this, arguments);
};
01.
02.
03.
04.
05.
06.
21
А инстанции такимиinherit(Child, Parent);
var c = new Child("Eva");
c.say() // "Eva"
c instanceof Child // true
c instanceof Parent // true
c instanceof Object // true
01.
02.
03.
04.
05.
06.
22
Цепочка прототипов после установлениянаследования
Модуль
Действительно ли глобальныепеременные это плохо?var a = $(".body").text("Hello");
26
Действительно ли глобальныепеременные это плохо?function $(counter) {
counter++;
if (counter === 100) return true;
return $(counter);
};
01.
02.
03.
04.
05.
27
Действительно ли глобальныепеременные это плохо?(function $(counter) {
counter++;
if (counter === 100) return true;
return $(counter);
})(0);
typeof $; // "undefined", но не в IE 6-8 :(
01.
02.
03.
04.
05.
06.
28
Цели паттерна— Минимизация числа глобальных переменных и функций
— Изолирование внутренних переменных
— Возможность изменения внутренней логики без изменния API
— Быстрый доступ до локальных переменных
29
Является комбинацией несколькихпаттернов
— Пространство имен
— Немедленно вызываемая функция
— Частные и привилегированные члены
30
$.fn.jsloader = (function ($, window) {
var urlMapping = {};
function createScript(src) {};
window.onerror = function(msg, url, line) {};
return function(src) {
urlMapping[src] = src;
createScript(src);
};
})($, this);
$.fn.jsloader("//yandex.st/share/cnt.share.js");
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
31
var Singleton = (function () {
var instance;
function init() { return { foo: "bar" }; };
return {
getInstance: function () {
if (!instance) { instance = init(); }
return instance;
}
};
})();
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
33
var single = Singleton.getInstance();
var single2 = Singleton.getInstance();
single === single2; // true
01.
02.
03.
34
Все модули в Node.js —«Модули Одиночки»
Цели паттерна— Создание иерархии модулей и их зависимостей
— Возможность динамической загрузки модулей
— Разделение кода на слобосвязанные компоненты
37
Используется— RequireJS
— bem-core
— AngularJS
— COCAINE
38
modules.define('logo', ['jquery', 'underscore'],
function(provide, $, _) {
$('.logo').animate({ opacity: 0.25 });
}
);
typeof $; // "undefined"
typeof _; // "undefined"
01.
02.
03.
04.
05.
06.
07.
39
cocaine.getServices(['geobase','uatraits','logging'],
function(geo,ua,log){
var server = new http.Server(function(req, res){
req.on('end', function(){
geo.region_id(req.headers['x-real-ip'])
.then(function(regionId){
return geo.names(regionId)
})
})
})
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
40
// req.regionId — Определяем id региона
app.use(require('./middleware/express-regionId')(config.geobase));
// req.uatraits - Определяление устройства
app.use(require('express-uatraits')(config.uatraits));
// req.langdetect - Определение языка
app.use(require('express-langdetect')(config.langdetect));
01.
02.
03.
04.
05.
06.
47
jQuery мог бы бытьдекоратором и очень на него
похож
Наблюдатель (Observer,Publisher-Subscriber)
Все пользовательские событияв jQuery — Наблюдатели
Резюме— Существует множество различных паттернов
— Одни и теже задачи можно решать по-разному
— Всегда выбирайте решение наиболее подходящее вам
53
Используйте паттерны с умом
Спасибо[email protected]
twitter.com/denchistyakov