Basic Factory Pattern for JavaScript

Ben Watts
4 min readMay 26, 2020

The factory pattern is a way to create objects without worrying about how that object is created or what is needed, which allows loose coupling. This means we can ask our factory object to provide us a specific object and the factory will deal with constructing it. Of course, we have to setup our factory to do the creation first!

Here’s an example: you want to hire a new developer to work at your company. Now we may know what skills we are looking for, but what about work benefits and background checks? This is where we would ask the company’s hiring manager to sort things out. The hiring manager is our factory, so we basically ask them “find me a developer with X skills”.

So let’s create a basic factory in a Javascript application. Our application is going to be quite basic; all it’s going to do is display some text, set the text colour, and also set the background colour.

Our basic application:

<!-- Application code --><html>
<script>
function RenderApplication() {
const title = document.createElement("H1");
const titleText = document.createTextNode("Basic Factory Pattern for Javascript");
title.className = "centre";
title.appendChild(titleText);
document.body.appendChild(
title
);
}
window.onload = function() {
RenderApplication();
}
</script>
<style>
.centre {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
</body>
</html>

Now let’s create our ConfigService. This will just hold our primary and secondary colour that will be used for our application, as below:

<!-- Config service --><script>
function ConfigService() {
this.Settings = [];
this.Settings["PrimaryColour"] = '#BFFCC6';
this.Settings["SecondaryColour"] = '#6EB5FF';
}
</script>

And let’s go ahead and create our FactoryService. This will deal with giving us our ConfigService when we ask for it:

<!-- Factory Service --><script>
function FactoryService() {
this.repoList = [
{name: 'ConfigService', source: ConfigService}
];
}
FactoryService.prototype.GetInstance = function(instanceName)
{
selectedRepo = this.repoList.find((element) => { return element.name == instanceName; });
return new selectedRepo.source();
}
Window["FactoryService"] = new FactoryService();
</script>

Now using our ConfigService and FactoryService we can update our application.

We’re going to use the primary colour setting to set the h1 colour and use our secondary colour setting to set the body background colour.

Now we could just create our ConfigService and use that directly, but then if we wanted to replace our ConfigService with a different ConfigService we would have to look through our entire code base to find the “new ConfigService()” and replace it.

This is where our FactoryService comes into play, so let’s setup our application to use the FactoryService when we want to use our ConfigService:

<!-- Full application --><html>
<script>
function ConfigService() {
this.Settings = [];
this.Settings["PrimaryColour"] = '#BFFCC6';
this.Settings["SecondaryColour"] = '#6EB5FF';
}
</script>
<script>
function RepositoryFactory() {
this.repoList = [
{name: 'ConfigService', source: ConfigService}
];
}
RepositoryFactory.prototype.GetInstance = function(instanceName)
{
selectedRepo = this.repoList.find((element) => { return element.name == instanceName; });
return new selectedRepo.source();
}
Window["RepositoryFactory"] = new RepositoryFactory();
</script>
<script>
function RenderApplication() {
const config = Window["RepositoryFactory"].GetInstance("ConfigService");
const title = document.createElement("H1");
const titleText = document.createTextNode("Basic Factory Pattern for Javascript");
title.style.color = config.Settings["PrimaryColour"]
title.className = "centre";
title.appendChild(titleText);
document.body.appendChild(
title
);
document.body.style.backgroundColor = config.Settings["SecondaryColour"];
}
window.onload = function() {
RenderApplication();
}
</script>
<style>
.centre {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
</body>
</html>

Now our full application does the following: we first define our ConfigService (which just holds our settings). Next we define our FactoryService, this holds an array of objects which are made up of a name and source. The GetInstance method attached to the FactoryService is used to generate a new instance we request.

If you look at the RenderApplication function, we are now calling the FactoryService to get our ConfigService and then using the settings array from the ConfigService to set our colours.

Now I understand we could have set the colour for our HTML page using css or any other number of ways, but I just wanted to demonstrate the factory pattern in a Javascript application.

Also just for a bonus round, let’s say we wanted to use a different config service. Thanks to factory pattern we have implemented, we can simply replace that source target in our FactorySevice like so:

<!-- Random config service --><script>
function RandomConfigService() {
this.Settings = [];
this.Settings["PrimaryColour"] = `#${Math.floor(Math.random()*16777215).toString(16)}`;
this.Settings["SecondaryColour"] = `#${Math.floor(Math.random()*16777215).toString(16)}`;
}
</script>
// Update our factory service to return a new RandomConfigService
<script>
function FactoryService() {
this.repoList = [
{name: 'ConfigService', source: RandomConfigService}
];
}
...
</script>

If we now refresh our application, our body and h1 tag will have been assigned a random colour. We could even go further and change our ConfigService to read the colours from a central business API, but this is as far as the post goes.

Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative!

References
Factory Pattern: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
Gist: https://gist.github.com/MrApproved/62f83df28cb30a41423838db3982b4a2
Wallpaper: https://www.pexels.com/photo/business-equipment-factory-industrial-plant-357440/
Random hex colour: https://css-tricks.com/snippets/javascript/random-hex-color/

--

--