Sunday, February 25, 2018

Abstract Factory Pattern in node.js

Abstract Factory provide an interface for creating families of related or dependent objects without specifying their concrete classes.

In the example we have two factories for creating shoes ,one for creating 'loafer' other for creating 'wingtip'.

consider ShoeFactory.js

    function Loafer(name) {
        this.name = name;

        this.say = function () {
        log.add("I am Loafer from " + name);
        };
    }

    function LoaferFactory() {

        this.create = function (name) {
        return new Loafer(name);
        };
    }

    function Wingtip(name) {
        this.name = name;

        this.say = function () {
        log.add("I am Wingtip from " + name);
        };
    }

    function WingtipFactory() {

        this.create = function (name) {
        return new Wingtip(name);
        };
    }

    var log = (function () {
        var log = "";

        return {
        add: function (msg) { log += msg + "\n"; },
        show: function () { console.log(log); log = ""; }
        }
    })();


    module.exports = {
        LoaferFactory: LoaferFactory,
        WingtipFactory: WingtipFactory,
        log:log
    }

Here is index.js

    var ShoeFactory = require('./ShoeFactory');

    var shoes = [];
    var loaferFactory = new ShoeFactory.LoaferFactory();
    var wingtipFactory = new ShoeFactory.WingtipFactory();

    shoes.push(loaferFactory.create("Lotto"));
    shoes.push(loaferFactory.create("Showman"));

    shoes.push(wingtipFactory.create("Bacca Bucci"));
    shoes.push(wingtipFactory.create("Jorden"));

    for (var i = 0, len = shoes.length; i < len; i++) {
        shoes[i].say();
    }

    ShoeFactory.log.show();

Here classes 'Loafer' & 'Wingtip' had same properties and methods like they are inheriting from same interface.

For checking our abstract factory lets run entry point

node index.js

output:
    I am Loafer from Lotto
    I am Loafer from Showman
    I am Wingtip from Bacca Bucci
    I am Wingtip from Jorden

Here we are creating object of related classes using factory method.

references:
    http://www.dofactory.com/javascript/abstract-factory-design-pattern

No comments:

Post a Comment