A
A
Anveed2015-06-20 20:27:48
JavaScript
Anveed, 2015-06-20 20:27:48

In what situations is the factory pattern used in Javascript?

What are some simple examples of the correct use of this pattern?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-06-21
@MarcusAurelius

There are three main ways to use factories in JavaScript:

// Объявление фабрики объектов
function Idiot(name) {
  return { name: name };
}
// создание экземпляра объекта
var idiot1 = Idiot('Bill');
console.dir(idiot1);

// Объявление фабрики классов
function PhilosophySchool(schoolName) {
  return function Philosopher(name) {
    return { name: name, school: schoolName };
  };
}

// Создание класса
var Stoicism = PhilosophySchool('Stoicism');
var philosopher = Stoicism('Marcus Aurelius');
console.dir(philosopher);

// Объявление базового прототипа
function Engineer(specialization) {
  this.specialization = 'Software';
};

Engineer.prototype.getName = function() {
  return this.specialization + ' engineer ' + this.name; 
}

// Объявление фабрики
function University(specialization) {
  function factoryConstructor(name) {
    this.name = name;
  };
  factoryConstructor.prototype = new Engineer(specialization);
  return factoryConstructor;
}

// Создание конструктора инженеров-программистов
SoftwareEngineer = University('Software');

// Создание экземпляра инженера-программиста
var alex = new SoftwareEngineer('Alex');
console.dir(alex.getName());

C
copal, 2015-06-20
@copal

In fact, the factory pattern, not to be confused with the abstract factory and I don’t remember now, but there is another one, it is used everywhere and is a very good example of OO. Its essence is to make the life of the recipient as comfortable as possible. Below is the simplest example, which shows how a button is assembled in a factory, about which the recipient only knows that it adds karma. If I make a lot of such buttons, and then decide to change its skin, then I will not have to run through the code and change it from everywhere, but I will only need to change the assembly at the factory.

var ButtonFactory = (function(){
  function ButtonFactory(){
    
  }
  
  ButtonFactory().prototype.getLikeButton = function(){
    	var likeButton = document.createElement('button');
    	likeButton.style.background = 'ff00ff';
    	likeButton.style.innerHTML = 'like';

        return likeButton;
  };
  
  return ButtonFactory;
})();

var buttonFactory = new ButtonFactory();

document.getElementsByTagName('body')[0].appendChild(buttonFactory.getLikeButton());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question