Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Singleton #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 1 addition & 20 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,3 @@
# JavaScript-Design-Patterns

Типы шаблонов и примеры некоторых из них.
Порождающие шаблоны (Creational). Cоздание новых объектов:
- Конструктор (Constructor)
- Модульный (Module)
- Фабричный метод (Factory)
- Одиночка (Singleton)

Структурные шаблоны(Structural). Упорядочивают объекты:
- Декоратор(Decorator)
- Фасад (Facade)

Поведенческие (Behavioral). Как объекты соотносятся друг с другом:
- Наблюдатель(Observer)
- Посредник(Mediator)
- Команда(Command)

Ссылки на статьи:
https://medium.com/@marina.kovalyova/java-script-design-patterns-569c627d25f9

https://proglib.io/p/javascript-patterns/
Одиночка (англ. Singleton) — порождающий шаблон проектирования, гарантирующий, что в однопроцессном приложении будет единственный экземпляр некоторого класса, и предоставляющий глобальную точку доступа к этому экземпляру.
33 changes: 33 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var counterModule = (function () {
var instance,
counter = 0;

var getCounter = function () {
return counter;
};

var increaseCounter = function () {
counter ++;
};

var createInstance = function () {
return {
getCounter: getCounter,
increaseCounter: increaseCounter
}
};

return {
getInstance: function () {
return instance || (instance = createInstance());
}
}
})();

console.log(counterModule.getInstance().getCounter());
counterModule.getInstance().increaseCounter();
console.log(counterModule.getInstance().getCounter());
counterModule.getInstance().increaseCounter();
counterModule.getInstance().increaseCounter();
console.log(counterModule.getInstance().getCounter());