Skip to content

Instantly share code, notes, and snippets.

@OlehRovenskyi
Last active August 12, 2017 20:47
Show Gist options
  • Save OlehRovenskyi/701d28bdb7358c1395267e18cc93d97a to your computer and use it in GitHub Desktop.
Save OlehRovenskyi/701d28bdb7358c1395267e18cc93d97a to your computer and use it in GitHub Desktop.
GOF Patterns
// ---- Module ----
// есть проблема в том что все свойства типа public, нет инкапсуляции
var counter = {
counter: 0,
incrementCounter: function () {
return ++this.counter;
},
resetCounter: function () {
return this.counter = 0;
}
};
// исправим ситуацию
var counterModule = (function () {
var counter = 0;
return {
incrementCounter: function () {
return ++this.counter;
},
resetCounter: function () {
return this.counter = 0;
}
}
})();
// модуль с использование import
var wrapperId = 'counter';
var counterModule2 = (function (id) {
var counter = 0;
console.log(id);
return {
incrementCounter: function () {
return ++this.counter;
},
resetCounter: function () {
return this.counter = 0;
}
}
})(wrapperId);
// модуль с использование export
var counterModule3 = (function () {
var counter = 0;
var module = {};
module.incrementCounter = function () {
return ++this.counter;
};
module.resetCounter = function () {
return this.counter = 0;
};
return module;
})();
// Module Constructor
var Neuron = (function (jQuery, Underscore) {
var Cell = function () {};
function say(message) {
console.log(message);
}
Cell.prototype = {
migrate: function() {
// cell is going to find a better place
say('travelling');
},
learn: function(subj) {
// trying something new
say('f***ing ' + subj);
},
duplicate: function() {}
};
return Cell;
})($, _);
// Usage:
// Creates new neuron instance
var brainCell = new Neuron();
// Outputs: travelling
brainCell.migrate();
// Outputs: f***ing math
brainCell.learn('math');
// ---- Singleton ----
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
// creates instans if it doesn't exist
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// Usage:
// Creates new instance
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
// Outputs: true
console.log(instance1 === instance2);
// ---- Pub-Sub ----
(function( $ ) {
var o = $( {} );
$.each({
trigger: 'publish',
on: 'subscribe',
off: 'unsubscribe'
}, function( key, val ) {
jQuery[val] = function() {
o[key].apply( o, arguments );
};
});
})( jQuery );
$.getJSON('http://search.twitter.com/search.json?q=dogs&callback=?', function( results) {
$.publish( 'twitter/results', results );
});
$.subscribe( 'twitter/results', function( e, results ) {
$('body').html(
$.map( results.results, function( obj, index) {
return '<li>' + obj.text + '</li>';
}).join('')
);
});
/*
* Publish/Subscribe Pattern
*/
class PubSub {
constructor() {
this.handlers = [];
}
subscribe(event, handler, context) {
if (typeof context === 'undefined') { context = handler; }
this.handlers.push({ event: event, handler: handler.bind(context) });
}
publish(event, args) {
this.handlers.forEach((topic) => {
if (topic.event === event) {
topic.handler(args)
}
})
}
}
/*
* Simple ChatRoom Class
* uses the PubSub Class to notify other users when a message is sent.
*/
class ChatRoom {
constructor() {
this.pubsub = new PubSub();
this.pubsub.subscribe('message', this.emitMessage, this);
}
emitMessage(msg) {
console.group('PubSub');
console.log('user sent message!', msg);
console.groupEnd();
}
sendMessage() {
this.pubsub.publish('message', 'Hey, how are you?');
}
}
var room = new ChatRoom();
room.sendMessage();
// ---- Mediator ----
/*
* Publish/Subscribe Pattern
*/
class PubSub2 {
constructor() {
this.handlers = [];
}
subscribe(event, handler, context) {
if (typeof context === 'undefined') {
context = handler;
}
this.handlers.push({ event: event, handler: handler.bind(context) });
}
publish(event, args) {
this.handlers.forEach((topic) => {
if (topic.event === event) {
topic.handler(args)
}
})
}
}
/*
* Mediator Pattern
*/
class Mediator extends PubSub2 {
constructor(opts) {
super(); // get handlers
}
attachToObject(obj) {
obj.handlers = [];
obj.publish = this.publish;
obj.subscribe = this.subscribe;
}
}
var mediator = new Mediator();
var myRoom = {
name: 'myRoom'
};
mediator.attachToObject(myRoom);
myRoom.subscribe('connection', function() {
console.group('Mediator');
console.log(`user connected to ${myRoom.name}!`);
console.groupEnd();
}, myRoom);
myRoom.publish('connection');
// ---- Facade ----
var module = (function() {
var _private = {
i: 5,
get: function() {
console.log('Текущее значение:' + this.i);
},
set: function(val) {
this.i = val;
},
run: function() {
console.log('процесс запущен');
},
jump: function() {
console.log('резкое изменение');
}
};
return {
facade: function(args) {
_private.set(args.val);
_private.get();
if (args.run) {
_private.run();
}
}
}
}());
module.facade({run:true, val:10});
// ----
function Facade() {
function getRequest(url, data, callback) {
setTimeout(function () {
return callback([{ name: 'Arni' }]);
}, 1000);
}
this.getResult = function(url, data, callback) {
getRequest(url, data, callback);
};
return this;
}
var BannerModule = function(options) {
var params = options || {},
doc = document,
facade = new Facade(),
ui = {
'close': doc.getElementById(params.close),
'image': doc.getElementById(params.image),
'download': doc.getElementById(params.download)
},
helper = {
applyData: function(options) {
console.log('apply data');
}
},
events = {
close: function() {
console.log('close')
},
image: function() {
console.log('image')
},
download: function() {
console.log('download')
}
};
//events mapping
for (var key in ui) {
ui[key].onclick = (function(key){
return function(event) {
events[key]();
};
})(key);
}
function successCallback(data) {
console.log('mockCallback', data);
helper.applyData(data);
};
return {
loadData: function() {
facade.getResult("GET", 'localhost:4000', successCallback);
}
};
};
var banner = new BannerModule({
close: 'close',
image: 'image',
download: 'download'
});
banner.loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="close">close</button>
<button id="image">image</button>
<button id="download">download</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script src="examples.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment