Suggested Pages

Saturday, December 28, 2013

Decorator vs Strategy in a brief description

In this post I will share a good definition found on the WEB about the difference between the Strategy and Decorator Design Patterns.
As the name suggests the Strategy design pattern is dedicated to providing a strategy to the Client while the Decorator design pattern is dedicated to providing an enrichment of a certain functionality.

To be precise the two patterns respond differently to the following question:

Does the functionality need to be swapped or to be added?

  • The design patter Strategy is used to swap different (very different) strategy most of the times.
  • The design patter Decorator is used to add different behaviour (no necessary very different most of the times).

Motivations for the Design-Pattern Decorator

In this post I'm going to explain the motivations of the usage of the design patterns Decorator.
Many developers think that, the easy and common way to perform a new behaviour is the usage of a subclass, but this way of designing the software leads to a complex hierarchical model.
Imagine a requirement that says: "A manager has a different mail signature from the members of his team, He has an additional field : Telephone Number; the manager needs to send his telephone number in the mail.".

A common strategy may be to extend the actual object that composes the mail signature and add the new field phoneNumber.
MailSignature.java

...

public class MailSignature {

 private String name;
 
 private String surname;
 
 private String company;
 
        /*NEW FIELD*/
 private String phoneNum;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSurname() {
  return surname;
 }

 public void setSurname(String surname) {
  this.surname = surname;
 }

 public String getCompany() {
  return company;
 }

 public void setCompany(String company) {
  this.company = company;
 }

 public String getPhoneNum() {
  return phoneNum;
 }

 public void setPhoneNum(String phoneNum) {
  this.phoneNum = phoneNum;
 }

  
}


But let's consider a new requirement: "not all managers have a telephone number".
This implies that we have to consider different combinations over the attributes of the MailSignature object. Therefore a possible solutions can be a sort of Factory that creates the object MailSignature and valorizes it differently for the member of a team and for the manager. This is a "compile time" solution because all the possible combinations you need are planned and written in the Factory .

The described solution achieves the requirement but not in the best way. You should consider instead the Decorator design pattern that suggests you to identify a "Core Mail Signature" and to think to the possible enrichments as phoneNumber, city. In the next post I will describe the Design Pattern Decorator in details.

Saturday, November 16, 2013

Design Pattern: Template Method vs Strategy


In this post we will speak about the main differences between the Design Pattern Template Method and Strategy; we're going to compare the situations when it's recommended to use the former or the latter.
First step is the comparison shown in the following table:
TemplateStrategy
Design OrientationVerticallyHorizontally
Concreate MethodologyFillingOverriding
Time UsingRuntimeRuntime

Template is used when you are interested in specializing a portion of a new or existing algorithms/behaviours.
Strategy instead is used to replace a current strategy with another one.
Both Design Pattern are used to change a behaviour at runtime, but they work differently: Strategy encourages Replacement of behaviours while Template encourages the Filling portions of behaviours.

Even if a Strategy can be realized through the mechanism of subclassing, you are planning to override functionalities and not filling portion of behaviours.
You can notice that when you increase the hierarchy of your strategies, you are moving towards the same mechanism Template.

Another difference it's that Template is useful when in a complex existing domain you cannot modify legacy code easly, and a Strategy can be very risky. Instead use a Strategy in a new context may be a more clean and clear to start with. This is only a brief summary but in the next week I will post concreate examples.

Thursday, November 14, 2013

Java Generics Example

Suppose we have the following class:

 public interface Pc {}

  class Apple implements Pc {}

  class Win implements Pc {}

  class Iphone extends Apple {}

  class Ipod extends Apple {}



Generics Statements


The following statements are correct:

    List<Apple> apples=new LinkedList<Apple>();
   List<Iphone> iphones=new LinkedList<Iphone>();
   List<Ipod> ipods=new LinkedList<Ipod>();
Instead the following statements are not correct:

   List<Apple> apples=new LinkedList<Iphone>(); // Compiler error

   List<Apple> apples=new LinkedList<Ipod>(); // Compiler error
  


Wildcard

Wildcard allows methods, classes, constructors to accept any type as argument. For example public void doThis (List<?> list) means you can pass to this method any type.

Generics Lower Bound


It's possible to specify an lower bound to wildcard using this signature: ? super type.
In the following snippet, you can see a method doThis that has a parameter List<? super Apple> lista which means that you can pass to the method any super type of Apple.

  ...
  public static void doThis(List< ? super Apple> list) {

        list.add(new Apple());   
        list.add(new Iphone());  
        list.add(new Ipod());   
  }

  public static void main(String[] args){
       
        List<Apple> apples=new LinkedList<Apple>();
        List<Pc>pcs=new LinkedList<Pc>();
        doThis(apples);
        doThis(pcs);
  }



Generics Upper Bound


It's possible to specify an upper bound to wildcard using this signature: ? extends type.
In the following snippet, you can see a method doThis that has a parameter List<? extends Apple> lista which means that you can pass to the method any super type of Apple.

Example-3


  ...

   public static void doThis(List< ? extends Apple> list) {
     list.add(null);
     List<Apple>listAux=(List<Apple>)list; 
     listAux.add(new Iphone());  
     listAux.add(new Ipod());  
   }

   public static void main(String[] args){
     List<Iphone> iphones=new LinkedList<Iphone>();
     List<Ipod> ipods=new LinkedList<Ipod>();
     List<Apple> apples=new LinkedList<Apple>();
     doThis(iphones);
     doThis(ipods);
     doThis(apples);
  }





Generics Statements with Upper Bound and Lower Bound


The following snippet compiles successfully.

List<? extends Apple> apples= new LinkedList<Apple>();
List<? super Apple> apples= new LinkedList<Apple>();



Generics Class


Esempio-1

You cannot make a static reference to the non-static type T. T and E are instance and not static properties
class GenericsList<T,E>{
   static T t; // Compiler Error 
}


class GenericsList<T,E>{
   public static void doThis(T t){} // Compiler Error

}

Esempio-2

Compile successfully.

class GenericsList<T,E>{
 T t;
 E e;
}

Esempio-3

E can be any subclass of Number.

class GenericsList<T,E extends Number> {
  T t;
  E e;
}

Esempio-4

You cannot use super keyword at class level
class GenericsList<E super Integer> {        // Compiler Error
  E e;
}

Esempio-5

You cannot use ? keyword at class level

 class GenericsList<? extends Number> {      // Compiler Error
 } 



Generics Method


Esempio-1


Compile successfully.

class GenericsList<T extends Number> {
    T t;
    public <V extends Number> void doThis(V v) {
    }
}

Esempio-2

You cannot use super keyword in generics methods.

class GenericsList<T extends Number> {               
  T t;
  public <V super Integer> void doThis(V v){   // Compiler error
  }
}

Esempio-3

Compile successfully.

class GenericsList<T extends Number> {               

   public void doThis(List<T> lista){   
    for(Number n:lista){
     System.out.println(n);
   }
}
}

Esempio-4

Compile successfully.

class GenericsList<T extends Number> {               

   public void doThis(List<T> lista){   
     for(Number n:lista){
       System.out.println(n);
   }
}

Monday, April 29, 2013

Singleton Design Pattern

In these days, I was about to write a post on the ways to write a Singleton Design Pattern, when I found a wonderful internet page that explain it. So I'd like to make you know this subject giving the link that explain the Singleton Design Pattern

http://www.ibm.com/developerworks/java/library/j-dcl/index.html.

Tuesday, March 19, 2013

Select for Update

A select for update is often use as a semaphore on your database. If you plan a transaction with a select for update, you are avoiding the other transactions to get a read o write lock on the accessed rows; at this way you are implementing a sort of semaphore that is released only when the transaction ends.

Maven Dependencies Plugin

In this post I will show an example of usage of the dependency plugin, that can be used when you want to make a check of your project dependencies. The dependency plugin has two main goals:
  • dependency:resolve
  • dependency:tree

dependency:resolve


The goal mvn dependency:resolve permits to see all dependencies of an artifact and its related features; for example it shows the scope of your dependency artifacts.
A common situation to use this goal is when you are interested to verify which jars are in WEB-INF/lib of your deployed war. If you run mvn dependency:resolve, you can see if your dependencies artifact are provided or compile and make a quick check on your dependencies. Here you are an example of output of this goal:

a@b:  cd myproject

a@b:  ls
pom.xml  src  target

a@b:  dependency:resolve



[INFO] [dependency:resolve {execution: default-cli}]
[INFO] 
[INFO]    The following files have been resolved:
[INFO]    antlr:antlr:jar:2.7.7:compile
[INFO]    aopalliance:aopalliance:jar:1.0:compile
[INFO]    asm:asm:jar:3.3.1:compile
[INFO]    cglib:cglib:jar:2.2.2:compile
[INFO]    ch.qos.logback:logback-classic:jar:1.0.7:compile
[INFO]    ch.qos.logback:logback-core:jar:1.0.7:compile
[INFO]    com.caucho:hessian:jar:4.0.7:compile
[INFO]    com.google.code.spring-crypto-utils:spring-crypto-utils:jar:1.3.0:compile
[INFO]    com.google.guava:guava:jar:13.0.1:compile
[INFO]    com.liferay.portal:portal-client:jar:6.1.20:provided
[INFO]    com.liferay.portal:portal-impl:jar:6.1.20:provided
[INFO]    com.liferay.portal:portal-service:jar:6.1.20:provided
[INFO]    com.liferay.portal:util-bridges:jar:6.1.20:provided
[INFO]    com.liferay.portal:util-java:jar:6.1.20:provided
[INFO]    com.liferay.portal:util-taglib:jar:6.1.20:provided
[INFO]    com.mchange:c3p0:jar:0.9.2-pre5:compile
[INFO]    com.mchange:mchange-commons-java:jar:0.2.3:compile
[INFO]    com.oracle:ojdbc:jar:6:provided
[INFO]    com.sun.xml.bind:jaxb-impl:jar:2.1.11:compile


dependency:tree


The goal dependency:tree permits to see the all tree of dependencies of an artifact. The output of this goal is a tree that shows the origin of your dependencies.
Here you are an example of output of this goal:

a@b:  cd myproject

a@b:  ls
pom.xml  src  target

a@b:  dependency:tree


[INFO] +- myartifact:myproject:myversion:compile
[INFO] |  +- javax.xml:jaxrpc-api:jar:1.1:compile
[INFO] |  +- org.apache.cxf.xjc-utils:cxf-xjc-runtime:jar:2.6.0:compile
[INFO] |  |  \- javax.xml.bind:jaxb-api:jar:2.2:compile
[INFO] |  |     +- javax.xml.stream:stax-api:jar:1.0-2:compile
[INFO] |  |     \- javax.activation:activation:jar:1.0.2:compile
[INFO] |  +- org.apache.cxf:cxf-api:jar:2.6.0:compile
[INFO] |  |  +- org.codehaus.woodstox:woodstox-core-asl:jar:4.1.2:runtime
[INFO] |  |  |  \- org.codehaus.woodstox:stax2-api:jar:3.1.1:runtime
[INFO] |  |  +- org.apache.ws.xmlschema:xmlschema-core:jar:2.0.2:compile
[INFO] |  |  +- org.apache.geronimo.specs:geronimo-javamail_1.4_spec:jar:1.7.1:compile
[INFO] |  |  \- wsdl4j:wsdl4j:jar:1.6.2:compile
[INFO] |  +- org.apache.cxf:cxf-rt-frontend-jaxws:jar:2.6.0:compile
[INFO] |  |  +- xml-resolver:xml-resolver:jar:1.2:compile
[INFO] |  |  +- asm:asm:jar:3.3.1:compile

Monday, February 25, 2013

Implicit Lock : Object Lock and Class Lock

Both Object Locks and Class Locks are called implicit locks because the developer hasn't to create a lock object explicitly.

Object Lock


In Java an implicit lock is associated with each object and it is used to synchronize threads on the object's state. The object that has to synchronize thread accesses to its state, it's called: Monitor. To perform synchronization using implicit object lock, developers have to use the synchronized keyword on instance methods.
Simply when a thread calls a synchronized method of an object, it has to acquire the object lock. Suppose a thread t1 tries to call a synchronized method, it tries to acquire the object lock. If another thread t2 tries to call a synchronized methods on the same object, it has to acquire the same object lock. if the lock was acquired by the thread t1, the thread t2 must wait until the thread t1 will release the lock.
In the following code we'll see an example of a Monitor (Monitor.java) that has an instance variable counter. This variable represents a shared variable for the threads MyThread. In order to avoid interference among threads it has been used implicit object lock of Monitor object.

Monitor.java

public class Monitor {

 private int counter;

 public synchronized int getCounter() {
  System.out.println("getCounter():"+counter);
  return counter;
 }

 public synchronized void setCounter(int counter) {
  System.out.println("setCounter():"+counter);
  this.counter = counter;
 }
  
}

As you can see the thread shown below tries to access to the Monitor state using getCounter() and setCounter() methods. These methods protect the so called Critical Region, preventing these two threads to access the monitor instance variable at the same time. Monitor methods use an intrinsic reentrant lock because the thread that has acquired the object lock, can still acquire the same lock even if it has not released the previus lock acquired.

MyThread.java
package com.simonefolinoblogspot.synchronization;

public class MyThread extends Thread {

 private Monitor monitor;
 
 public MyThread(Monitor monitor) {
  this.monitor = monitor;
 }

 @Override
 public void run() {
     int counter = monitor.getCounter();
     counter++;
     monitor.setCounter(counter);
 }
 
}



Main.java
package com.simonefolinoblogspot.synchronization;

public class Main {

 public static void main(String[] args) {

  Monitor monitor=new Monitor();
  MyThread t1=new MyThread(monitor);
  MyThread t2=new MyThread(monitor);
  t1.start();
  t2.start();
 }
}



Class Lock


While there is a lock object for each objects, class lock is only one for a class. It acts at the same way as Object Lock from the acquiring point of view.

Synchronized Statements


Another way to create synchronized code is to use a block synchronized . This mechanism allows developers to explain the object of which is to acquire the lock.
In the following code you can see the previus Monitor implemented by Synchronized Statements.
Monitor.java
package com.simonefolinoblogspot.synchronization;

public class Monitor {

 private int counter;

 public  int getCounter() {
  synchronized(this){
      System.out.println("getCounter():"+counter);
  }
  return counter;
 }

 public  void setCounter(int counter) {
  synchronized(this){
    System.out.println("setCounter():"+counter);
    this.counter = counter;
  }

 }
  
}


About Synchronization


  • Implicit Object Lock are Reentrant Lock
  • Only static and instance method can use synchronized keyword
  • Constructors can't be synchronized : Only the thread that creates the object should access it during inizialization. Developers should take care on not leaving references to that object before completion

Suggested Pages