Author - StudySection Post Views - 402 views
Factory Pattern

Javascript / Jquery – Factory Pattern

Factory pattern is a constructive pattern that provides a template that is used to create the objects. It is used in that situation where the type of object required can vary and need to be specified in each case. This pattern does not use the new keyword to create the instance of objects. It does not require the use of a constructor to create objects. It provides the generic interface that assigns the object creation responsibility to the corresponding sub-classes.

As the factory term implies we can use this pattern to create different objects which have some similar features. Let’s take an example of a flavored shakes factory that can be used to create different flavors of shakes.

class FlavouredShakesFactory {
constructor() {
this.createShakes = function(flavor) {
let Shake;
if (flavor === 'chocolate'){
Shake = new Chocolate();
}
else if (flavor === 'mango'){
Shake = new Mango();
}
else if (flavor === 'strawberry'){
Shake = new Strawberry();
}
return Shake;
};
}
}
class Chocolate {
constructor() {
this.shakeFlavor = "chocolate";
this.message = function() {
return `You chose the ${this.shakeFlavor} flavor.`;
};
}
}
class Mango {
constructor() {
this.shakeFlavor = "mango";
this.message = function() {
return `You chose the ${this.shakeFlavor} flavor.`;
};
}
}
class Strawberry{
constructor() {
this.shakeFlavor = "strawberry";
this.message = function() {
return `You chose the ${this.shakeFlavor} flavor.`;
};
}
}
// creating objects
const flavouredShakesfactory = new FlavouredShakesFactory();
const chocolate = flavouredShakesfactory.createShakes('chocolate');
const mango = flavouredShakesfactory.createShakes('mango');
const strawberry = flavouredShakesfactory.createShakes('strawberry');
console.log(chocolate.message());
console.log(mango.message());
console.log(strawberry.message());

In the example above we created a factory called FlavouredShakesFactory. Its constructor has a function createShakes that accepts the parameter flavor. Depending on the flavor, it instantiates an object of the corresponding class. For example, if the flavor is chocolate, it instantiates an object of the Chocolate class. It does the same if the flavor is mango or strawberry

People having good knowledge of Financial accounting can get an accounting certification from StudySection to increase their chances of getting a job in this field. You can get a foundation level certification if you are new to Financial Accounting or you can go for advanced level certification if you have expert level skills in Financial accounting.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri