Saturday, October 8, 2011

oops

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency

These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency.

News

Its 1 Million now – Thank You

Its been a while I have written on the blog. I was kind of occupied with other studies! Suddenly I noticed a surge in bandwidth usage in my service provider’s report. Something is happening with javapapers. I quickly checked analytics report and found in recent months there is a surge in number of visitors to the website.

Ooh hah! We have crossed ONE MILLION Pageviews. Rarely I see blog authors sharing their site visitor statistics as it might affect the revenue plan. I am happy to share the little stats with you. Its all happening because of you. Thank you!
Its been a slow and steady growth till the last few months. Growth in number of direct visitors is significant in the last couple of months. Similarly from the last couple of months the total Pageviews growth are close to 100%. Almost I am experiencing an explosion in the last few months. This is a successful first step for a blogger and still long way to go. Thanks to Google for all the search traffic and many free tools.

There might be some silent period in between, but I will keep on coming back and annoy you! There is a lot to write about and I will keep on writing. More and more when I try to make it simpler and easier, in direct proportion I learn many new things.

















Top ten countries                

Apache (ASF) Resigns from JCP Committee

It’s one month old news as of today. Still if you are not aware, Apache software foundation one of the most respected group and it moves away from JCP citing license issues and Oracle’s strong hold on java.
Java benefited in many ways for more than 10 years from Apache. It chaired the JCP executive committee and one of the main drivers for java community process. Starting with famous Apache Tomcat, ASF has around 100 projects focusing on Java. This is really sad news for us. We the java community have happily used ASF’s products.
Five years back, can you name a decent project that was built without Apache Ant? Of course now it’s Apache Maven. Okay time to move on. But we believe in Apache’s ethics. I am sure that all those projects will flourish as always.
ASF resigning from JCP is now. In future, will there be JCP itself? Will there be same harmony?
Now we are living in a world of uncertainty pertaining Java. As a developer we may lose some freedom over Java and its path. But we hope java will live long. Losing some freedom, isn’t that everything?

JAG is Now Unemployed!

I recently noticed that James Gosling moved his blog from sun’s site to his own blog with a cool domain name. Also, I noticed in his bio that he is unemployed. Yes, you read it right, James Gosling is unemployed! Oracle bought Sun some time back. We are all eagerly watching the events aftermath. I would say this as one of the huge blows.
Though now java grows out of JSRs, he was the CTO of an important division. Of late his contributions to java as a language is debatable. But above all, he is James Gosling. He resigned on April 2nd. I am not aware of the happenings behind. He says, he is going to start ‘job hunting’.
Don’t get emotionally attached with the product, technology and anything else with you are working on. Only knowledge is yours. Beware, if it could happen to JAG, it could happen to ‘anyone’!


              


Now the SUN is Red

sun.com now redirects to oracle.com – oracle completes acquisition of sun.

Is it a happy news or sad news for sun customers? In particular java guys.
  1. Oracle is a strong supporter of Eclipse – what will happen to NetBeans now?
  2. Will oracle continue and endorse JCP (Java Community Process)?
  3. Will MySQL development continue?
  4. Will oracle continue OpenOffice?
  5. Will Glassfish live in sync with oracle owned weblogic

Oracle’s press release says it will continue to support sun customers and invest more money on SPARC and MySQL. Until now, no negative news to worry about.
This $7.4 billion deal has become notorious on the above fronts. All the controvercy is surrounding MySQL and there is not much noise about what will happen to java!
There is a high possibility for a new commercial platform as oracle java. They know how to sell it as oracle is everywhere.
Mike Milinkovich, the Eclipse Foundation’s Executive Director:
“The Oracle acquisition of Sun and Java holds some real promise for resolving one of the simmering disputes in the Java community. Namely, the technical direction of modularity in Java. OSGi has been around for a number of years and has demonstrated its utility as a well architected Java modularity solution in domains ranging from mobile to enterprise middleware. OSGi has been adopted to varying degrees by every major Java licensor, including Oracle.
During the past couple of years, it looked like Sun was on a path of basically reinventing the wheel. With Oracle at the helm there is a chance that the Java platform will be moving forward with OSGi as the standardized model for modularity.”
But its one killer blow by Larry Ellison. Now the competition with MS$ becomes even stronger, and a new direct competition with IBM and so on.







Log4J

Log4J Levels

This log4j post is a tutorial post describing different levels of logging in log4j. This is for log4j beginners only but if you wish to refresh, go ahead and enjoy!
Log4j logger contains three main components namely logger, appender and layout. Logger takes care of the logging mechanism and deals with level of logging. Log4j provides five standard levels of logging. There are two more special levels given by log4j. Above all these, log4j allows you to create custom levels.
Don’t try to make out a meaning from this image. Just for fun :)

Five standard log4j levels

DEBUG Level

This log4j level helps developer to debug application. Level of message logged will be focused on providing support to a application developer.

INFO Level

This log4j level gives the progress and chosen state information. This level will be generally useful for end user. This level is one level higher than DEBUG.

WARN Level

This log4j level gives a warning about an unexpected event to the user. The messages coming out of this level may not halt the progress of the system.

ERROR Level

This log4j level gives information about a serious error which needs to be addressed and may result in unstable state. This level is one level higher than WARN.

FATAL Level

This log4j level is straightforward and you don’t get it quite often. Once you get this level and it indicates application death.

Two special log4j levels

ALL Level

This log4j level is used to turn on all levels of logging. Once this is configured and the levels are not considered.

OFF Level

This log4j level is opposite to ALL level. It turns off all the logging.

New Trace Level added in Log4j

TRACE Level

This log4j level gives more detailed information than the DEBUG level and sits top of the hierarchy. This level is introduced from version 1.2.12 in log4j.

Custom log4j levels

Log4j’s levels are mostly sufficient for all common applications. Rarely you may need a new Level apart from the levels provided by log4j. In that case you can extend org.apache.log4j.Level class and have your own custom level implementation.

Log4j Logger Output

When a logger is created, generally you assign a level. The logger outputs all those messages equal to that level and also all greater levels than it. So the order for the standard log4j levels are:

Log4J Levels

TRACE Level DEBUG Level INFO Level WARN Level ERROR Level FATAL Level
TRACE Level Y Y Y Y Y Y
DEBUG Level N Y Y Y Y Y
INFO Level N N Y Y Y Y
WARN Level N N N Y Y Y
ERROR Level N N N N Y Y
FATAL Level N N N N N Y
ALL Level Y Y Y Y Y Y
OFF Level N N N N N N

Log4j Level Inheritance Rule

There can be instances when you don’t assign a level to the logger. In such cases log4j handles it seamlessly based on the following level inheritance rule:
The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.
That means, if you have a package as com.foo.bar and you didn’t allocate a level, then it will inherit the level from com.foo package. Still in that package also if the level is not available, then it will inherit from the log4j root level. The log4j’s root logger is instantiated and available always. Log4j’s root logger by default has DEBUG level.

Jsp

How to pre-compile JSP?

Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile. Why it is mentioned as pre compile instead of compilation is that, the request is not served. That is, the JSP will not be executed and the request will not be serviced. Just it will be compiled and the implementation class will be generated.
The jsp_precompile parameter may have no value, or may have values true or false. It should not have any other values like ?jsp_precompile=yes – this will result in HTTP error 500.
So the example for query strings to pre compile jsp files are
?jsp_precompile
?jsp_precompile=true
?jsp_precompile=false
?foobar=foobaz&jsp_precompile=true
?foobar=foobaz&jsp_precompile=false

How to do pre compile for a bunch of JSP files? for all JSPs in a folder or application?

There are no special features available for this in the JSP specification. But the application servers (JSP containers) provide methods to do this on their own way. At the end of this tutorial we will see how to pre compile JSP files for Apache Tomcat 6.
But if you want to pre compile in server independent manner you have to use jsp_precompile request parameter and no other option available. To do it for the whole application, you can custome write a servlet or jsp file which will raise a request for all the JSPs available with jsp_precompile added as parameter.

Following JSP will pre compile all JSPs available in a folder and its subfolder:

<%@ page import="javax.servlet.*,javax.servlet.http.*,javax.servlet.jsp.* "%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>
<%!
  private void preCompileJsp(PageContext pageContext, JspWriter out,
   HttpServletRequest request, HttpServletResponse response, String uripath)
   throws IOException, ServletException {
 
     // getting jsp files list for pre compilation
     Set jspFilesSet = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator jspFilesSetItr = jspFilesSet.iterator(); jspFilesSetItr.hasNext();) {
         String uri = (String) jspFilesSetItr.next();
         if (uri.endsWith(".jsp")) {
             RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
             if (rd == null) throw new Error(uri +" - not found");
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             preCompileJsp(pageContext, out, request, response, uri);
         }
     }
   }
%>
<html><head><title>Pre Compile JSP Files</title></head>
<body>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
      public String getQueryString() {
          // setting the pre compile parameter
          return "jsp_precompile";
      };
  };
  preCompileJsp(pageContext, out, req, response, "/");
%>
JSP files Pre Compile Completed.
</body></html>

How to pre compile JSP from command line?

Yes you can compile JSP files from command line. There are no specific tool promoted or authored by JSP specification or SUN. The right choice is to depend on application server for which we are compiling application or JSP the JSP files. Logic is to fork the JSP compiler mostly JSPC from command prompt using a utility like ANT.
I will give an example for the popular Apache Tomcat using ANT tool to pre compile JSP files. Important step is to write the ANT build script which will take through the compilation process. Using this ant script, either you can pre compile JSP files from command prompt or you can integrate the step of pre compiling JSP files into the build process which creates the distributable (WAR) file of your application.

Apache Tomcat 6.0 uses Eclipse JDT Java compiler to perform JSP java source code compilation.

<project name="Webapp Precompilation" default="all" basedir=".">
   <import file="${tomcat.home}/bin/catalina-tasks.xml"/>
   <target name="jspc">
<jasper
             validateXml="false"
             uriroot="${webapp.path}"
             webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
             outputDir="${webapp.path}/WEB-INF/src" />
  </target>
  <target name="compile">
    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    <mkdir dir="${webapp.path}/WEB-INF/lib"/>
    <javac destdir="${webapp.path}/WEB-INF/classes"
           optimize="off"
           debug="on" failonerror="false"
           srcdir="${webapp.path}/WEB-INF/src"
excludes="**/*.smap">
      <classpath>
        <pathelement location="${webapp.path}/WEB-INF/classes"/>
        <fileset dir="${webapp.path}/WEB-INF/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/lib"/>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
      </classpath>
      <include name="**" />
      <exclude name="tags/**" />
    </javac>
  </target>
  <target name="all" depends="jspc,compile">
  </target>
  <target name="cleanup">
    <delete>
        <fileset dir="${webapp.path}/WEB-INF/src"/>
        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
    </delete>
  </target>
</project>
Use the above ant script and execute the following command to pre compile JSP files from command prompt:
$ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>

The benefits of pre-compiling a JSP page:

It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.
Since the Java compiler is not needed, there will be a reduction of the footprint needed to run a JSP container.
In include directives, tag library references, and translation-time actions used in custom actions, compilation of a JSP page provides resolution of relative URL specifications.

Scope of JSP Objects

The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object created in a JSP page will have a scope. Object scope in JSP is segregated into four parts and they are page, request, session and application.
  • page
    ‘page’ scope means, the JSP object can be accessed only from within the same page where it was created. The default scope for JSP objects created using <jsp:useBean> tag is page. JSP implicit objects out, exception, response, pageContext, config and page have ‘page’ scope.
  • request
    A JSP object created using the ‘request’ scope can be accessed from any pages that serves that request. More than one page can serve a single request. The JSP object will be bound to the request object. Implicit object request has the ‘request’ scope.
  • session
    ‘session’ scope means, the JSP object is accessible from pages that belong to the same session from where it was created. The JSP object that is created using the session scope is bound to the session object. Implicit object session has the ‘session’ scope.
  • application
    A JSP object created using the ‘application’ scope can be accessed from any pages across the application. The JSP object is bound to the application object. Implicit object application has the ‘application’ scope.

Difference between forward and sendRedirect

forward

Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.
For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.
‘session’ is not lost in both forward and redirect.
To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.

When can we use forward and when can we use sendRedirect?

Technical scenario: redirect should be used
  1. If you need to transfer control to different domain
  2. To achieve separation of task.
For example, database update and data display can be separated by redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.

Example for forward and sendRedirect based on real world

Consider the real world scenario, the milk man comes and asks for monthly payment to you in your house. Here house is the container and you are a resource existing in the container. Milk man is the client or browser.
He asks for the monthly payment to you, this is the request made by the browser to resource A. If you go inside your house and ask your mother (another resource B inside the same container) for the cash and come back and deliver to milkman this is called forward.
If you ask the milkman to speak himself to your mother inside your house or you ask the milkman to speak to your father who is in his office (different domain) then this is called redirect.

JSP Comments

There is only one type of JSP comment available by JSP specification.
JSP Comment Syntax:
<%-- comment --%>
This JSP comment tag tells the JSP container to ignore the comment part from compilation. That is, the commented part of source code is not considered for the content parsed for ‘response’.
Example:
<%-- This JSP comment part will not be included in the response object --%>

Is this a JSP Comment?

<!-- comment --> is not a JSP comment. This is HTML comment. The JSP container treats this HTML comment tag as equal as any other HTML tags. When view source is done, the content given between this tag is visible. This is not anyway related to the JSP container, it is the expected behaviour of this HTML tag.

Example

<!-- This HTML comment part is included in the response object and can be seen in view source -->
// or /* comment */ used inside the <% %> scriplet tag is also not a JSP comment. This is just a java comment and JSP container doesn’t reserve any special treatment for this comments usage.
Therefore, there is nothing called as hidden comment or output comment in JSP by specification.

JSP Implicit Objects

JSP Implicit objects are created by the web container. These implicit objects are Java objects that implement interfaces in the Servlet and JSP API. Scripting elements in a JSP page can make use of these JSP implicit objects. There are nine (9) JSP implicit objects available.

JSP Implicit Objects are as follows:

  1. request implicit object

    The JSP implicit request object is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. It represents the request made by the client. The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
  2. response implicit object

    The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
  3. out implicit object

    The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.
  4. session implicit object

    The JSP implicit session object is an instance of a java class that implements the javax.servlet.http.HttpSession interface. It represents a client specific conversation. The session implicit object is used to store session state for a single user.
  5. application implicit object

    The JSP implicit application object is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.
  6. exception implicit object

    The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.
  7. config implicit object

    The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
  8. page implicit object

    The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not advisable to use this page implict object often as it consumes large memory.
  9. pageContext implicit object

    The JSP implicit pageContext object is an instance of the javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it provides methods to get and set attributes in different scopes and for transfering requests to other resources. Also it contains the reference to to implicit objects.

Difference between JSP include directive and JSP include action

  • <%@ include file=”filename” %> is the JSP include directive.
    At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers. The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output.
  • <jsp:include page=”relativeURL” /> is the JSP include action element.
    The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters. If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

    Difference between _jspService() and other life cycle methods.

    JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().
    The contents what we write in the JSP will go into _jspService() because we are implicitly implementing it. If we again try to override it explicitly, JSP compliler will giver error as ‘the method is already implemented and cannot override’. But in the case of other two methods we are not implementing it in the JSP. Therefore the JSP compiler will allow to override jspInit() and jspDestroy().
    To show this difference _jspService() method is prefixed with ‘_’ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes.

    JSP Life Cycle – explain.

    JSP’s life cycle can be grouped into following phases.

    1. JSP Page Translation:

    A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

    2. JSP Page Compilation:

    The generated java servlet file is compiled into a java servlet class.
    Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

    3. Class Loading:

    The java servlet class that was compiled from the JSP source is loaded into the container.

    4. Execution phase:

    In the execution phase the container manages one or more instances of this class in response to requests and other events.
    The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

    5. Initialization:

    jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

    6. _jspService() execution:

    This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

    7. jspDestroy() execution:

    This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
    jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

Java Gallery

Wordle – Word Clouds

From now onwards I am starting up a series, where in I will share cool java applications that I come across. I don’t want to keep my blog stiff. Even some friends have started commenting that, we get exam fever when we stumble on javapapers.com
Sometimes I couldn’t resist myself when I see a nice thing that I feel like introducing to others. So how is it going to get related with javapapers? Will I post about a nice secret joke that I came across. No! as always I will stick to java.
So how can you identify this series? Watch out for the tag (look at the url) – “java-gallery”. Now over to the first cool thing :)
I came across a website named wordle, which generates word clouds. Its awesome! Done using java platform. You should have java in your machine to run that. If you came to javapapers.com thinking that its about coffee, then this site is not for you.
I am dumbstruck by the options it gives. Its not just a toy, it has loads and loads of logic behind it. You may wonder how useful it is? There are many ways, wordle can be useful, starting with generating a nice image for you T-shirt. More than worrying about the usefulness, I wish to appreciate the innovate idea.
Couple of images generated using wordle with source as javapapers.com

just click this image to see the same in large size.
I hope these kind of applications will be an inspiration and will boost the energy of the creator inside everybody.

Design Patterns

Decorator Pattern

To extend or modify the behaviour of ‘an instance’ at runtime decorator design pattern is used. Inheritance is used to extend the abilities of ‘a class’. Unlike inheritance, you can choose any single object of a class and modify its behaviour leaving the other instances unmodified.
In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.

Design of decorator pattern

You start with an interface which creates a blue print for the class which will have decorators. Then implement that interface with basic functionalities. Till now we have got an interface and an implementation concrete class. Create an abstract class that contains (aggregation relationship) an attribute type of the interface. The constructor of this class assigns the interface type instance to that attribute. This class is the decorator base class. Now you can extend this class and create as many concrete decorator classes. The concrete decorator class will add its own methods. After / before executing its own method the concrete decorator will call the base instance’s method. Key to this decorator design pattern is the binding of method and the base instance happens at runtime based on the object passed as parameter to the constructor. Thus dynamically customizing the behavior of that specific instance alone.

Decorator Design Pattern – UML Diagram


Implementation of decorator pattern

Following given example is an implementation of decorator design pattern. Icecream is a classic example for decorator design pattern. You create a basic icecream and then add toppings to it as you prefer. The added toppings change the taste of the basic icecream. You can add as many topping as you want. This sample scenario is implemented below.
package com.javapapers.sample.designpattern;
 
public interface Icecream {
  public String makeIcecream();
}
The above is an interface depicting an icecream. I have kept things as simple as possible so that the focus will be on understanding the design pattern. Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.
package com.javapapers.sample.designpattern;
 
public class SimpleIcecream implements Icecream {
 
  @Override
  public String makeIcecream() {
    return "Base Icecream";
  }
 
}
Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.
package com.javapapers.sample.designpattern;
 
abstract class IcecreamDecorator implements Icecream {
 
  protected Icecream specialIcecream;
 
  public IcecreamDecorator(Icecream specialIcecream) {
    this.specialIcecream = specialIcecream;
  }
 
  public String makeIcecream() {
    return specialIcecream.makeIcecream();
  }
}
Following two classes are similar. These are two decorators, concrete class implementing the abstract decorator. When the decorator is created the base instance is passed using the constructor and is assigned to the super class. In the makeIcecream method we call the base method followed by its own method addNuts(). This addNuts() extends the behavior by adding its own steps.
package com.javapapers.sample.designpattern;
 
public class NuttyDecorator extends IcecreamDecorator {
 
  public NuttyDecorator(Icecream specialIcecream) {
    super(specialIcecream);
  }
 
  public String makeIcecream() {
    return specialIcecream.makeIcecream() + addNuts();
  }
 
  private String addNuts() {
    return " + cruncy nuts";
  }
}
package com.javapapers.sample.designpattern;
 
public class HoneyDecorator extends IcecreamDecorator {
 
  public HoneyDecorator(Icecream specialIcecream) {
    super(specialIcecream);
  }
 
  public String makeIcecream() {
    return specialIcecream.makeIcecream() + addHoney();
  }
 
  private String addHoney() {
    return " + sweet honey";
  }
}

Execution of the decorator pattern

I have created a simple icecream and decorated that with nuts and on top of it with honey. We can use as many decorators in any order we want. This excellent flexibility and changing the behaviour of an instance of our choice at runtime is the main advantage of the decorator design pattern.
package com.javapapers.sample.designpattern;
 
public class TestDecorator {
 
  public static void main(String args[]) {
    Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
    System.out.println(icecream.makeIcecream());
  }
 
}

Output

Base Icecream + cruncy nuts + sweet honey

Decorator Design Pattern in java API

java.io.BufferedReader;
java.io.FileReader;
java.io.Reader;
The above readers of java API are designed using decorator design pattern.

Adapter Pattern

An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need.
In real world the easy and simple example that comes to mind for an adapter is the travel power adapter. American socket and plug are different from British. Their interface are not compatible with one another. British plugs are cylindrical and American plugs are recangularish. You can use an adapter in between to fit an American (rectangular) plug in British (cylindrical) socket assuming voltage requirements are met with.

How to implement adapter design pattern?

Adapter design pattern can be implemented in two ways. One using the inheritance method and second using the composition method. Just the implementation methodology is different but the purpose and solution is same.

Adapter implementation using inheritance

When a class with incompatible method needs to be used with another class you can use inheritance to create an adapter class. The adapter class which is inherited will have new compatible methods. Using those new methods from the adapter the core function of the base class will be accessed. This is called “is-a” relationship. The same real world example is implemented using java as below. Dont worry too much about logic, following example source code attempts to explain adapter design pattern and the goal is simplicity.
public class CylindricalSocket {
  public String supply(String cylinStem1, String cylinStem1) {
    System.out.println("Power power power...");
  }
}
 
public class RectangularAdapter extends CylindricalSocket {
  public String adapt(String rectaStem1, Sting rectaStem2) {
    //some conversion logic
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return supply(cylinStem1, cylinStem2);
  }
}
 
public class RectangularPlug {
  private String rectaStem1;
  private String rectaStem2;
  public getPower() {
    RectangulrAdapter adapter = new RectangulrAdapter();
    String power = adapter.adapt(rectaStem1, rectaStem2);
    System.out.println(power);
  }
}

Adapter implementation using composition

The above implementation can also be done using composition. Instead of inheriting the base class create adapter by having the base class as attribute inside the adapter. You can access all the methods by having it as an attribute. This is nothing but “has-a” relationship. Following example illustrates this approach. Difference is only in the adapter class and other two classes are same. In most scenarios, prefer composition over inheritance. Using composition you can change the behaviour of class easily if needed. It enables the usage of tools like dependency injection.
public class CylindricalSocket {
  public String supply(String cylinStem1, String cylinStem1) {
    System.out.println("Power power power...");
  }
}
 
public class RectangularAdapter {
  private CylindricalSocket socket;
 
  public String adapt(String rectaStem1, Sting rectaStem2) {
    //some conversion logic
    socket = new CylindricalSocket();
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return socket.supply(cylinStem1, cylinStem2);
  }
}
 
public class RectangularPlug {
  private String rectaStem1;
  private String rectaStem2;
  public getPower() {
    RectangulrAdapter adapter = new RectangulrAdapter();
    String power = adapter.adapt(rectaStem1, rectaStem2);
    System.out.println(power);
  }
}

Adapter design pattern in java API

java.io.InputStreamReader(InputStream)
java.io.OutputStreamWriter(OutputStream)

Singleton Pattern

Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.
The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }
You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
This article is an attempt to explain the basics on singleton design pattern. If you want more insight on singleton refer this technical article “When is a Singleton not a Singleton?” and its references.

Usage of Singleton Patter in Java API

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

Prototype Pattern

When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs.
Its a simple and straight forward design pattern. Nothing much hidden beneath it. If you don’t have much experience with enterprise grade huge application, you may not have experience in creating a complex / time consuming instance. All you might have done is use the new operator or inject and instantiate.
If you are a beginner you might be wondering, why all the fuss about prototye design pattern and do we really need this design pattern? Just ignore, all the big guys requires it. For you, just understand the pattern and sleep over it. You may require it one day in future.
Prototype pattern may look similar to builder design pattern. There is a huge difference to it. If you remember, “the same construction process can create different representations” is the key in builder pattern. But not in the case of prototype pattern.
So, how to implement the prototype design pattern? You just have to copy the existing instance in hand. When you say copy in java, immediately cloning comes into picture. Thats why when you read about prototype pattern, all the literature invariably refers java cloning.
Simple way is, clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need. Therefore whenever you clone that object you will directly get the new object of desire without modifying the created object explicitly.
The prototype design pattern mandates that the instance which you are going to copy should provide the copying feature. It should not be done by an external utility or provider.
But the above, other way comes with a caution. If somebody who is not aware of your tweaking the clone business logic uses it, he will be in issue. Since what he has in hand is not the exact clone. You can go for a custom method which calls the clone internally and then modifies it according to the need. Which will be a better approach.
Always remember while using clone to copy, whether you need a shallow copy or deep copy. Decide based on your business needs. If you need a deep copy, you can use serialization as a hack to get the deep copy done. Using clone to copy is entirey a design decision while implementing the prototype design pattern. Clone is not a mandatory choice for prototype pattern.
In prototype pattern, you should always make sure that you are well knowledgeable about the data of the object that is to be cloned. Also make sure that instance allows you to make changes to the data. If not, after cloning you will not be able to make required changes to get the new required object.
Following sample java source code demonstrates the prototype pattern. I have a basic bike in hand with four gears. When I want to make a different object, an advance bike with six gears I copy the existing instance. Then make necessary modifications to the copied instance. Thus the prototype pattern is implemented. Example source code is just to demonstrate the design pattern, please don’t read too much out of it. I wanted to make things as simple as possible.

Sample Java Source Code for Prototype Design Pattern

package com.javapapers.sample.designpattern.prototype;
 
class Bike implements Cloneable {
  private int gears;
  private String bikeType;
  private String model;
  public Bike() {
    bikeType = "Standard";
    model = "Leopard";
    gears = 4;
  }
 
  public Bike clone() {
    return new Bike();
  }
 
  public void makeAdvanced() {
    bikeType = "Advanced";
    model = "Jaguar";
    gears = 6;
  }
  public String getModel(){
    return model;
  }
}
 
public class Workshop {
  public Bike makeJaguar(Bike basicBike) {
    basicBike.makeAdvanced();
    return basicBike;
  }
  public static void main(String args[]){
    Bike bike = new Bike();
    Bike basicBike = bike.clone();
    Workshop workShop = new Workshop();
    Bike advancedBike = workShop.makeJaguar(basicBike);
    System.out.println("Prototype Design Pattern: "+advancedBike.getModel());
  }
}

Builder Pattern

Builder pattern is used to construct a complex object step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.
Complex Object Construction
Complex Object Construction
For example, you can consider construction of a home. Home is the final end product (object) that is to be returned as the output of the construction process. It will have many steps, like basement construction, wall construction and so on roof construction. Finally the whole home object is returned. Here using the same process you can build houses with different properties.
GOF says,
“Separate the construction of a complex object from its representation so that the same construction process can create different representations” [GoF 94]

What is the difference between abstract factory and builder pattern?

Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction.

Sample builder design pattern implementation in Java API

DocumentBuilderFactory , StringBuffer, StringBuilder are some examples of builder pattern usage in java API.

Sample Java Source Code for Builder Pattern

Following is the interface, that will be returned as the product from the builder.
package com.javapapers.sample.designpattern.builder;
 
public interface HousePlan {
 
  public void setBasement(String basement);
 
  public void setStructure(String structure);
 
  public void setRoof(String roof);
 
  public void setInterior(String interior);
}
Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory;
 
public interface AnimalFactory {
  public Animal createAnimal();
}
Concrete class for the above interface. The builder constructs an implementation for the following class.
package com.javapapers.sample.designpattern.builder;
 
public class House implements HousePlan {
 
  private String basement;
  private String structure;
  private String roof;
  private String interior;
 
  public void setBasement(String basement) {
    this.basement = basement;
  }
 
  public void setStructure(String structure) {
    this.structure = structure;
  }
 
  public void setRoof(String roof) {
    this.roof = roof;
  }
 
  public void setInterior(String interior) {
    this.interior = interior;
 
  }
 
}
Builder interface. We will have multiple different implementation of this interface in order to facilitate, the same construction process to create different representations.
package com.javapapers.sample.designpattern.builder;
 
public interface HouseBuilder {
 
  public void buildBasement();
 
  public void buildStructure();
 
  public void bulidRoof();
 
  public void buildInterior();
 
  public House getHouse();
}
First implementation of a builder.
package com.javapapers.sample.designpattern.builder;
 
public class IglooHouseBuilder implements HouseBuilder {
 
  private House house;
 
  public IglooHouseBuilder() {
    this.house = new House();
  }
 
  public void buildBasement() {
    house.setBasement("Ice Bars");
  }
 
  public void buildStructure() {
    house.setStructure("Ice Blocks");
  }
 
  public void buildInterior() {
    house.setInterior("Ice Carvings");
  }
 
  public void bulidRoof() {
    house.setRoof("Ice Dome");
  }
 
  public House getHouse() {
    return this.house;
  }
}
Second implementation of a builder. Tipi is a type of eskimo house.
package com.javapapers.sample.designpattern.builder;
 
public class TipiHouseBuilder implements HouseBuilder {
  private House house;
 
  public TipiHouseBuilder() {
    this.house = new House();
  }
 
  public void buildBasement() {
    house.setBasement("Wooden Poles");
  }
 
  public void buildStructure() {
    house.setStructure("Wood and Ice");
  }
 
  public void buildInterior() {
    house.setInterior("Fire Wood");
  }
 
  public void bulidRoof() {
    house.setRoof("Wood, caribou and seal skins");
  }
 
  public House getHouse() {
    return this.house;
  }
 
}
Following class constructs the house and most importantly, this maintains the building sequence of object.
package com.javapapers.sample.designpattern.builder;
 
public class CivilEngineer {
 
  private HouseBuilder houseBuilder;
 
  public CivilEngineer(HouseBuilder houseBuilder){
    this.houseBuilder = houseBuilder;
  }
 
  public House getHouse() {
    return this.houseBuilder.getHouse();
  }
 
  public void constructHouse() {
    this.houseBuilder.buildBasement();
    this.houseBuilder.buildStructure();
    this.houseBuilder.bulidRoof();
    this.houseBuilder.buildInterior();
  }
}
Testing the sample builder design pattern.
package com.javapapers.sample.designpattern.builder;
 
public class BuilderSample {
  public static void main(String[] args) {
    HouseBuilder iglooBuilder = new IglooHouseBuilder();
    CivilEngineer engineer = new CivilEngineer(iglooBuilder);
 
    engineer.constructHouse();
 
    House house = engineer.getHouse();
 
    System.out.println("Builder constructed: "+house);
  }
}

Output of the above sample program for builder pattern

Builder constructed: com.javapapers.sample.designpattern.builder.House@7d772e

Abstract Factory Pattern

Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.
There is also a view that abstract factory is ‘also’ implemented using prototype instead of factory methords pattern. Beginners for now please don’t yourself with that. Just go with factory methods pattern.
As there is a word ‘abstract’ in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is from object oriented programming paradim.

Sample abstract factory design pattern implementation in Java API

XML API implements abstract factory. There is a class name SchemaFactory. This acts as a factory and supports implemenation of multiple schemas using abstract factory design pattern.

Sample Java Source Code for Factory Method Design Pattern

Following is the interface, that will be returned as the final end product from the factories.
package com.javapapers.sample.designpattern.abstractfactory;
 
public interface Animal {
  public void breathe();
}
Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory;
 
public interface AnimalFactory {
  public Animal createAnimal();
}
One of the factory from a predefined set which will instantiate the above interface.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class SeaFactory implements AnimalFactory {
 
  public Animal createAnimal() {
    return new Shark();
  }
 
}
Second factory from a predefined set which will instantiate the Animal interface.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class LandFactory implements AnimalFactory {
  public Animal createAnimal() {
    return new Elephant();
  }
}
Implementation of an Animal. This class is grouped with the first abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class Shark implements Animal {
  public void breathe() {
    System.out.println("I breathe in water! He he!");
  }
}
Implementation of an Animal. This class is grouped with the second abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class Elephant implements Animal {
  public void breathe() {
    System.out.println("I breathe with my lungs. Its easy!");
  }
}
Following class consumes the abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class Wonderland {
  public Wonderland(AnimalFactory factory) {
    Animal animal = factory.createAnimal();
    animal.breathe();
  }
}
Testing the abstract factory design pattern.
package com.javapapers.sample.designpattern.abstractfactory;
 
public class SampleAbstractFactory {
 
  public static void main(String args[]){
    new Wonderland(createAnimalFactory("water"));
  }
 
  public static AnimalFactory createAnimalFactory(String type){
    if("water".equals(type))
      return new SeaFactory();
    else
      return new LandFactory();
  }
}

Output of the above sample program for abstract factory pattern

I breathe in water! He he!

Factory Method Pattern

05/11/2009
A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.
Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Sample factory method design pattern implementation in Java API

For a reference of how the factory method design pattern is implemented in Java, you can have a look at SAXParserFactory. It is a factory class which can be used to intantiate SAX based parsers to pares XML. The method newInstance is the factory method which instantiates the sax parsers based on some predefined logic.

Block diagram for The Design Pattern

factorydesignpattern

Sample Java Source Code for Factory Method Design Pattern

Based on comments received from users, I try to keep my sample java source code as simple as possible for a novice to understand.
Base class:
package com.javapapers.sample.designpattern.factorymethod;
 
//super class that serves as type to be instantiated for factory method pattern
public interface Pet {
 
 public String speak();
 
}
First subclass:
package com.javapapers.sample.designpattern.factorymethod;
 
//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {
 
 public String speak() {
 return "Bark bark...";
 }
}
Second subclass:
package com.javapapers.sample.designpattern.factorymethod;
 
//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
 public String speak() {
 return "Quack quack...";
 }
}
Factory class:
package com.javapapers.sample.designpattern.factorymethod;
 
//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {
 
 public Pet getPet(String petType) {
 Pet pet = null;
 
 // based on logic factory instantiates an object
 if ("bark".equals(petType))
 pet = new Dog();
 else if ("quack".equals(petType))
 pet = new Duck();
 return pet;
 }
}
Using the factory method to instantiate
package com.javapapers.sample.designpattern.factorymethod;
 
//using the factory method pattern
public class SampleFactoryMethod {
 
 public static void main(String args[]){
 
 //creating the factory
 PetFactory petFactory = new PetFactory();
 
 //factory instantiates an object
 Pet pet = petFactory.getPet("bark");
 
 //you don't know which object factory created
 System.out.println(pet.speak());
 }
 
}

Output of the above sample program for Factory Method Pattern

Bark bark

Download Java Source Code For Factory Method Pattern

Introduction To Design Patterns

Pattern is a defined, used and tested solution for a know problem. Design patterns is all about re-use. Software design patterns evolved as a subject of study only when object oriented programming started becoming popular. OOPS and design patterns became inseparable.
In OOPS, we should have well defined boundaries for objects. That is every object should have its roles and responsibilities well defined. Then at next level, we should have a clear interaction plan between objects. If you design a OO software with the above principle, then by default you will be following some of the already defined design patterns.
A formal definition for design patterns, “A design pattern addresses a recurring design problem that arises in specific design situations and presents a solution to it” (Buschmann, et. al. 1996)
Java widely uses design patterns in its APIs. It started as early as Java 1.2 in java foundation classes. By then you can see the widespread use of commonly know design patterns in collections framework and IO packages. When I say commonly known design patterns, I mention about the set of 23 design patterns by Gang of Four (GOF). Gamma, Helm, Johnson and Vlissides known as Gang of Four (GOF) published a book “Design Patterns — Elements of Reusable Software” (1995) based on their series of technical meetings. It is one of the best seller in computer science books till date.
In China gang of four means different set of people. Jiang Qing (Mao Zedong’s fourth wife), Zhang Chunqiao, Yao Wenyuan, and Wang Hongwen were very popular leaders of cultural revolution. They almost seized power after Mao Zedong’s death. But they were finally arrested and imprisoned for life.
Our GOF divided the 23 design patterns into three types creational design patterns, structural design patterns and behavioral design patterns.
Creational design patterns can be used to instantiate objects. Instead of instantiating objects directly, depending on scenario either X or Y object can be instantiated. This will give flexibility for instantiation in high complex business logic situations.
Structural design patterns can be used to organize your program into groups. This segregation will provide you clarity and will enable you for easier maintainability.
Behavioral design patterns can be used to define the communication and control flow between objects.
Following this post, I have planned to write a series of article on these design patterns with java source code examples and UML diagrams. Looking forward to your comments.