Skip navigation

Tag Archives: design pattern


Interface is an important concept in object oriented programming. It helps to reuse the code effectively.
So what is interface?

Interface provides a way to define what methods an object should have but not how it should be implemented. Interface allows to group objects based on what features they provide.

Javascript does not come with built-in support for interface. So in JavaScript it has to be manually ensure that a given class implements an interface.

Three ways to ensure interface in JavaScript:

  • Comments,
  • Attribute checking,
  • Duck typing
/*
interface BasicMember {
    function isMajor(age);
    function isCitizen(ssn);
}
interface GoldMember {
    function havingVisaCard(ccn);
}
*/
var RentACar = function(user, vehicle) { // implements BasicMember, GoldMember
    // ...
}
// Implement the BasicMember interface
RentACar.prototype.isMajor = function(age) {
    // ...
};
RentACar.prototype.isCitizen = function(ssn) {
    // ...
};
// Implement the GoldMember interface
RentACar.prototype.havingVisaCard = function(ccn) {
    // ...
};

This is just kind of documentation, Compliance is voluntary. Other two types will be explained in forth coming posts.


In the previous post (JavaScript Singleton pattern), we saw the basic structure of JavaScript Singleton pattern. Then what is the need of JavaScript Lazy loading Singleton pattern? You can understand that JavaScript Singleton pattern which explain in previous post becomes performance issue if the code inside singleton object becomes more and more because the ananimous function executes immediately and returns properties, function, etc into singleton object immediately when .js files loads.

So it is wise to execute the function when it requires really. For that we need to define getInstance() method which checks to see whether the singleton has been instantiated. If not, it will instantiated and returned.  If it has, a stored copy is returned.

NameSpace.Singleton = (function(){
	var instance;
	function constructor() { // normal singlton goes here
		// Private members
		var privateAttr1 = false;
		var privateAtrr2 = [1,2,3];
		function privateMethod1(){
			// code goes here
		}
		function privateMethod2(){args
			// code goes here
		}
		return {  // Public members
			publicAttr1 : true;
			publicAttr2 : 25,
			publicMethod1 : function() {
				// code goes here
			},
			publicMethod2 : function(args) {
				// code goes here
			}
		};
	}
	return {
		getInstance : function(){
			if(!instance) {  // check already exists
				instance = constructor();
			}
			return instance;
		}
	}
})();

// Here is how the public function get called.
NameSpace.Singleton.getInstance().publicMethod1();
Follow

Get every new post delivered to your Inbox.

Join 150 other followers