viernes, 18 de septiembre de 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);
      
      

miércoles, 11 de marzo de 2020

Design Patterns 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)

viernes, 15 de noviembre de 2019

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

ckage 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);
    }
}


sábado, 8 de junio de 2019

Java 9 Concurrency new CompletonStage and CompletableFuture

Java 9 CompletableFuture Example


Introduction

Many Java applications require of concurrent operations. When using concurrency there are common risk that have to be avoided such as memory leaking, race condition, callback hell, disjointed error handling… In version 8, Java provides a new class CompletableFuture. This class has about 50 methods mainly for: compose, combine and execute asychronous steps and also to handle errors.

Concurrency classes provided by Java as  Future and ExecutorService interfaces since version 5 to handle the asynchronous operations.

The Future interface is a placeholder for a result from an asynchronous operation which can be a Runnable or Callable instance. The ExecutorService interface submits an asynchronous operation and returns a Future object. The caller can use its get method to wait for the operation or cancel method to try to cancel the operation. 

Future has the following methods: isDone() : Checks if the computation is completed. isCancelled() : checks if the task was cancelled before it is completed normally. get() : blocks for its completion and to retrieve the result of the computation. get​(long timeout, TimeUnit unit) : blocks if necessary for at most the given time for this future to complete, and then returns its result, if available. cancel() : cancels execution of this task if possible.

Java 8 Introduced a new Class for dealing with concurrency problems caused by Future like blockings, also implementing interfaces Runnable and CompletionStage.

Java 8 Concurrency new CompletonStage and CompletableFuture

Java 8 provided a new interface : – java.util.concurrent.CompletionStage  This interface defines a “stage” of possible asynchronous computation. All its methods return an instance of “CompletionStage” itself. This way multiple Completionstages can be chained together to complete a group of tasks.

Java 8 also introduced a new class: a new 

java.util.concurrent.CompletableFuture*
This class implements both: 1) Future  and 2) CompletionStage interfaces. This class provides static methods as starting points of concurrent operations as we will see below.

Here are some of the more common used methods:

1) - supplyAsync(Supplier supplier)  : Create a CompletableFuturence out of Suplier functional type.

2) runAsync(Runnable action) : Create a CompletableFuture instance out of Runnable functional type.

3) completeExceptionally(Throwable ex) : Return true if this invocation caused this CompletableFuture to transition to a completed state, else false.

4) thenRun(Runnable action)  : Execute the action when it completes normally.

5) thenApply(Function f) : Return a new CompletionStage.

6) thenAccept(Consumer action) : Return a new CompletionStage.

7) thenCombine(Future fu, Function foo) : Combines a  Future  and a  Function  with two arguments to process both results.

8) thenCompose(Function f) : To chain two Futures sequentially.

.

Its important to understand how the new threads are obtained. In fact by default those threads are obtained from "ForkJoinPool.commonPool()", but we have also the possibility to create our Executor (see: "Executors" API) and pass it to the CompletableFuture callbacks.

//Creating a new executor

Executor executor = Executors.newFixedThreadPool(5);

//then passing to CompletableFuture.supplyAsync(supplier, executor);

We can also launch new sync or async callback by calling "thenApply" operation. This callback offer to variants sync (same thread) or async(a new thread) -

 CompletableFuture thenApply(Function func)
 CompletableFuture thenApplyAsync(Function func)
 CompletableFuture thenApplyAsync(Function fn, Executor executor)

Code Example:

ExampleConcurrency.java
package pub.Java.src;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ExampleConcurrency {

	public static void main(String[] args) {
		
		
		/* Example of CompletableFuture */
		
		
		/*First completable Future*/
		
		CompletableFuture firstCompletableFuture = new CompletableFuture();
		String s = "Is there someone?  ";
		String r = null;
		try {
			
			 firstCompletableFuture.complete(": Yes! Hello Concurrent");;
			r =  firstCompletableFuture.get();
			s = s + r;
			 
		} catch (InterruptedException | ExecutionException e) {
	
			e.printStackTrace();
		}
		
		System.out.println("Result: " + s);
		
		
		/* "runAsync" : Example accepts a Runnable this time implemented with Anonymous Class */
		
		CompletableFuture cfuture = new CompletableFuture().runAsync(new Runnable() {
			
			@Override
			public void run() {
				String[] mesg = {"We","wait","in a" ,"different", "Thread"};
				int i;
				try {
					
					for(i = 0;i cfuture1 = new CompletableFuture().runAsync( () ->
  {		
	  String[] mesg = {"We","wait","in a" ,"different", "Thread"};
  
		int i;
		try {
			
			for(i = 0;i myLuckyNumberFuture = new CompletableFuture().supplyAsync(()->{
/* NOTE: STREAMS HAVE TO BE USED CAREFULLY IN CONCURRENT OPERATIONS
** In this case We need to use a Stream Supplier to get a new open Stream to invoke a new operation 
 * ONCE we have invoked a Terminal Operation (in this case ) that closes the Stream
 * That is the way to AVOID the:" java.lang.IllegalStateException: stream has already been operated upon or closed"
 * */
	Supplier> supplierOfStreamNums = ()->Stream.of(0,1,2,3,4,5,6,7,8,9).parallel();
	
	List luckList = supplierOfStreamNums.get().collect(Collectors.toList());	
	int ridx = (int) (Math.random()*10) % 10;
			
	return (Integer) luckList.get(ridx);

});	
/* We add the callback "thenApply"  Function to modify the result obtained before */
myLuckyNumberFuture.thenApply((   
		l ->{
Integer n = l;
	if(n%2==0)
		n = n +1;
	else
		n = n -1;
	return n;
}));
/* add callback "thenAccept" Consumer to consume the Integer generated, in this case by printing it */ 
myLuckyNumberFuture.thenAccept(n->System.out.println("My lucky number is (I'm in a different thread) : " + n));

//Invoking the blocking the CompletableFuture blocking operation "get"  */
Integer myLuckyNumber = -1;
try {
	 myLuckyNumber = myLuckyNumberFuture.get();

	System.out.println("My lucky number is : " + myLuckyNumber);

} catch (InterruptedException | ExecutionException e) {
	e.printStackTrace();
}



}

	

}





jueves, 21 de febrero de 2019

Interface inheritance in Java 8 an example

Java 8 interface allows default implementations, static method declaration and static final attributes declarations: Here we show an example (just to show the concept) of interface declaration and inheritance. We can add that with the default code, inherited attributes are hidden and we will show the final solution.

Example: In the code bellow we had to redeclare the inherited default method in each interface because the static attributes "from" and "to" were hidden by the super interface Locationable. You can try to remove the methods in subinterfaces to verify.

public interface Locationable {
 float from = 0;
 float to = 0;
 public  default int  closeTo( float other) {
  System.out.println(from + " and " + to ); 
  if( other>=from && other<=to)
    return 1;
   return -1;
  }
 
}

public interface Southern extends Locationable {
 float from = 100;
 float to = 1000;
 public  default int  closeTo( float other) {
  System.out.println(from + " and " + to ); 
  if( other>=from && other<=to)
    return 1;
   return -1;
  }
}

public interface Northern extends Locationable {
 float from = 5000;
 float to = 7000;
 public  default int  closeTo( float other) {
  System.out.println(from + " and " + to ); 
  if( other>=from && other<=to)
    return 1;
   return -1;
  }
}
public interface Midthern extends Locationable {
 float from = 1000;
 float to = 5000;
 public  default int  closeTo( float other) {
  System.out.println(from + " and " + to ); 
  if( other>=from && other<=to)
    return 1;
   return -1;
  }
}


public class Walker implements Southern,Northern,Midthern{
 
 
 public int closeTo(float pos) {
      int r = -1;
  if( (Southern.super.closeTo(pos) == 1)) {
  
   System.out.println("Hey I'm in the South!!");
   r = 1;
   }
   else if( Northern.super.closeTo(pos) == 1) {
    System.out.println("Hey I'm in the North!!");
    r = 1;
  }
   else if( Midthern.super.closeTo(pos) == 1) {
    System.out.println("Hey I'm in the Midlands!!");
    r = 1;
  }else
   System.out.println("Hey I'm in the Lymbus!!!!");
 
      return r;

 }

}


void interfaces_exec() {

Walker walker = new Walker();

for(int i= 0; i < 20; i++) {
 float pos = (float)(Math.random() * 7000) % 7000;
 
 walker.closeTo(pos);
}
 

domingo, 17 de febrero de 2019

JPA inheritance tecniques

This article discuses different techniques of JPA inheritance.

It explains: 1) Mapped superclass, 2) Table per class, 3)Single table, 4)Joined table.

It gives an example and a discussion about what technique is appropiate depending on the case.

Link:

https://thoughts-on-java.org/complete-guide-inheritance-strategies-jpa-hibernate/

sábado, 2 de febrero de 2019

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