design patterns · JavaScript · Programming

Design Patterns in JavaScript

Singleton Pattern

//This is a simple singleton with all public members
var simpleSingleton = {
    "func1" : function() {alert('func1');},
    "msg" : "hello"
};

//This is complex singleton with private and public members
var complexSingleton = (function() {
    var privateVar = 'private var';
    function privateMethod1(){alert('privateMethod1');}

    return {
        publicMethod1 : function(){
            //from here all public and private members are accesible
            privateMethod1();
        },

        getPrivateVar : function() {
            return privateVar ;
        }
    }

})();


function testSingleton() {
    simpleSingleton.func1();
    alert(simpleSingleton.msg);

    complexSingleton.publicMethod1();
    alert(complexSingleton.getPrivateVar());
}

testSingleton();

Factory Pattern

var factory = (function(){
    
    var Car = function(model,price){
        this.model = model;
        this.price = price;
    };

    return {
        getPerson : function(model,price){return new Car(model,price);}
    };

})();


testFactoryPattern() {
    var x = factory.getPerson('i10','5lakh');
    
    alert(x.model);
    alert(x.price);
}

testFactoryPattern();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s