Showing posts with label patterns. Show all posts
Showing posts with label patterns. Show all posts

Friday, September 12, 2014

Transform if else (conditional) with polymorphism

Switch and consecutive if-else statements are not necessary anti-patterns, but you should consider using polymorphism in this situations, especially  if conditional is complex and long.
Sometimes when you refactor your code in this way, you actually learn something new about your data and make your code easier to follow.
Polymorphism also give you advantage when you have same conditional in through your code on several places and for example you want to introduce new branching, which in case of polymorphism will be just new type.

Let see it in example:
public class ConditionalPolymorphism {
    
    //smelly approach
    public int carSpeed(String car) {
        if ("Hyundai".equals(car)) {
            return 180;
        } else if ("Mazda".equals(car)) {
            return 160;
        } else if ("Nissan".equals(car)) {
            return 190;
        } else {
            throw new InvalidParameterException(
                    "Parameter not legal: " + car);
        }
    }

    //polymorphic approach
    public int carSpeed(Car car) {
        return car.speed();
    }

    public static void main(String[] args) {
        ConditionalPolymorphism conditionalPolymorphism = 
                new ConditionalPolymorphism();
        System.out.println(
                conditionalPolymorphism.carSpeed("Hyundai"));
        System.out.println(
                conditionalPolymorphism.carSpeed(new Hyundai()));
    }
}

interface Car {
    int speed();
}

class Hyundai implements Car {

    public int speed() {
        return 180;
    }
}

class Mazda implements Car {

    public int speed() {
        return 160;
    }
}

class Nissan implements Car {

    public int speed() {
        return 190;
    }
}
This is pretty simple and naive example, but you can see basic mechanics behind it. Polymorphic code is more elegant and it is written more in object-oriented manner. Also in this example you can omit parameter check, which will further reduce code complexity.

Sunday, May 19, 2013

Desing Patterns in Java - builder pattern

Static factories and constructors share a limitation: they do not scale well to large
numbers of optional parameters.
Consider the case of computer configuration builder. There are parts that are essential in this build, but also there are optional parts.

There number of ways that developers usually try to approach this problem. First is  telescopic constructors where you need to create constructor for each of optional parameter. This approach has obvious disadvantages (ugly code, lot of work). Second approach is to use JavaBeans in which you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest. There are two problems with this approach. First is that JavaBean may be in an inconsistent state partway through its construction. Second is that this pattern pre-cludes the possibility of making a class immutable.
There is however third approach that is very elegant and can create immutable objects. It is a form of the Builder pattern.Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Here is how it looks like:
public class ComputerConfigurator {    
    private final int sizeOfRam;
    private final int sizeOfHdd;
    private final int processorSpeed;    
    private final int dedicatedGpuSpeed;
    private final boolean waterCooling;
    
    public static class Builder {
        //Required params
        private final int sizeOfRam;
        private final int sizeOfHdd;
        private final int procesorSpeed;        
        //Optional params
        private int dedicatedGpuSpeed;
        private boolean waterCooling;

        public Builder(int sizeOfRam, int sizeOfHdd, int procesorSpeed) {
            this.sizeOfRam = sizeOfRam;
            this.sizeOfHdd = sizeOfHdd;
            this.procesorSpeed = procesorSpeed;
        }
        
        public Builder dedicatedGpuSpeed(int val) {
            dedicatedGpuSpeed = val;
            return this;
        }
        
        public Builder waterCooling(boolean val) {
            waterCooling = val;
            return this;
        }
        
        public ComputerConfigurator build() {
            return new ComputerConfigurator(this);
        }
        
    }
    
    private ComputerConfigurator(Builder builder) {
        sizeOfRam = builder.sizeOfRam;
        sizeOfHdd = builder.sizeOfHdd;
        processorSpeed = builder.procesorSpeed;
        dedicatedGpuSpeed = builder.dedicatedGpuSpeed;
        waterCooling = builder.waterCooling;
    }
}
The builder’s setter methods return the builder itself so that invocations can be chained. Here’s how the client code looks:
public class Main {
    
  public static void main(String[] args) {
    ComputerConfigurator firstComputerConfigurator = new ComputerConfigurator.
            Builder(2, 40, 3000).
            dedicatedGpuSpeed(1000).build();
        
    ComputerConfigurator secondComputerConfigurator = new ComputerConfigurator.
            Builder(2, 40, 3000).
            dedicatedGpuSpeed(1000).waterCooling(true).build();
  }    
}

Saturday, May 18, 2013

Desing Patterns in Java - Visitor

Visitor lets you define a new operation (method) on object without changing the classes (interface) of the elements on which it operates. This is the essence of visitor patter. The name "Visitor" is misleading and this pattern has noting to do with visiting, iteration or something like that. If you need to perform operations across a disparate set of objects, Visitor might be the pattern for you. Let see how does it work.

So let's presume we have have some disparate object structure and we want to run one operation on each object of this structure.
Here is how it works then:
The core of this pattern is Visitor interface. This interface defines a visit operation for each type in the object structure. The object (one object from structure) interface simply defines an accept method to allow the visitor to run some action over that object. This operation is here to to allow the visitor access to the object.

Here we have example that will calculate average Per Seat Fuel Economy for different type of vehicles. Calculation is quite simple: consumption / number of seats. Each of vehicle is represented with simple POJO's. Each of this object have one accept method so we have access to object through unified interface.

Interfaces:
public interface Visitable {
    
    void accept(Visitor visitor);
    
}

public interface Visitor {
    
    void visit(Bike bike);
    void visit(Bus bus);
    void visit(Car car);
    
}
Simple POJO's.
public class Bike implements Visitable {
    
    private int consumption;
    
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
    
    public Bike(int consumption) {
        this.consumption = consumption;
    }
    
    public int getConsumption() {
        return consumption;
    }  
            
}

public class Bus implements Visitable {
    
    private int numberOfSeats;
    private int litersConsumption;

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
    
    public Bus(int numberOfSeats, int litersConsumption) {
        this.numberOfSeats = numberOfSeats;
        this.litersConsumption = litersConsumption;
    }
   
    public int getNumberOfSeats() {
        return numberOfSeats;
    }

    public int getLitersConsumption() {
        return litersConsumption;
    }   
    
}

public class Car implements Visitable {
    
    private int consumption;
    private int weight;
    private int seats;
    
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }

    public Car(int consumption, int weight, int seats) {
        this.consumption = consumption;
        this.weight = weight;
        this.seats = seats;
    }    
    
    public int getConsumption() {
        return consumption;
    }
   
    public int getWeight() {
        return weight;
    }

    public int getSeats() {
        return seats;
    }
}
Although this objects don't know how to calculate average per seat consumption we will learn them how to do that without even touching them:
public class EfficiencyVisitor implements Visitor {
    
    private int efficiency;
    
    @Override
    public void visit(Bike bike) {
        efficiency += bike.getConsumption() / 2;
    }

    @Override
    public void visit(Bus bus) {
        efficiency += bus.getLitersConsumption() / bus.getNumberOfSeats();
    }

    @Override
    public void visit(Car car) {
        efficiency += car.getConsumption() / car.getSeats() ;
    }

    public int getEfficiency() {
        return efficiency;
    }     
    
}
Client:

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        int averageConsumptionPerSeat = 0;
        
        List <Visitable> vehicles = new ArrayList<>();
        
        Car mazda = new Car(6, 1024, 5);
        vehicles.add(mazda);
        Car skoda = new Car(7, 1200, 4);
        vehicles.add(skoda);
        Bus merc = new Bus(60, 30);
        vehicles.add(merc);
        Bike suzuki = new Bike(4);
        vehicles.add(suzuki);
        
        EfficiencyVisitor efficiencyVisitor = new EfficiencyVisitor();
        
        for (Visitable vehicle : vehicles) {
            vehicle.accept(efficiencyVisitor);
            averageConsumptionPerSeat += efficiencyVisitor.getEfficiency();
        }
        
        System.out.println(averageConsumptionPerSeat / vehicles.size());
    }
}

Best thing about this is that we can easily add new vehicle types or change existing methods without changing interface or methods on "old" vehicle types.

The whole point of this pattern is to clean up your code. It allow you to separate  certain logic from the elements themselves, keeping your data classes simple.

Thursday, April 25, 2013

Desing patterns in Java - Facade


Facade Pattern is structural pattern. It basically hide complexity, so I tend to call it "good sense pattern". It also decouples code, which is good thing. But you should not overuse Facade pattern in your applications.
 
Similar like to much abstraction is considered harmful for code readability, same thing apply to too much simplification (because you basically add layer on top layer and you introduce complexity).

Session facade is useful in situations where it encapsulate the complexities between the client and the server interactions. It manages business objects and provides uniform service access layer to clients. It basically represent centralized peace that minimize method calls over network, exposes uniform interface and managing security and transactions in one place.

Sunday, December 30, 2012

Desing Patterns in Java - Command pattern

Description

Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. (A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation.

This pattern allows the requester of a particular action to be decoupled from the object that performs the action.

This pattern encodes the details needed to send a message to an object. Such messages can be invoked along different points of time or location in a general way without having to hard-code its details. It allows messages to be invoked one or more times, or passed along to different parts of the system or multiple systems without requiring the details of a specific invocation to be known before execution.

Object references VS function pointers

Some languages (C for example) support function pointers facilities that allow programs to store and transmit the ability to invoke a particular function. Java does not provide function pointers, but object references together with dynamic loading and binding mechanism can be used to achieve a similar effect. This is where command pattern comes into play.

Example

We will use simple remote control for CD Player as example. This simple CD Player support only basic commands (Play, Stop and Pause), but that is good enough for out example of command pattern.

//Cd Player that will be controlled by remote control
public class CdPlayer {

  public enum State {
    PAUSE, PLAY, STOP
  }

  private State state;

  public void pause() {
    state = State.PAUSE;
  }

  public void stop() {
    state = State.STOP;
  }

  public void play() {
    state = State.PLAY;
  }

  public State getState() {
    return state;
  }

}
//Simple command interface.
public interface Command { 
  void execute(); 
}
//Cd Player remote control that will control Cd Player through button press.
public class CdPlayerRemoteControl {
 
  private Command command;
 
  public void setCommand(Command command) {
    this.command = command;
  } 
 
  public void pressButton() {
    command.execute();
  }
}

//Cd Player play command.
public class CdPlayerPlayCommand implements Command {

  private CdPlayer cdPlayer;
 
  public CdPlayerPlayCommand(CdPlayer cdPlayer) {
    this.cdPlayer = cdPlayer;
  }
 
  public void execute() {
    cdPlayer.play();
  }
 
}
//Cd Player pause command.
public class CdPlayerPauseCommand implements Command {

  private CdPlayer cdPlayer;
 
  public CdPlayerPauseCommand(CdPlayer cdPlayer) {
    this.cdPlayer = cdPlayer;
  }
 
  public void execute() {
    cdPlayer.pause();
  }
 
}
//Stop command...
public class CdPlayerStopCommand implements Command {
 
  private CdPlayer cdPlayer;
 
  public CdPlayerStopCommand(CdPlayer cdPlayer) {
    this.cdPlayer = cdPlayer;
  }
 
  public void execute() {
    cdPlayer.stop();
  }
 
}
//Client class that uses remote control for CD Player control.
public class Client {
 
  public static void main(String[] args) {
    CdPlayerRemoteControl cdPlayerRemoteControl = new CdPlayerRemoteControl();  
    CdPlayer cdPlayer = new CdPlayer();
    
    Command play = new CdPlayerPlayCommand(cdPlayer);
    Command pause = new CdPlayerPauseCommand(cdPlayer);
    Command stop = new CdPlayerStopCommand(cdPlayer);
  
    //Play music  
    cdPlayerRemoteControl.setCommand(play);
    cdPlayerRemoteControl.pressButton();
    
    //Stop music
    cdPlayerRemoteControl.setCommand(stop);
    cdPlayerRemoteControl.pressButton();
  
    //prints STOP
    System.out.println(cdPlayer.getState());
  
  }
 
}

Tuesday, April 19, 2011

Design patterns in Java - Decorator

Introduction


As holy grail of Java OO design book (GoF - Elements Of Reusable OO Software) say: "Decorator design pattern is intended to add additional responsibility to an object dynamically. This design pattern is also known as Wrapper".

So in another words this design pattern enable object inheritance at runtime. It achieve this by using interface inheritance and class composition.

Implementation

In Java classes java.io package also use decorator design pattern. For example:

File f = new file("d:\something.txt");
//Here FileInputStream "inherits" File class.
FileInputStream is = new FileInputStream(f);
//Here we add buffering capability to FileInputStream using decorator.
BufferedInputStream bis = new BufferedInputStream(fi);

I must point out that Decorator design pattern can also be used to remove responsibility from object (our example will not include this case).

Following code represent simple implementation of this pattern in Java.

Interface that will be our default "object". This object will be decorated (extended).
/**
 * Basic phone that can do only basic ringing.
 */
public interface IPhone {
    
    void announceCall();

    void announceMessage();

}
Decorator interface that extends our default "object" interface. So instead of static inheritance in implementation we create interface inheritance.
/**
 * Decorator that adds additional functionality to basic Phone.
 */
public interface IPhoneDecorator extends IPhone {

    void vibrate(int milliseconds);

    void flashLED();
}
Concrete implementation of our "default" object (nothing interesting, just simple interface implementation).
public class Phone implements IPhone {

    /*
     * This Phone announce call only by ringing.
     */
    public void announceCall() {
        System.out.println("Ring!");
    }

    /*
     * Phone announce message by makeing some sound.
     */
    public void announceMessage() {
        System.out.println("Make a sound!");
    }
}
Concrete decorator implementation that implements all operations. It delegate part of functionality to our "default" object and add more functionality of his own. It has one filed named phone which represent our "default" object implementation to which we will delegate stuff.
/**
 * Concrete decorator class that adds additional functionality.
 * @author jan.krizan
 */
public class UpgradePhoneDecorator implements IPhoneDecorator {

    private IPhone phone;

    /**
     * Constructor through which client put
     * instance that will be decorated.
     * @param phone
     */
    public UpgradePhoneDecorator(IPhone phone) {
        super();
        this.phone = phone;
    }

    public void vibrate(int milliseconds) {
        System.out.println("Vibrating for " + milliseconds + " milliseconds.");
    }

    public void flashLED() {
        System.out.println("Make a LED flash!");
    }

    public void announceCall() {
        //Delegate basic functionality to Phone clase.
        phone.announceCall();
        //Add additional functionality.
        vibrate(1500);
    }

    public void announceMessage() {
        //Delegate basic functionality to Phone clase.
        phone.announceMessage();
        //Add additional functionality.
        flashLED();
    }
}
We can now see what can our "default" object do before and after it has been decorated. You can see that we provide phone instance to decorator constructor and by using polymorphism (dynamic binding) we delegate basic work to our "default" object.
public static void main(String[] args) {
        IPhone oldPhone = new Phone();
        System.out.println("What can old phone do!");
        oldPhone.announceCall();
        oldPhone.announceMessage();
        System.out.println();
        IPhoneDecorator decoratedPhone = new UpgradePhoneDecorator(oldPhone);
        System.out.println("What can new phone do!");
        decoratedPhone.announceCall();
        decoratedPhone.announceMessage();
    }

Hope you like this!


Here is output (example uses ANT):
run:
What can old phone do!
Ring!
Make a sound!

What can new phone do!
Ring!
Vibrating for 1500 milliseconds.
Make a sound!
Make a LED flash!
BUILD SUCCESSFUL (total time: 0 seconds)

Sunday, January 16, 2011

Design Patterns in Java (Java EE) - Model View Controller (aka MVC)

MVC Concept

MVC pattern is quite simple and very useful pattern for context representation. Representation can be of any kind (text based consoles - OBERON OS for example, or modern GWT based applications).

Please download sample code from my google code repository.

MVC approach divides components into three kinds:
Model that holds model of data we wish to represent, it represents the business logic of an application. It encapsulate business rules into components (JavaBeans in JSP/Servlets MVC application).
View that present data on screen (render model). Model is rendered in such way that it enable interaction with model data and model operations.
Controller that react to user input and based on what is selected it make decisions for making specific calls on model components (update model for example) and selecting appropriate view for displaying updated or existing data.

Because of limitations of web architecture (page are refreshed only when use request them), we cannot use push model of MVC. With this model data has "power" to updates model. For example if you have two simultaneous users that are accessing same web page and same data, if one of them update part of the data, that update will be available immediately to other user. We all know that this does not happen, but there are some tweaks (please see this oracle description for techniques that enable this - long polling, etc.).

Ok, but what can we do to have full functional MVC design in our JEE application. We can (as many framework do) use pull model design concept. With this model view pulls data from model as user initiate request. Or you can wait for WebSocket to be properly (by complying to HTML5 spec.) implemented by all browser vendors and as we know until now, all browser are beautifully aligned with W3C spec, so no problem here! :)
Note: If you still want to use some of cutting edge HTML5 stuff, please use libraries (like jQuery, prototype) right away because then when HTML5 spec changes (and it will!) you just need to upgrade you library. :)
I will also do some tutorials later on jQuery (maybe jQuery mobile?) and full fat client JavaScript application that can leverage HTML5 stuff.

Whatever strategy we use, MVC architecture still delivers its key benefits. This are:

  • Each component has clear responsibility;
  • models contain no view-specific code;
  • view contain no control code or data-access code and concentrate on data display;
  • controllers create and updates models, they do not depend on particular view implementations.

MVC using JSP and servlets

Servlet are good at data processing (reading data, communication with database, invoking business service). JSPs on other hand are good at presentation of data (building HTML to present result of request). So it is natural to combine these two Java EE core concepts for MVC implementation.

The original request is handled by servlet. The servlet invokes the business services (we can use Spring for initializing business service object, but it will be overkill for this example) components which will perform data access and create beans to represent the result (this is the model). Then the server decides which JSP page is appropriate to present those particular result and forwards the request there (this is where JSP pages play they part - view). Servlet decide what business logic code applies and which JSP page should preset (so servlet is the controller).

Simple (but really simple) MVC example

In this example some user will chose product to buy on first page. When he select (or submit without selecting anything) product than the servlet RequestDispatcher (controller) will choose to which JSP page (view) will send request and put product transfer object - DTO (model) to request scope attribute.

Here are couple of images:
First image show list of products, second image show JSP page that is displayed after controller decide which view to show (you can see here that we do not have enough amount of that product on stock, so we suggest customer to buy another product).




Here is controller servlet code:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //get parameter
        String param = request.getParameter("productId");
        //check if null
        int productId = param != null ? Integer.parseInt(param) : 0;

        Product product = Product.findProduct(productId);

        String forwardAddress = "/NoProduct.jsp";

        if (product != null) {
            request.setAttribute("currentProduct", product);

            if (product.getAmount() < 10) {
                forwardAddress = "/LowAmount.jsp";
            } else if (product.getAmount() > 10) {
                forwardAddress = "/SufficientAmount.jsp";
            }
        }        
        RequestDispatcher dispatcher =
                request.getRequestDispatcher(forwardAddress);
        dispatcher.forward(request, response);
    }

As you can see, first we get selected product id (if any) and then we choose appropriate JSP page for that product based on it's amount. If user do not choose any product page "NoProduct.jsp" will be displayed.

Product class is quite simple (it's DTO with static initializing block):

package org.codingwithpassion.model;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author jan.krizan
 */
public class Product {

    private static Map products;

    /*
     * Execute on object create (only once).
     */
    static {
        products = new HashMap();

        products.put(1, new Product(1, "Square ball", 12, 122));
        products.put(2, new Product(2, "Invisible cup", 1223, 12234));
        products.put(3, new Product(2, "Vitamins", 1, 2));

    }
    private int id;
    private String name;
    private int price;
    private int amount;

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public Product(int id, String name, int age, int amount) {
        this.id = id;
        this.name = name;
        this.price = age;
        this.amount = amount;
    }

    /*
     * Required no-argument constructor.
     */
    public Product() {
    }

    public int getAge() {
        return price;
    }

    public void setAge(int age) {
        this.price = age;
    }

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public static Product findProduct(int id) {
        return (Product) products.get(id);
    }
}

Final remarks

It is not necessary to use MVC in whole web application (GOD servlet is not a good idea). You can use MVC on places you think you will get most from this pattern and on other places use simple JSP.

Controller servlet in MVC do not create any output, the output should be handled only by JSP pages (or any other view technology). So remember, servlet do not call response.setContentType, response.getWriter, etc.

You can forward (using dispatcher) or you can redirect (using request.sendRedirect) to transfer control from controller servlet to view (JSP page).
When you use forward then control is transfered entirely on the server (no network traffic) and user do not see that address of destination JSP page. You should put JSP pages into WEB-INF if those JSP pages make sense only in the context controller servlet.
When you use redirect then control is transfered by sending client a 302 status code together with Location response header. This require an additional network traffic and user sees the address of destination JSP page.

Final remark (of final remarks) is about pointing out that you are not limited for usingrequest scope, but also you can use session or application scope, but remember to synchronize scope declaration in servlet and JSP page.

Out of the box MVC frameworks

I must admit that I'm not a big fan on Java web frameworks. I understand that they help in organization and work load distribution in complex development undertaking, but for small project they are obviously overkill. They bring complexity but on other hand they bring good patterns and common sense guidelines.

This Model-2 MVC architecture is quite powerful and good as core pattern for most simple to mid size project. If you are developing reasonably complex Java web application please see Struts 2 or Spring MVC (the most popular out of action-based frameworks).

Thursday, November 4, 2010

Design Patterns in Java - Abstract Factory and Factory Method

Introduction

These factory design patterns belong to group of patterns that are named "creational". These patterns helps in instantiation of classes. So with this pattern we separate creation process from object usage (If you think about if creation of new classes is kind of low level stuff like allocating memory for pointer...I now that it is not...but I just give a small analogy...whatever). So the name "factory" is derived from "factory of objects". In this way we do not use "new" keyword in object creation, but we use this pattern. With this pattern we choose which concrete class we will use at runtime and also in this way we can introduce new classes in our code without changing our base code.

This is all common sense to me (plain polymorphism in use...nothing more), and remember: Always program to interface not concrete class (don't you forget this!).

I will show same example for both patterns. In this example we need to decorate string text with some special characters. Nothing fancy...for example: from "decorate me" we will have "** decorate me **". So we just put two stars at end and beginning. All my examples are simple, because I want to concentrate at topic and at current problem.

Factory method

/**
 * Simple example of Factory Method pattern.
 * @author jan.krizan
 */
interface Decorator {

    String doDecorating(String str);
}

class StarDecorator implements Decorator {

    public String doDecorating(String str) {
        return "** " + str + " **";
    }
}

class OtherDecorator implements Decorator {

    public String doDecorating(String str) {
        return "<<|-- " + str + " --|>>";
    }
}

public class Factory {

    public static final int STAR_DECORATOR = 1;
    public static final int OTHER_DECORATOR = 2;

    public static Decorator createSpecificDecorator(int i) {
        if (i == STAR_DECORATOR) {
            return new StarDecorator();
        } else if (i == OTHER_DECORATOR) {
            return new OtherDecorator();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {

        String nonDecoratet = "Please decorate me!";

        Decorator decorator = createSpecificDecorator(STAR_DECORATOR);

        System.out.println(decorator.doDecorating(nonDecoratet));
    }
}
Output of this example is: "** Please decorate me! **". No kidding...really! :) Ok, never mind that, let's comment it!:
(5 - 8) We first create interface.
(10 - 15 and (17 - 22) Then we implement that interface.
As you can see all straight forward for now.
(29 - 37) This represent factory that will choose (base on input parameter) which
class to instantiate.
Then we test the stuff in main.

Abstract factory

Abstract factory is (as you can figure out from its name) in higher level at higher level of abstraction. In abstract factory event the factory is abstract (interface or abstract class) and we choose factory at runtime (not the "working" class). The factory will "know" which class it need to instantiate in order to fulfill job in hand.

/**
 *
 * Simple example of Abstract Factory pattern.
 * @author jan.krizan
 */
interface DecoratorFactory {

    Decorator createDecorator();
}

class StarDecoratorFactory implements DecoratorFactory {

    public Decorator createDecorator() {
        return new StarDecorator();
    }
}

class OtherDecoratorFactory implements DecoratorFactory {

    public Decorator createDecorator() {
        return new OtherDecorator();
    }
}

interface Decorator {

    String doDecorating(String str);
}

class StarDecorator implements Decorator {

    public String doDecorating(String str) {
        return "** " + str + " **";
    }
}

class OtherDecorator implements Decorator {

    public String doDecorating(String str) {
        return "<<|-- " + str + " --|>>";
    }
}

public class Factory {

    public static final int STAR_DECORATOR = 1;
    public static final int OTHER_DECORATOR = 2;

    public static DecoratorFactory createSpecificDecorator(int i) {
        if (i == STAR_DECORATOR) {
            return new StarDecoratorFactory();
        } else if (i == OTHER_DECORATOR) {
            return new OtherDecoratorFactory();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {

        String nonDecoratet = "Please decorate me!";

        DecoratorFactory decoratorFac = createSpecificDecorator(OTHER_DECORATOR);

        Decorator decorator = decoratorFac.createDecorator();

        System.out.println(decorator.doDecorating(nonDecoratet));
    }
}

Here we see that code is almost same as for Factory Method. There are just small but important differences:
(11 - 16 and 18 - 23) Here we create another layer, this seem like waste of code, but this can be beneficiary if for example we have more than one method to implement and we don't want all method to implement (just subset). In this way we in our concrete classes implement only those method we need for our work and ignore other. We can extends one interfaces to accomplish this. If this sound a little bit confusing for you, don't worry and search some good example of Abstract Factory and you will see what I talking about. For example here.

Creating class instances is similar and also testing is similar, we just have another step and that is to obtain Decorator class through createDecorator method.

Using Abstract Factory pattern for simple example like this is stupid and overkill, but I want to show differences between the two patterns.

You can download code for this two examples from here.

Monday, October 4, 2010

Design Patterns in Java - Template Method

Introduction

This is first article about OO design patterns, we will start with the most useful pattern.
Template method (GoF - Gang Of Four) present good example of using concrete inheritance. If you ask me, using inheritance in this way is far more productive than using concrete inheritance for code reuse. Everything you think you can do with concrete inheritance, you can do also with plain object composition. But, ok...never mind about that, let's write something about template method pattern.

You can download example of this Java code from my repository on google code:
https://code.google.com/p/codingwithpassionblog/source/browse/trunk/src/org/codingwithpassion/patterns/templateMethod/DecorateData.java

Usage

This pattern address common problem: we know the steps of an algorithm and the order in which they should be performed, but we don't know (or don't care) how to perform all of the steps. Template method encapsulate individual steps we don't know how to perform to abstract methods in abstract superclass. Concrete subclass will implement these methods. These method represent individual steps in an algorithm. In this way, superclass (abstract one) will control the flow (workflow) of algorithm. Subclasses just fill the gaps in superclass algorithm.

In this example this centralized workflow logic is example of inversion of control. In this approach the superclass is calling methods from subclass. This is fundamental approach for lean and clean code and code reuse.

Let's see example (this example can be put in one file for easy testing - it have only one public class):
/**
 * Abstract implementation -- class that control flow.
 * Describe algorithm for generic object creation.
 *
 */
abstract class CreateObject {
 
 protected Object[] datas = {"Kimmi", "Zuco", 1, 21};
 
 public void setData(Object[] data) {
  CreateObject.this.datas = data;
 }
 
 /**
  * Algorithm that control flow (IOC - Inversion of Control).
  * @return Object String representation. 
  */
 public String decorate() {
  StringBuilder sb = new StringBuilder();
  objectStart(sb);
  
  for (int i = 0; i < datas.length; i++) {
   Object data = datas[i];
   if (data instanceof String) {
    stringValue(sb, data, i);
   } else if (data instanceof Integer) {
    numberValue(sb, data, i);
   }
  }
  objectEnd(sb);  
  return sb.toString();
 }
 
 //these classes (down) need to be implemented in subclasses.
 abstract void objectStart(StringBuilder sb);
 
 abstract void objectEnd(StringBuilder sb);
 
 abstract void stringValue(StringBuilder sb, Object value, int indx);
 
 abstract void numberValue(StringBuilder sb, Object value, int indx);
 
}

/**
 * Object creation for JSON objects;
 *
 */
class JSONObject extends CreateObject {
 
 protected void objectStart(StringBuilder sb) {
  sb.append("\"Object\":").append("\n{");
 }
 
 protected void objectEnd(StringBuilder sb) {
  sb.append("\n}");
 }
 
 protected void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append("\"").append(value).append("\",")
    .append("\n");
    
 }
 
 protected void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append(value).append(",")
    .append("\n");
 }
}

/**
 * Object creation for xml objects.
 *
 */
class XmlObject extends CreateObject {
 
 protected void objectStart(StringBuilder sb) {
  sb.append("").append("\n");  }    protected void objectEnd(StringBuilder sb) {   sb.append("");
 }
 
 protected void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
 protected void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
}

public class DecorateData {
 
 public static void main(String[] args) {
  CreateObject xml = new JSONObject();
  System.out.println(xml.decorate());
 }
 
}
Lot of stuff going of there, but don't worry. Main thing to understand is flowing:

6 - 32: We declare abstract class that encapsulate workflow of creating string representation of object.
18 - 32: Implementation of algorithm - workflow. This algorithm use abstract methods (35 - 42) that need to be implemented by subclasses (He calls these methods from subclasses, hence Inversion of Control paradigm).
49 - 73: First implementation that implement abstract method and create JSON string object representation...nothing fancy.
79 - 111: Same thing, but for Xml Object representation.

112 - 120: Testing...

Conclusion

Such patterns as this offer good paradigm for separation of concerns. We can for example create superclass that will concentrate on business logic (and flow of that business logic), and use subclasses for primitive operation (technical stuff, JPA, servlets, parsing, JDBC,...).

It is useful to use Template method patter to capture an algorithm in one place, but deffer implementation of simple steps to subclasses. This has the potential to avoid bugs, by getting tricky operations right once in superclass and simplifying user code.

Please check post about Strategy design pattern that is very similar like Template, but instead abstract class uses interface.

Design Patterns in Java - Strategy

Introduction

Strategy pattern is alternative to Template method. But in case of Strategy pattern we use interface instead of abstract class. Please read more about this type of encapsulating logic in post about Template method if you are interested. Here we will here just show differences in correlation to TM.

You can download example of this Java code from my repository on google code:
https://code.google.com/p/codingwithpassionblog/source/browse/trunk/src/org/codingwithpassion/patterns/strategyMethod/DecorateData.java

Example

So in this case, class that knows the algorithm is not an abstract superclass, but a concrete class that uses a helper that implements an interface defining individual steps. You will use this type of pattern if you need to use concrete inheritance for some other purpose (because as we all knows Java and similar languages does not support multiple inheritance), or you just like this approach better because you are not forced to inherit from abstract class. Whatever is you reason, here is example:
/**
 * Concrete Object implementation. 
 * Here we implement workflow.
 */
class CreateObject {
 
 protected Object[] datas = {"Kimmi", "Zuco", 1, 21};
 
 public void setData(Object[] data) {
  CreateObject.this.datas = data;
 }
 
 /**
  * Algorithm that control flow (IOC - Inversion of Control).
  * @return Object String representation. 
  */
 public String decorate(DecoratorHelper helper) {
  StringBuilder sb = new StringBuilder();
  helper.objectStart(sb);
  
  for (int i = 0; i < datas.length; i++) {
   Object data = datas[i];
   if (data instanceof String) {
    helper.stringValue(sb, data, i);
   } else if (data instanceof Integer) {
    helper.numberValue(sb, data, i);
   }
  }
  helper.objectEnd(sb);  
  return sb.toString();
 }   
}
/**
 * Helper interface to which we defer individual steps.
 *
 */
interface DecoratorHelper {
 
 void objectStart(StringBuilder sb);
 
 void objectEnd(StringBuilder sb);
 
 void stringValue(StringBuilder sb, Object value, int indx);
 
 void numberValue(StringBuilder sb, Object value, int indx);
}

/**
 * Object creation for JSON objects;
 *
 */
class JSONObject implements DecoratorHelper {
 
 public void objectStart(StringBuilder sb) {
  sb.append("\"Object\":").append("\n{");
 }
 
 public void objectEnd(StringBuilder sb) {
  sb.append("\n}");
 }
 
 public void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append("\"").append(value).append("\",")
    .append("\n");
    
 }
 
 public void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append(value).append(",")
    .append("\n");
 }
}

/**
 * Object creation for xml objects.
 *
 */
class XmlObject implements DecoratorHelper {
 
 public void objectStart(StringBuilder sb) {
  sb.append("").append("\n");
 }
 
 public void objectEnd(StringBuilder sb) {
  sb.append("");
 }
 
 public void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
 public void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
}
/**
 * Testing...
 *
 */
public class DecorateData {
 
 public static void main(String[] args) {
  CreateObject xml = new CreateObject();
  
  System.out.println(xml.decorate(new XmlObject()));
 }
 
}
37 - 46: First we move template methods into an interface. Definition is same as in previous example.
52 - 76, 82 - 114: In implementation of our interface we do not need to subclass anything anymore. But note that we must change access mode of method to public because this time we will to access them from outside class hierarchy.
17: Note that we need to provide interface type to our template method. This type will be substitute to concrete instance of class at runtime (Polymorphism is great stuff!). Method is exactly same as in TM example.

Which to choose?

This approach is more complex, but is more flexible. This is classic example of trade-off between concrete inheritance and delegating to an interface. Decision what to choose is completely up to you and may be influenced by circumstances like: Class implementing steps needs its own inheritance hierarchy, how many steps are involved, how many different implementation will you have...

Wednesday, September 29, 2010

jQuery triggering custom event (Observer pattern)


Introduction

We all know what basic events in JavaScript and jQuery are. They represent handlers that are triggered at specify event (click, timer, mouse move, etc.). But how do we create custom events that are triggered on our command, here comes jQuery to the rescue! Also doing this (calling custom events), we can simulate classic Go4 observer pattern (publish/subscribe).

Using jQuery is beneficiary, because, we are not concerned about various DOM levels, browser specific stuff (like: (event.target) ? event.target : event.srcElement;...), does IE 6,7,8 support event capture phase, and stuff like that. We basically create another abstraction level over various JavaScript implementations.

So, let the fun begin!

Live event handling

In our example we will use jQuery ability to manage event handler on the fly (as we manipulate the DOM by adding or removing elements). This means that we will proactively establish event handlers for elements that don't exist yet. jQuery provide this functionality with the live() method. Syntax for this method is similar like bind() or for example click() method.

Triggering events

In out example we will also need some method that will automatically invoke (trigger) event handlers on our behalf under script control. For this we will use the trigger method. This method does its best to simulate the event to be triggered. One curiosity is that it even populate instance of jQuery event (event object in jQuery style :) ), but because there is no real event, properties that report event-specific values such as the location of mouse x and y cordinates, have no value. Ok, let's move on.

Example

First jQuery part:

$(function() { //Wait until DOM is fully loaded .
    $('#addBox').click(function() {
        $('td.box:first-child').clone().appendTo('tr.boxLine');                
    });

    $('#paintBlue').click(function() {                
        $('td.box').trigger('paintThem');
    });

    $('td.box').live('paintThem', function() {
        $(this).css('background', 'blue');                
    });            
});

2-5: First we create simple click handler that add new box like element on the DOM. We create boxes using simple table and just adding new table data elements by coping them. Please see html part, and first picture where we add couple of boxes.

6-8: Here we trigger custom event named "paintThem". This is simple click event triggered by button. We need to trigger custom event on elements (in this case 'td.box') that posses custom event (but, also we can trigger standard events like: click, hover...).

10-12: The "real meat" of this whole story. Here we see a use of the live() method to proactively establish event handlers. The 'td.box' elements will be added dynamically to the DOM and live method will automatically establish handlers as necessary.
This way, we sat it up _once_ and jQuery will handle the details whenever an item that matches that selector (td.box) is create (or destroyed). Great stuff!

So as you can see, this example is not so fancy, it just paint red boxes to blue. But the way it does it is interesting. I can also walk trough all elements and paint them to certain color, but this approach is much cleaner and in some situations better (asynchronous refresh (AJAX) for example).

Then, html part. My apologies for this fuzzy looking html code (it's blogger fault! :) ).


Custom event is a very useful concept. Using it, we can attach code to an element as a handler for a custom event, and cause it to execute by triggering the event. The beauty of this approach, as opposed to directly calling code, is that we can register the custom handlers in advance, and by simply triggering the event, cause any registered handlers to be executed, without having to know they've been established.

Custom event concept in jQuery can be seen as limited version of Observer pattern. In this pattern (also know as publish/subscribe pattern) we subscribe an element to a particular event by establishing a handler for that element, and then when the event is published (triggered), any elements that are subscribe to that event will automatically invoke their handlers.

In this way we are creating loose coupling (and that is always a _good_ idea) in our JavaScript code. This make our code cleaner and meaner!

Custom trigger in action:

Adding boxes.


Triggering event to paint boxes in blue.