September 18, 2020

Design patterns (Observer, Singleton, Factory Method and Adapter) implemented in Dojo Toolkit JS

This is a list of design patterns, implemented in Dojo JS

I'v found difficult to work with some restrictions as the use of static variables, in this kind of implementation

Observer


  //Observer pattern

      dojo.declare("com.dev.dojo.Observer",[],
    	{
    	  state: "observer",
    	  obs: null,
    	 constructor:function(obl){
    		  this.obs = obl;
    	  },
    	  update: function(sta){
    		 this.state = sta;
    		 status = this.obs.updateObserver(this);
    	  
    	  	console.log("udate observer result for "+ this + ": " +  status);
    	  }
    	  
    		  
    	});
      
      dojo.declare("com.dev.dojo.Observable",[],
    	    	{
    	    	  state: "observable",
    	    	  observers: [],
    	    	 
    	    	 Observervable:function(obss){
    	    		  this.observers = obss;
    	    	  },
    	    	  addObserver: function(o){
    	    		  idx = dojo.indexOf(this.observers,o);
    	    		  if(idx!=null && idx>=0)
    	    			  this.observers[idx] = o;
    	    		  else
    	    			this.observers.push(o);  
    	    	  },
    	    	  getObservers: function(){
    	    		  return this.observers;
    	    	  },
    	    	  notifyAll: function(stat){
    	    		  this.state = stat;
    	    		  for(i=0;i< this.observers.length;i++)
                	     this.observers[i].update(this.state);
    	    	  },
    	    	  updateObserver:function(observer){
    	    		  idx = dojo.indexOf(this.observers,observer);
    	    		  if(idx!=null && idx>=0){
    	    			  this.observers[idx] = observer;
    	    		  	 return 1;
    	    		  }
    	    	  	return -1;
    	    	  }
    	    	  ,
    	    	  displayObservers: function(s) {
    	    		  for(i=0;i

Singleton

//Singleton pattern
var created = false;
dojo.declare("com.dev.dojo.Singleton",[],{
	
	singleton:null,
	__isCreated__: created,
	
	getInstance: function(){
		if(!this.__isCreated__){
			created = true;
			this.singleton = new com.dev.dojo.Singleton();
		}
		return this.singleton;
	},
	
	doTask: function(seconds){
		for(i=0;i
    

Factory Method

 //Factory method pattern
    
    dojo.declare("com.dev.dojo.Animal",[],{
    	type:"Animal",
    	saySomething: function(){
    		return "I'm too generic to say something";
    	}
    });
    dojo.declare("com.dev.dojo.Dog",[com.dev.dojo.Animal],{
    	type:"Dog",
    	saySomething: function(){
    		return "Guau,guau,guau";
    	}
    });
   
    dojo.declare("com.dev.dojo.Tiger",[com.dev.dojo.Animal],{
    	type:"Tiger",
    	saySomething: function(){
    		return "Roarrrr,roarrrrrr";
    	}
    });
   
    dojo.declare("com.dev.dojo.Factory",[],{
    
    	getInstance:function(type){
    		var instance = null;
    		if(type==new com.dev.dojo.Animal().type)
    			instance = new com.dev.dojo.Animal();
    		else if(type==new com.dev.dojo.Tiger().type)
    			instance = new com.dev.dojo.Tiger();
    		else if(type==new com.dev.dojo.Dog().type)
    			instance = new com.dev.dojo.Dog();
    		
    		return instance;
    	}
    	
    });
    var t = "Dog";
    var o = com.dev.dojo.Factory().getInstance(t);
    
    alert(o.saySomething());
    
    t="Tiger";
    
    o = com.dev.dojo.Factory().getInstance(t);
    
    alert(o.saySomething());
    
    //End of factory method
    

Adapter

    //Adapter pattern
     /* Example of adapter pattern*/
      
      function FlyingEngine() {
    	  var operation = "Principal ";
    	  var state = -1;
    	  this.turnOnEngine=function(){
    		  this.operation += "Engine is turning ON\n";
    	  	  this.state = 0;
    	  }
    	  this.takingOver=function(){
    		  if(this.state<1)
    			  this.operation += "Can't take over until engine is turn on";
    		  this.operation += "Taking over\n";
    		  this.state=2;
    	  }
    	  
    	  this.flying=function(){
    		  if(state<2)
    			  operation+="Not posible to fly until taking over";
    		  this.operation += "FLYING\n";
    		  this.state=3;
    	  }
    	  
    	  
      }
      
      function Helicopter(){
    	  var operation = "Principal ";
    	  var flyingEngine = new FlyingEngine();
    	  this.rotorsWarm=function(){
    		  if(this.state==0){
    		 /*adapter->*/ flyingEngine.operation = "Rotors ";
    		 				flyingEngine.turnOnEngine();
    		 				this.operation += flyingEngine.operation;
    			  this.operation += "warming rotors:"
    			  for(i=0;i<5;i++)
    	  		this.operation +=i
    		 }
    		  this.operation += "\n";
      		
      		this.state+=1;
    	  	}
      
      
      }
      
      
      dojo.extend(Helicopter,new FlyingEngine());
      
      var h1 = new Helicopter();
      var s = "";
      h1.turnOnEngine();
      h1.rotorsWarm();
      h1.takingOver();
      h1.flying();
      
      s = h1.operation;
      
      alert(s);
      
      

Proxy pattern example

Proxy pattern
Index
Proxy pattern
Includes code that you can download from GitHub

Theory

The proxy pattern Provide a surrogate or placeholder for another object to control access to it.

One reason for controlling access to an object is to defer the full cost of its creation and initialization until we actually need to use it.

In this example we have simulated a remote communication as you will see.

The UML model is

Figure-1

Code of the application

Comm Interface

package com.patterns.proxy;

public interface Comm {
	public String receive();
	public boolean reset();


}

CommImpl Class

package com.patterns.proxy;

public class CommImpl implements Comm {
private static int INFOLENGTH = 10;
private boolean isAlive = false;
private String information;
public String receive() {
	// TODO Auto-generated method stub
	if(isAlive) mockCall();
	return read();
}
public boolean reset() {
	if(isAlive) isAlive=false;
	else isAlive = true;
	return isAlive;
}
public String read() {
	// TODO Auto-generated method stub
	if(isAlive)
	information = this.generateInfo();
	return information;
}
 void mockCall() {
	try {
		Thread.sleep(500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

String generateInfo() {
	StringBuffer sb = new StringBuffer();
	String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	for(int i=0;i

CommProxy Class

package com.patterns.proxy;

public class CommProxy implements Comm{

	private static CommImpl comm;
    private boolean isAlive;
    
	public CommProxy() {
		comm = new CommImpl();
	}
	
	public String receive() {
	   
		if(isAlive) /*new information arrived */
			return comm.receive(); 
		else
			return "NO NEW INFORMATION=" + comm.receive();
	}

	public boolean reset() {
		isAlive = comm.reset();
		return isAlive;
		// TODO Auto-generated method stub
		
	}


	
}


App Class

package com.patterns.proxy;

/**
 
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	String message;
        CommProxy proxy = new CommProxy();
        
        proxy.reset();
        message = proxy.receive();
        System.out.println("Mess-1"+ message);
        proxy.reset();
        message = proxy.receive();
        System.out.println("Mess-2"+ message);
        proxy.reset();
        message = proxy.receive();
        System.out.println("Mess-3"+ message);
    }
}


Ok!

Design Patterns with code examples

Design Patterns code examples
Index
Gof Patterns code examples
You can download code from GitHub Updated

You can find implementation in Java of the following design patterns:

Design Patterns
DecoratorCar decorator example
ObserverSubject, suscribers example
SingletonConcurrent access example
Abstract FactoryAbstract factory that creates virtual robots example
CommandInvoker, command, receiver (simulates a cars race)
AdapterInternational facilities adapter
FacadeMobile Clinic facade example
MVCCompound pattern: Model as Observer, Controller as Strategy, View as Composite (ref:HFDesign Patterns)

10 Architectural Patterns

The article describes and gives some examples of application of the following Architectural patterns:

  1. Layered pattern
  2. Client-server pattern
  3. Master-slave pattern
  4. Pipe-filter pattern
  5. Broker pattern
  6. Peer-to-peer pattern
  7. Event-bus pattern
  8. Model-view-controller pattern
  9. Blackboard pattern
  10. Interpreter pattern

It can be found

at

: 10 Common Software Architectural Patterns in a nutshell