Monday 11 February 2013

Java Design Paterns

Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice


Creational Patterns: Creational patterns describe how objects are created (or "instantiated" in object-oriented terminology)

Singleton Pattern: Usually singletons are used for centralized management of internal or external resources and they provide a global point of access.

Common usage :
- Logger Classes
- Configuration Classes
- Accesing resources in shared mode
- Other design patterns implemented as Singletons: Factories and Abstract Factories, Builder, Prototyp

To avoid breaking of Singleton you can use
1. Override Clone method
2. Use double locking mechanism
3. In case of serialization override readResolve() methods


Factory Pattern: Creates objects but hides the instantiation logic from the client. And the newly created objects are referred through a common interface. 

Common usage :

- factories providing an xml parser: javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory
- java.net.URLConnection - allows users to decide which protocol to use

java.text.NumberFormat#getInstance(Locale inLocale) : This is an example of a Factory pattern , where the locale decide which NumberFormat implementation will be returned to the client.As based on locale there could be multiple implementations for NumberFormat object while handling numbers

Abstract Factory Pattern: Creates a family of related objects,without specifying their classes.



 Builder - Defines an instance for creating an object but letting subclasses decide which class to instantiate and Allows a finer control over the construction process.

Builder Pattern is used when:
  • the creation algorithm of a complex object is independent from the parts that actually compose the object
  • the system needs to allow different representations for the objects that are being built

The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That's why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory's methods to create its own objects. In the Builder's case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.

Example 1 - Vehicle Manufacturer. Let us take the case of a vehicle manufacturer that, from a set of parts, can build a car, a bicycle, a motorcycle or a scooter. In this case the Builder will become the VehicleBuilder. It specifies the interface for building any of the vehicles in the list above, using the same set of parts and a different set of rules for every type of type of vehicle. The ConcreteBuilders will be the builders attached to each of the objects that are being under construction. The Product is of course the vehicle that is being constructed and the Director is the manufacturer and its shop

Behavioral Design Patterns:   Behavioral patterns describe algorithms or communication mechanisms.

Chain of Responsibiliy -  The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.


The following example explains best how chain pf responsibility works here.



Example : JavaEE, the concept of Servlet filters implement the Chain of Responsibility pattern

Interface: javax.servlet.FilterChain has a method 

doFilter(ServletRequest request, ServletResponse response)

All the implementations in the chain implement the above method/interface. This basically decided how the request will move. The  javax.servlet.Filter implements the method

doFilter(ServletRequest request,ServletResponse response, FilterChain chain)


Command - [The command object can act as an interface between the client and the reciever. ] . In which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Example for Command pattern is here


Template Method - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses / Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure.
 
Implementation: 
AbstractClass
 - defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
- implements a template method which defines the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
ConcreteClass 
- implements the primitive operations to carry out subclass-specific steps of the algorithm.
When a concrete class is called the template method code will be executed from the base class while for each method used inside the template method will be called the implementation from the derived class.

 Strategy - Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.



 The code example is here


In the above diagram the behavior strategy dynamically changes. Here the family of algorithms for Behaviour are defined as Aggressive,Defensive and Normal . These algorithms are different strategies applied based on the input request.


Observer - Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.



 The code example is here.



 
In the above diagram all the observer[handlers/listeners] are loaded in the News Publisher. Whenever the notifyObservers() method is called the upate() method of all the observer[handlers/listeners] are invoked. You can re-modify this implementation by replacing the List of observers with a factory and you can select an observer to be invoked based on the input to the update() method.

Structural Design Patterns:  Structural Patterns are the design patterns used to define structures of objects and classes that can work together and to define how the relations can be defined between entities

Adapter - (Creation methods taking an instance of different abstract/interface type and returning an implementation of own/another  type ,which overrides the instance)

Like any adapter in the real world it is used to be an interface, a bridge between two objects. In real world we have adapters for power supplies, adapters for camera memory cards, and so on.  

Example in JDK : InputStreamReader(InputStream in)

The above constructor takes input stream as an object and then returns InputStreamReader as an output.


Bridge  

Methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which uses the given instance

Examples : here is the example in general. 

When to use : The above pattern can be used in cases where you have different models to interact with databases as DTO objects and different models that do business computation or Front-end rendering.

 

DecoratorAttach additional responsibilities to an object dynamically.

 This is actually used all over the JDK, the more you look the more you find, so the list below is definitely not complete.

-java.io.BufferedInputStream(InputStream)
-java.io.DataInputStream(InputStream)
-java.io.BufferedOutputStream(OutputStream)
-java.util.zip.ZipOutputStream(OutputStream)
-java.util.Collections#checked[List|Map|Set|SortedSet|SortedMap]()


A decorator is different from an adapter in that a decorator changes object's responsibilities, while an adapter changes an object interface.









Saturday 9 February 2013

JavaScript and AJAX

JavaScript is an object oriented language but most of us does not know how this language works or how is uses the concept of object oriented language


In JavaScript you first create an object, there is no concept of class, then you can augment your own object or create new objects from it. JavaScript has a concept of prototype. The prototype property allows you to add properties and methods to an object.

This article contains all that is important to understand JavaScript and prototype.


How Ajax works :
With AJAX [Asynchronous JavaScript and XML], your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.

Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest.

Then, you'll follow the same basic outline in almost all of your Ajax applications:

  •     Get whatever data you need from the Web form.
  •     Build the URL to connect to.
  •     Open a connection to the server.
  •     Set up a function for the server to run when it's done.
  •     Send the request.