Tuesday, 1 July 2014

Java Design Patterns Part - 3B

Design Pattern In Java

Interview Questions                                                                                                      JSON
Behavioral Design patterns :- 
 7) Observer design pattern(Publish/Subscribe) :- This pattern falls under behavioral design pattern. This pattern defines a one-to-many dependency between objects so that when one object state is change then all of its dependents are notified and updated automatically. In this pattern the objects that listen or watch for change are called observers and the object that is being watched for is called subject. It is mainly used to implement distributed event handling systems. Most of the programming libraries and system including GUI toolkits have implemented this design pattern.

As per GOF:- “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”

Observer design pattern in Real World:- Most of the time, we have used online shopping, so whenever we searched for any product and suppose at that point of time it is not available then there is an option available i.e. "Notify me when product is available". If we will choose that option then whenever that product is available then we will get notification by mail or sms(Here when product is available means product state changes then we will get notification). In this case, Product is subject and we are observers.
Similarly in facebook, If we subscribe someone then whenever new updates raises by him then we will get notification.
Observer design pattern in Java :-
  • javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener
  • All implementations of java.util.EventListener (Used in Swings)
  • java.util.Observer/java.util.Observable
When we can use this:-
  • When subject doesn't know about number of observers it has.
  • When one object changes its state,then all other dependent objects must automatically change their state to maintain consistency
  • When an object should be able to notify other objects without knowing who objects are.
8) State design pattern:- This type of behavioral design pattern provides a mechanism to change behavior of an object based on the object’s state. State is used when we need a class to behave differently, such as performing slightly different computations, based on some arguments passed through to the class. In this pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

As per GOF:- “Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.”

State design pattern in real world:- As we know, A vending machine is a machine which dispenses items such as snacks, beverages, alcohol, cigarettes, lottery tickets, cologne, consumer products and even gold and gems to customers automatically, after the customer inserts currency or credit into the machine. So this vending machines maintain its internal state which allow it to change it's behaviour depends on situation. For example, if there is no change available, it will demand exact currency. When something is out of stock, it will not deliver any product.
Another example is a drawing program like MSPaint where the program has a mouse cursor, which at any point in time can act as one of several tools. like eraser, pensil e.t.c. So, instead of switching between multiple cursor objects, the cursor maintains an internal state representing the tool currently in use. When a tool-dependent method is called (say, as a result of a mouse click), the method call is passed on to the cursor's state.

State design pattern in Java :-
  • javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)
9)Strategy design pattern:- This behavioral pattern is also known as policy pattern. An object controls which of a family of methods is called. Each method is in its' own class that extends a common base class. The Strategy pattern help us to build a software as a loosely coupled collection of interchangeable parts which makes our software much more extensible, maintainable, and reusable.
The strategy pattern tells do the below things
  • It defines a family of algorithms,
  • encapsulates each one(algorithm), and
  • It makes the algorithms interchangeable within that family.
The best example of Strategy pattern is Collections.sort() method that takes Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.
In Strategy design pattern:-
  • Algorithms (strategies) are chosen at runtime.
  • A Strategy is dynamically selected by a client i.e. a user or consuming program or by the Context.
  • Our driver or controller class is typically named as Context.
  • The Context class is aware of a variety of different algorithms, and each algorithm is considered as a Strategy. The Context class is responsible for handling the data during the interaction with the client.
As per GOF:- “Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour.”

Uses:-
  • When we need to use one of several algorithms dynamically.
  • When we want to configure a class with one of many related classes behaviors.
Advantages:-
  • Provides an alternative to subclassing.
  • Reduces multiple conditional statements in a client.
  • Can be used to hide data that an algorithm uses that clients shouldn't know about.
  • Hides complex, algorithmic-specific data from the client.
Strategy design pattern in real world:- In many applications we are saving the files in different formats like: doc format(Ms-Word), ODT(OpenOffice), RTF, HTML, plain text.
Compress files using different compression algorithms by different application like winzip, winrar, 7Zip e.t.c.
Display calendars, with different holidays for different countries.

Strategy design pattern in Java:-
  • javax.servlet.Filter#doFilter()
  • java.util.Comparator#compare(), executed by among others Collections#sort().
  • javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
10) Template method design pattern:- This design pattern also fall under behavioural design pattern. In the template method design pattern, the 'template method' defines the common steps of an algorithm. The implementation of these steps can be deferred based on subclasses. Thus, the common algorithm is defined in the template method, but the exact steps of this algorithm can be defined in subclasses and the template method is implemented in an abstract class.

As per GOF:- “Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure.”

When to use: -
When we have a predefined steps for algorithm but implementation of those steps may vary.
When we want to avoid code duplication,implementing common code in base class and variation in subclass.

Template method design pattern in real world:-Making of every automobile and machines are based on some template pattern. Basic building plans because a different building may have many variations. For creating any framework, we need to use this design pattern in order to remove code duplication.

Template method design pattern in Java:-
  • javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. We are free to implement none or any of them.
  • All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
  • All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.

11) Visitor design pattern:- This pattern falls under behavioral design pattern. This pattern is used when we have to perform an operation on a group of similar kind of Objects. Using this design pattern, we can move the operational logic from the objects to another class. This pattern is providing a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.

As of GOF:- “Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure.

Visitor design pattern in Real world:- Visitor pattern is a design pattern commonly used in the parser of a compiler, such as Eclipse JDT AST Parser.

Visitor design pattern in Java:-
  • javax.lang.model.type.TypeMirror and TypeVisitor
  • javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
  • javax.lang.model.element.Element and ElementVisitor
Uses:-
  • When the classes defining the object structure changes rarely, but we often want to define new operations over the structure. (If the object structure classes change often, then it's probably better to define the operations in those classes.)
  • When many distinct and unrelated operations need to be performed on objects in an object structure, and we don't want to spoil their classes with these operations
  • When an object structure contains many classes of objects with differing interfaces, and we want to perform operations on these objects that depend on their concrete classes
Advantages:-
  • Adding new operations is easy
  • Related behavior isn't spread over the classes defining the object structure; it's localized in a visitor. Unrelated sets of behavior are partitioned in their own visitor subclasses.
Difference between Visitor and Strategy pattern:-

Visitor and strategy looks similar as they encapsulates complex logic from data. We can say that Visitor design pattern is more general form of strategy. In Strategy design pattern we have one context on which multiple algorithms operate means in Strategy pattern we have a single context and multiple algorithms work on it. But on the other way Visitor design pattern have multiple contexts and for every context we have an algorithm.
In short, We can generalize that Strategy is a special kind of Visitor, In strategy we have one data context and multiple algorithms while in visitor for every data context, one algorithm associated with that.

Web-Services                                             Spring-AOP                                                      Spring-Core                  

Wednesday, 11 June 2014

Java Design Patterns Part - 3A

Design Pattern In Java

Spring-AOP                                                                                    Spring-Core

Behavioral : Thisdesign pattern explains about how objects will get interacted with other objects.
The commiunication between the objects is like that they should talk with each other but still they should be loosly coupled. Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns. A loosely-coupled class can be consumed and tested independently. Interfaces are powerful tool to use for loose coupling. So it is clear to say that loose coupling will help to avaoid dependencies.
  1. Chain of Responsibility Pattern : This design pattern belongs to Behavioral pattern. In software engineering the more stress we are giving on decoupling of objects. The main objective of this design pattern is when a sender sends a request to a chain of objects, where the objects in the chain decide themselves who to serve the request. If an object in the chain decides not to serve the request, it forwards the request to the next object in the chain.
As per GOF : - "Gives more than one object an opportunity to handle a request by linking receiving objects together."
This design pattern allows a number of classes to attempt to handle a request, independently of any other object along the chain. Once the request is handled, it completes it’s journey through the chain. Extra handlers can be added or removed from chain in the middle or anywhere without modifying the logic inside any of concrete handler. In a chain of objects, the responsibility of deciding who to serve the request is left to the objects participating in the chains. This is very similar to ‘passing the question in a quiz scenario’. When the quiz master asks a question to a contestent & if he doesn’t know the answer, he passes the question to next contestent and so on. When one contestent answer to that question, the passing flow stops. Sometimes, the passing might reach the last contestent and still nobody gives the answer.
Points to remember while using Chain of Resposibility Pattern :
  • Sender is not aware of that which object in the chain will serve its request.
  • Every node in chain will have the responsibility to decide, if they are able to serve the request.
  • If node/chain decides to forward the request, then it should be capable of choosing the next node and forward the request to that.
  • There is a possibility where none of the node may serve the request.
Example : -
  • Real time example for this design pattern is Service desk support for any bank.
  • Chain of Resposibility Pattern references in JDK is

java.util.logging.Logger#log() : -
If the logger is currently enabled for the given message level then the given message is forwarded to all the registered output Handler objects available in the chain.

javax.servlet.Filter#doFilter() : -
The Servlet doFilter method of the Filter class is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

       2.  Command Design Pattern :- This design pattern falls under behavioral design pattern. In this design pattern, an object is used to represent and encapsulate all the complete information which is required to call a method after some time. The information which that object contains includes the method name, the object that owns the method and values for the method parameters. Particularly it defines a manner for controlling communication between classes or entities.The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object.
A command object has a receiver object and invokes a method of the receiver in a way that is specific to that receiver's class. This command object is separately passed to an invoker object, which invokes the command, and optionally does logging about the command execution. Any command object can be passed to the same invoker object. Both an invoker object and several command objects are held by a client object. The client contains the decision making about which commands to execute at which points. To execute a command, it passes the command object to the invoker object.

As per GOF :- “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo able operations.”
There are some terms which are related to this design pattern, which are invoker, receiver, command & client.
  • Command is an interface which is having a execute() method. So it means that this interface declares a method for executing a specific action. This provides the base class for all objects
  • An invoker instructs the command to perform an action or the invoker object initiates the execution of commands. The invoker could be controlled by the client objects.
  • A client creates an instance of the command implementation and then associates/links it with the receiver.
  • A command implementation class instance creates a binding between the receiver and an action.
  • Receiver is the object that knows the actual steps to perform the action or we can say that Receiver objects contain the methods that are executed when one or more commands are invoked.
Command Pattern can be used for the following situations:
  • If we want to parameterize objects by an action to perform.
  • If we need to specify, queue, and execute requests at different times.
  • When a set of changes to data need to be encapsulated as a single action or transaction.
Example:-
A Command pattern is also known as an action pattern or transaction pattern.
  • The real world example for the command pattern is the idea of table order at a restaurant. Restaurent waiter takes the order, which is a command from the customer.This order is then queued for the kitchen staff, then waiter tells the chef that the a new order has placed, and the chef has complete information to cook the ordered dish.

Another Example:-
  • Struts controller uses the Command Design Pattern.
  • All implementations of javax.swing.Action
  • All implementations of java.lang.Runnable

       
       3.   Interpreter Design Pattern :- The interpreter pattern is used to define the grammar for instructions that form part of a language or notation, at the same time allowing the grammar to be easily extended. It means that design pattern is used to define a grammatical representation for a language and provides an interpreter to deal with this grammar. This design pattern is useful for simple languages where performance is not critical. It's used to manage algorithms, relationships and responsibilities between objects. 
Few terms which relate to this design pattern :
  • Context, Client, Abstract Expression, TerminalExpression and NonTerminalExpressions.
  • Context :- This contains information which is global to the interpreter.
  • Client :- This build the Abstract Syntax tree or AST is passed through the client.
  • AbstractExpression :- This provides an interface for executing an operation.
  • TerminalExpression :- This implements the interpret interface associated with any terminal expressions in the defined grammer. This will not contain other expression, the leaf node in a tree
  • NonTerminalExpressions :- This will contain other expression, non-leaf node in a tree.

An AST( Abstract Syntax tree) is composed of both TerminalExpressions and NonTerminalExpressions.

As per GOF :- “Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.”
  • Real Time example:-
Java compiler which interprets the java source code into byte code and which is understandable by JVM is the best example for this design pattern. Google Translator is another known example for this pattern where the input can be in any language and we can get the output interpreted in another language.

Examples related to Java :-
  • SQL parsing is using this design pattern.
  • All subclasses of java.text.Format
  • All subclasses of javax.el.ELResolver
  • java.util.Pattern
  • java.text.Normalizer 


            4.    Iterator design pattern: - This is the commonly used design pattern in Java. This pattern is used to manage algorithms, relationships and responsibilities between objects. This pattern allows to traverse through a collection of objects without exposing the underlying collection. As this pattern helps to hide the actual implementation of traversal. Iterator pattern is widely used in Java Collection Framework where Iterator interface provides methods for traversing through a collection objects.

As per GOF :- Provides a way to access the elements of an aggregate object without exposing its underlying represenation.”
  • Iterator example in Real world :- Mp3 player control is very good example of this design pattern.
  • Iterator example in Java :- As we know that this is the widely used design pattern in Java collection framework.
  • All implementations of java.util.Iterator (thus among others also java.util.Scanner!).
  • All implementations of java.util.Enumeration
                5.     Mediator design pattern :- In order to have a good object oriented design framework, we have to create multiple objects and classes and these classes interacting with each other. Mediator pattern is used to reduce communication complexity between multiple objects or classes. It provides loose coupling by providing a mediator class which normally handles all the communications between different classes and also supports easy maintainability of the code.

As per GOF:-Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another.

a) Mediator example in Real world :- Air traffic controller (ATC) is a mediator between multiple flights. It helps in communication between flights and co-oridates/controls landing & take-off. Two flights need not interact directly and there should not be any dependency between them. This dependency is solved by the mediator ATC.

b) Mediator example in Java :-
  • java.lang.reflect.Method#invoke()
  • java.util.Timer (all scheduleXXX() methods)
  • java.util.concurrent.Executor#execute()
  • java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
  • java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods)
             6.    Memento design pattern :-Memento means anything serving as reminder. This pattern helps to store an object's state so that this state can be restored at a later point. The saved state data in the memento object is not accessible from outside of the object to be saved and restored.
In this pattern, an Originator class represents the object whose state we would like to save. A Memento class represents an object to store the state of the Originator. The Memento class is typically a private inner class of the Originator. As a result, the Originator has access to the fields of the memento, but outside classes do not have access to these fields. This means that state information can be transferred between the Memento and the Originator within the Originator class, but outside classes do not have access to the state data stored in the Memento.

The memento pattern also utilizes a Caretaker class. This is the object that is responsible for storing and restoring the Originator's state via a Memento object. Since the Memento is a private inner class, the Memento class type is not visible to the Caretaker. As a result, the Memento object needs to be stored as an Object within the Caretaker.

As per GOF :-Captures and externalizes an object's internal state so that it can be restored later, all without violating encapsulation.

a) Memento design pattern in Real world :- We have seen option in cellphone i.e. Restore phone data with factory settings
Other example :- Undo or backspace or ctrl+z is one of the most used operation in an editor. Memento design pattern is used to implement the undo operation.

b) Memento design pattern in Java :-
  • java.util.Date (the setter methods do that, Date is internally represented by a long value)
  • All implementations of java.io.Serializable
  • All implementations of javax.faces.component.StateHolder
Uses of Memento design pattern :- The Memento pattern is useful when we need to provide an undo mechanism in our applications, when the internal state of an object may need to be restored at a later point of time. Using serialization along with this pattern, it's easy to preserve the object state and bring it back later on.
                                                                                                      Rest of the behavioral design pattern will be in next part


Web-Services                                             Spring-MVC                                         Interview-Questions

Sunday, 30 March 2014

Java Design Patterns Part - 2

Design Pattern In Java

Hibernate                                                                                       Core Java

Structural : This design patterns describes how classes and objects can be composed, to form larger structures. These patterns teaches us about how the classes inherit from each other and how they are composed from other classes.This patterns simplifies the structure by identifying the relationships.

  1. Adapter This pattern work as a connector or helps to join two unrelated interfaces so that they can work together.
For example :
A well defined example for Adapter design pattern is Laptop charger. When we are using our laptop then to charge the laptop battery we are connecting this to mainline socket but using adapter in between. Because normally laptop requires least voltage(20 V) in order to charge its battery and mainline is supplying more voltage(240 V). So we need a power adapter which converts and provide the required voltage in order to charge the Laptop battery. This pattern combines the capability of two independent interfaces.The Adapter pattern which is a Structural Design pattern can be used to realize relationship between entities. This pattern can be implemented in two ways, either by Inheritance(is-a)or by Composition(has-a).

The description given by Gof(Gang of four)about this pattern is below:
"Convert the interface of class into another interface clients expect.Adapter lets class work together that couldn't otherwise because of incompatible interfaces".
Examples as per java API :
  • java.util.Arrays#asList()
  • java.io.InputStreamReader(InputStream) (returns a Reader)
  • java.io.OutputStreamWriter(OutputStream) (returns a Writer)
  • javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal()
    1. Bridge The Bridge pattern is known as Structural pattern and GOF states that pattern tells that :
As per GOF:-
Decouple an abstraction from its implementation so that the two can vary independently”

Mainly this pattern is useful in graphic toolkits that needs to run on a variety of platforms. The display of various image formats on different OS is the best example of the Bridge pattern. The image structure is the same across all OS, but how they are viewed (the implementation) is different on each OS. This is the type of decoupling that the Bridge pattern allows. This pattern allows us to separate the abstraction and the implementation. It means to say that this pattern allows the Abstraction and the Implementation to be developed independently.This layer provides a two layer of abstraction. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

For example:
The example of TV and Remote Control(typo in diagram) can demonstrate the two layers of abstraction. We have an interface for TV and an abstract class for remote control. It is not a good idea to make a concrete class for either of them, because other vendors may make different implementations.
  • This creates 2 hierarchies i.e. One for abstraction and another for implementation.
  • This avoids permanent binding by removing the dependency between abstraction & Implementation.
  • It should be used when we need to switch between the various implementations.
  • Client should not be impacted if there is any modification in abstraction implementation.
  • Abstraction and Implementation can be extended separately.
  • When we are dealing with multiple implementations then we can use Bridge Design Pattern.
  • Bridge will coordinates between Abstraction and Implementation.
Example as per java API : Object Persistence API is the example of Bridge Design pattern.
A classic example of Bridge is Drivers. Each driver is an instance of the Adapter pattern, providing the interface a client expects, using the services of a class with a different interface. An overall design that uses drivers is an instance of Bridge. The JDBC architecture decouples an abstraction from its implementation so that the two can vary independently—an excellent example of Bridge e.g. JDBC ODBC Bridge driver.
    1. Composite This design pattern is represents as a partitioning design pattern. This pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The purpose of composite is to "compose" objects into tree structures to represent part-whole hierarchies.
As per Gof:-
"Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly".

Questions : What is the meaning of part-whole hierarchies?
Answer:- A system is a combination of subsystem or components. Components are the combinations of smaller components. Similarly, Smaller components are the combination of smaller elements. This is known as part-whole hierarchy.

This design pattern allows as to have a tree structure and each node of that tree structure will perform a specific task.
Real World example : We can think about our company. There are Project Director, Project Director will further categorized into Project managers, Project managers can be further divided into Project leads, then Project lead can have many Team leads, then Team leads may have many Developers.
This is making a tree structure and composing an organization and each node of this tree structure is performing some task for that they are getting salary.

Example as per API : - Tiles framework in Struts, which help us to compose a webpage using multiple JSP pages. This is actually an implementation of CompositeView Pattern and this pattern itself based on Composite pattern.

Another example as per Java API :-
java.awt.Container#add(Component) (In awt, we have containers and components, the best example for Composite pattern)
javax.faces.component.UIComponent#getChildren() (In JSF UI)
    1. Decorater – Decorater design pattern is used to change or extend the behavior of an object. This is used to attach or add responsibities to an individual object dynamically, without affecting the behavior of other objects from the same class. Alternatively this is also known as Wrapper. In different words, this pattern uses composition instead of inheritance to extend the functionality of an object at runtime.
When to use decorator design pattern?
Answer :- we can use this design pattern when :
When we need to attach responsibilities to individual objects dynamically without affecting other objects.
For adding the beviour which can be withdrawn in future.
Extending functionality by sub-classing is no longer possible.
Decorators are very flexible alternative of inheritance.

Example in java API :-
[I] In Java Collection API, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
e.g. checkedCollection(), checkedSet(), checkedSortedSet(), checkedList(), checkedMap(), checkedSortedMap() are the examples of decorator design pattern.

[II] javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper.

[III] All subclasses of java.io.InputStream, OutputStream, Reader and Writer constructors because
These classes are abstract since in that way they can be easily extended and the implementor classes could use the Decorator Pattern. With the decorator pattern, the implementor class can add dynamic functionality at runtime. For example: we can have an InputStream which will read a File using FileInputStream or it can also be read serialized objects using ObjectInputStream.

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("/project/resources/test.dat"));
    1. Facade A facade is generally the face of a building, especially the principal face. This word comes from the French Language, which means frontage or face. During a building creation it is having many complexities like boring, wiring, pipelining or others, but we are seeing only the frontface of the building because it hides all the complexities.
This is the way we can use Facade design pattern. This pattern provides a simplified interface to a set of interfaces within the system and thus it hides the complexities of the subsystem from the client.

As per GoF:- definition facade design pattern is, “Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.”
We can use Facade design pattern for :-
  • It will increase the readability.
  • Easy to maintain.
  • Makes a library easier to use, understand and test because the facade will provide convenient methods for common tasks.
  • It reduces the dependencies of the external code, so it provides flexibility.
  • We can use this pattern to collate all the complex method calls and related code blocks and channelizes it through one single Facade class. In this way with respect to client there is only one single call. Even if we make changes to the subsystem classes and then there is no impact to the client call which means this increases loose coupling.
Example :- Service oriented architectures make use of the facade pattern. For example, in web services, one web service might provide access to a number of smaller services that have been hidden from the caller by the facade. Like while purchasing clothes online how it is interacting through payment gateway that complexities if unknown by the user.

Facade design pattern used in java api are : -
javax.servlet.http.HttpSession
javax.servlet.http.HttpServletRequest
javax.servlet.http.HttpServletResponse
javax.faces.context.ExternalContext
javax.faces.context.FacesContext, it internally uses many others the abstract/interface types like LifeCycle, ViewHandler, NavigationHandler and many more without showing that to enduser.
  1. Flyweight – It is a kind of design pattern which is used to reduce the creation of multiple objects which are identical in nature. This design pattern is used when there is requirement to create large number of objects which are similar in nature. It helps to minimizes the memory use by sharing as much data as possible in case of similar objects. As we know creation of multiple objects consumes huge memory so this design pattern is providing a solution to minimizes the amount of memory by sharing those objects or we can say that this pattern allow us to reuse memory spaces within the application when we have huge number of objects which are almost same in nature. Sharing is the key feature of this design pattern.
As per GOF : "Facilitates the reuse of many fine grained objects, making the utilization of large numbers of objects more efficient."

For example : Suppose we are making a game for Android OS like car race app, then the shape of car we can share by providing different colours to those cars and making them different cars for the game players.
When we think about this pattern then we need to think about the concept of Intrinsic and Extrinsic state, The data which comes inIntrinsic state are constant, so they can be stored in memory. But the data which comes under Extrinsic state are not constant, they are required to be calculated on the fly or dynamically, so the reason they can't be stored in memory. So as per the above example, we can consider as the shape of each car will be under Intrinsic state andthe color of each car will be in Extrinsic state.

In Java API : String Pool implementation is the best example of Flyweight Design Pattern.
Other example are : java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short and Long)

    7) Proxy : The word Proxy means an agent or substitute which is authorized to act for another one. In the design pattern Proxy will represent another object.
As per GOF :- "Provide a surrogate or placeholder for another object to control access over it."

This pattern is also known as surrogate or placeholder. This pattern allows us to create a wrapper class over the actual object. Here wrapper class which acts as proxy helps to control access to real object so in turn we can add extra functionalities to real object without changing real object's.

For example: In most of the IT companies, they are allowing the internet use but blocking the sites like Gmail, Yahoo, Facebbok by using a Proxy server which acts as a wrapper of original server.

Example as per java API : java.lang.reflect.Proxy, java.rmi.*.
If we are working with Spring, then also we can find AOP proxies object.

We can use proxy design pattern in below conditions:

[1] During the need of a remote proxy which provides a local representative for an object in a different address space by providing interface for remote resources such as web service or REST resources.

[2] During the need of a virtual proxy which creates expensive object on demand.

[3] During the need of a protection proxy which controls access to the original object. Protection proxies are useful when objects should have different access rights.

[4] During the need of a smart reference which is a replacement for a bare pointer that performs additional actions when an object is accessed.

[5] Suppose there is a requirement to add a thread-safe feature to an existing class without changing the existing class's code.

Java-Collections                                           Spring-Core                                                     JSON

Next part - Behavioral Design Pattern is under progress

Friday, 14 March 2014

Java Design Patterns Part - 1

Design Pattern In Java

Web Service                                                                                              Java and It's Version - Features

Question:- What is design pattern?

Answer:- As per GOF(Gang of Four), "Design Patterns: Elements of Reusable Object-Oriented Software"

It help to provide solutions to common software design problems. Its a kind of a powerful tool for software development. Its an independent strategies for solving common object-oriented design problems. It explains a general design that addresses a recurring design problem in object-oriented systems.Design pattern is nothing but a general resuable solution to commonly occurring problem within the given context in software design.

History of software patterns :-
  • 1987 – Ward Cunningham and Kent Beck used Alexander's ideas to develop a small pattern language.
  • 1990 – The Gang of Four ( Erich Gamma, Richard Helm, Ralph Johnson & John Vlissides) begin work compiling a catalog of design patterns.
  • 1991 – Bruce Anderson gives first patterns Workshop at OOPSLA
  • 1993 – Kent Beck and Grady Booch sponsor the first meeting – what is now known as Hillside group
  • 1995 – The Gang of Four published the design pattern book.
  • 2002 – Martin Fowler published the book “Patterns of Enterprise Application Architecture”.

Advantage of Design pattern
  • Reusable in nature.
  • Provide the solution that help to define the system architecture
  • Provide transparency towards application design
  • Easily maintenable
  • Reducing complexity by providing the clarity towards the system architecture

Design patterns is mainly categorized in three parts.
  • Creational : - It concerns the process of object creation
  • Structural :- This deals with the composition of classes & objects.
  • Behavioral :- This Characterize the ways in which classes/objects interact and distribute responsibility.
Creational

1) Singleton- Only one instance of the class :- This design pattern is recognized by creational methods returning the same instance everytime.

For example :

a) java.lang.Runtime#getRuntime()
b) java.awt.Desktop#getDesktop()

2) Abstract Factory: An abstract factory to produce factory of objects. This design pattern is having one level of abstraction higher than factory design pattern. This pattern returns the factory of classes. In case of factory pattern, it returns object of one of the subclass in several subclasses and this(Abstract factory) design pattern will return factory which later will return one of the sub classes. This design pattern is recognized by creational methods returning the factory itself which in turn can be used to create another abstract/interface type. Finally we can tell that this design pattern create factory which later creates products.

a) javax.xml.parsers.DocumentBuilderFactory#newInstance()
b) javax.xml.xpath.XPathFactory#newInstance()
c) javax.xml.transform.TransformerFactory#newInstance()

For example : 

 DocumentBuilderFactory is the best example of Abstract design pattern which creates a factory which is DocumentBuilder which later help us to create Document objects. Here we can find that DocumentBuilderFactory is the AbstractFactory where as DocumentBuilder is the Factory and Document is the Product.

DocumentBuilderFactory docBuildAbstractFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuildFactory = docBuildAbstractFactory.newDocumentBuilder();
Document doc = docBuildFactory.newDocument();

3)Factory A factory that produces objects. This design pattern is used to create instance of our classes which is somehow similar in features. For example :- If we will take “Human” class and want to create objects of “man” and “woman” classes dynamically which is subclass of human then we can go with this design pattern because man & woman classes are somehow similar to human class in terms of features.This design pattern is recognized by creational methods returning an implementation of an abstract/interface type. Finally we can tell that this design pattern creates products instead of factory.

a) java.text.NumberFormat#getInstance()
b) java.util.Calendar#getInstance()
c) java.nio.charset.Charset#forName()
d) java.util.ResourceBundle#getBundle()
e) java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)

Difference between AbstractFactory & Factory design pattern

[I] AbstractFactory uses compositionto delegate responsibility of creating object to another class while Factory pattern uses inheritanceand relies on derived classes or sub classes for object creation.

[II] AbstractFactory creates Factory which later creates objects of their sub classes where as Factory creates products instead of factory.

4) Builder :-Its a pattern used to construct a complex object in step by step process and at last or final step will return the object. These separates the construcution of complex objects from their representation. It is recognized by creational methods returning the instance itself. 

For example :

a) java.lang.StringBuffer#append()
b) java.lang.StringBuilder#append()
c) java.nio.ByteBuffer#put() (also on IntBuffer, CharBuffer, ShortBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
d) All implementations of java.lang.Appendable

According to Gang of Four(Gof):- The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.For example, we can think for making of a Mobile Handset. Making of a cellphone involves various steps such as embedding the processor chip, Ram, camera, screen, and supporting softwares. Finally we will get a complete Mobile phone object nothing but a complex object obtained by going through step by step process. With the help of the same process, we can make cellphones having different features.

Question:- When to use Builder design pattern?
Answer :- This design pattern is useful when we need to do lots of things to build an object. 

For example : 

In the creation of DOM object, we have to create plenty of nodes and attributes to get our final object.

    5) Prototype Prototype meaning itself is telling that making a clone. Prototype design pattern is used when an application needs to create many instances of a class, which is almost same as original one. So this we can do using clone. If the object creation is a expensive process then we can clone that object. While appling cloning, we should know which cloning we have to use Shallow or Deep cloning

    For example:-
      a) java.lang.Object#clone() (the class has to implement java.lang.Cloneable)