So, since Interfaces are in JavaScript OOP world, our job is to use ConcreteFactory and Developer objects.
Let me make an example in WinJS to show you how they are implemented.
Before start coding JavaScript, I'd advice you to create another JavaScript file and link it.
Implementation
Let's create our Developer objects in JS using WinJS library:
- var Developer = WinJS.Class.define(
- function (name) {
- this.name = name;
- this.Shout = function () {
- Helper.Func.add("I'm an employee named " + name);
- }
- });
This is a simple class, that has a function named "Shout" which sends message to our Helper class (which I will introduce later)
Now,lets define our ConcreteFactory:
- var DeveloperFactory = WinJS.Class.derive(Developer,
- function () {
- this.Wave = function (name) {
- return new Developer(name);
- }
- });
Be careful about notation, I named it as its ConcreteFactory. As its not AbstractFactory, but the Design Pattern is named Abstract Factory. It may be confusing at first but in JS Abstract Factory is 2 objects pattern. We derived Developer classes from Factory here.
Before creating our Helper Class, let's create a namespace for it:
- WinJS.Namespace.define("Helper");
Fill in the functionality of this Helper namespace with 2 functions that gets and sets items:
- var log = "";
-
- Helper.Func =
- {
- add: function (msg) { log += msg + "\n"; },
- show: function () { console.log(log); log = ""; }
- };
I've decided to show the output on JavaScript Console.But its up to you.
Next we'll be creating a new Factory object and call the Shout function which will write some output for a developer individual.
- var devfactory = new DeveloperFactory();
-
- devfactory.Wave("Ibrahim Ersoy").Shout();
We've created a new developer object named "Ibrahim Ersoy" and as a last step,we'll be calling our show function:
After you build & run the project,you'll be getting the output like this:
Finalize
You can create as much Product and Factory object as you like. It's all up to your software design
If I wanted to extend it, I'd add Companies and Company Factory:
- var Company = WinJS.Class.define(function (name) {
- this.name = name;
- this.Shout = function() {
- Helper.Func.add("This is " + name);
- }
- });
-
-
- var CompanyFactory = WinJS.Class.derive(Company,
- function () {
- this.Wave = function (name) {
- return new Company(name);
- }
- });
To access and create new objects from it I'd initialize it:
- var compfactory = new CompanyFactory();
-
- compfactory.Wave("Microsoft").Shout();
- compfactory.Wave("MCN").Shout();
- compfactory.Wave("Google").Shout();
Abstract Factory is useful to implement in project "if you have the same kind of products but different kinds of objects" and with ConcreteFactory we can create many products with it.