Java Design Patterns – Example Tutorial

Filed Under: Design Patterns
Java Design Patterns

Design Patterns are very popular among software developers. A design pattern is a well-described solution to a common software problem. I have written extensively on java design patterns. You can download PDF eBook (130+ pages) by subscribing to our newsletter.

Java Design Patterns

Some of the benefits of using design patterns are:

  1. Design Patterns are already defined and provides industry standard approach to solve a recurring problem, so it saves time if we sensibly use the design pattern. There are many java design patterns that we can use in our java based projects.
  2. Using design patterns promotes reusability that leads to more robust and highly maintainable code. It helps in reducing total cost of ownership (TCO) of the software product.
  3. Since design patterns are already defined, it makes our code easy to understand and debug. It leads to faster development and new members of team understand it easily.

java design patterns
Java Design Patterns are divided into three categories – creational, structural, and behavioral design patterns. This post serves as an index for all the java design patterns articles I have written so far.

Design Patterns Video Tutorials

Recently I started video tutorials on Design Patterns and they are uploaded on YouTube. Please subscribe to my YouTube channel as I am planning to upload a lot more videos on Core Java, Spring Framework, etc.

Creational Design Patterns

Creational design patterns provide solution to instantiate a object in the best possible way for specific situations.

1. Singleton Pattern

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java virtual machine. It seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of the Singleton pattern has always been a controversial topic among developers. Check out Singleton Design Pattern to learn about different ways to implement Singleton pattern and pros and cons of each of the method. This is one of the most discussed java design patterns.

2. Factory Pattern

The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class. We can apply a Singleton pattern on the Factory class or make the factory method static. Check out Factory Design Pattern for example program and factory pattern benefits. This is one of the most widely used java design patterns.

3. Abstract Factory Pattern

Abstract Factory pattern is similar to Factory pattern and it’s a factory of factories. If you are familiar with the factory design pattern in java, you will notice that we have a single Factory class that returns the different sub-classes based on the input provided and the factory class uses if-else or switch statements to achieve this.

In Abstract Factory pattern, we get rid of if-else block and have a factory class for each sub-class and then an Abstract Factory class that will return the sub-class based on the input factory class. Check out Abstract Factory Pattern to know how to implement this pattern with example program.

4. Builder Pattern

This pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. Builder pattern solves the issue with a large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object. Check out Builder Pattern for example program and classes used in JDK.<

5. Prototype Pattern

The prototype pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. So this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. This pattern uses java cloning to copy the object.

Prototype design pattern mandates that the Object which you are copying should provide the copying feature. It should not be done by any other class. However whether to use the shallow or deep copy of the Object properties depends on the requirements and it’s a design decision. Check out Prototype Pattern for sample program.

Structural Design Patterns

Structural patterns provide different ways to create a class structure, for example using inheritance and composition to create a large object from small objects.

1. Adapter Pattern

The adapter design pattern is one of the structural design patterns and it’s used so that two unrelated interfaces can work together. The object that joins these unrelated interfaces is called an Adapter. As a real-life example, we can think of a mobile charger as an adapter because the mobile battery needs 3 volts to charge but the normal socket produces either 120V (US) or 240V (India). So the mobile charger works as an adapter between the mobile charging socket and the wall socket. Check out Adapter Pattern for example program and it’s usage in Java.

2. Composite Pattern

Composite pattern is one of the Structural design patterns and is used when we have to represent a part-whole hierarchy. When we need to create a structure in a way that the objects in the structure have to be treated the same way, we can apply the composite design pattern.

Let’s understand it with a real-life example – A diagram is a structure that consists of Objects such as Circle, Lines, Triangle, etc and when we fill the drawing with color (say Red), the same color also gets applied to the Objects in the drawing. Here drawing is made up of different parts and they all have the same operations. Check out Composite Pattern article for different component of composite pattern and example program.

3. Proxy Pattern

Proxy pattern intent is to “Provide a surrogate or placeholder for another object to control access to it”. The definition itself is very clear and proxy pattern is used when we want to provide controlled access of a functionality.

Let’s say we have a class that can run some command on the system. Now if we are using it, it’s fine but if we want to give this program to a client application, it can have severe issues because the client program can issue a command to delete some system files or change some settings that you don’t want. Check out Proxy Pattern post for the example program with implementation details.

4. Flyweight Pattern

The flyweight design pattern is used when we need to create a lot of Objects of a class. Since every object consumes memory space that can be crucial for low memory devices, such as mobile devices or embedded systems, the flyweight design pattern can be applied to reduce the load on memory by sharing objects. String Pool implementation in java is one of the best examples of Flyweight pattern implementation. Check out Flyweight Pattern article for sample program and implementation process.

5. Facade Pattern

Facade Pattern is used to help client applications to easily interact with the system. Suppose we have an application with a set of interfaces to use MySql/Oracle database and to generate different types of reports, such as HTML report, PDF report, etc. So we will have a different set of interfaces to work with different types of databases. Now a client application can use these interfaces to get the required database connection and generate reports. But when the complexity increases or the interface behavior names are confusing, the client application will find it difficult to manage it. So we can apply Facade pattern here and provide a wrapper interface on top of the existing interface to help client application. Check out Facade Pattern post for implementation details and sample program.

6. Bridge Pattern

When we have interface hierarchies in both interfaces as well as implementations, then the bridge design pattern is used to decouple the interfaces from implementation and hiding the implementation details from the client programs. Like the Adapter pattern, it’s one of the Structural design patterns.

The implementation of bridge design pattern follows the notion to prefer Composition over inheritance. Check out Bridge Pattern post for implementation details and sample program.

7. Decorator Pattern

The decorator design pattern is used to modify the functionality of an object at runtime. At the same time, other instances of the same class will not be affected by this, so individual object gets the modified behavior. The decorator design pattern is one of the structural design patterns (such as Adapter Pattern, Bridge Pattern, Composite Pattern) and uses abstract classes or interface with the composition to implement.

We use inheritance or composition to extend the behavior of an object but this is done at compile-time and it’s applicable to all the instances of the class. We can’t add any new functionality to remove any existing behavior at runtime – this is when the Decorator pattern comes into the picture. Check out Decorator Pattern post for sample program and implementation details.

Behavioral Design Patterns

Behavioral patterns provide solution for the better interaction between objects and how to provide lose coupling and flexibility to extend easily.

1. Template Method Pattern

Template Method is a behavioral design pattern and it’s used to create a method stub and deferring some of the steps of implementation to the subclasses. The template method defines the steps to execute an algorithm and it can provide a default implementation that might be common for all or some of the subclasses.

Suppose we want to provide an algorithm to build a house. The steps that need to be performed to build a house are – building a foundation, building pillars, building walls, and windows. The important point is that we can’t change the order of execution because we can’t build windows before building the foundation. So, in this case, we can create a template method that will use different methods to build the house. Check out Template Method Pattern post for implementation details with example program.

2. Mediator Pattern

The mediator design pattern is used to provide a centralized communication medium between different objects in a system. The mediator design pattern is very helpful in an enterprise application where multiple objects are interacting with each other. If the objects interact with each other directly, the system components are tightly coupled with each other which makes maintainability cost higher and not flexible to extend easily. The mediator pattern focuses on to provide a mediator between objects for communication and help in implementing lose-coupling between objects.

Air traffic controller is a great example of a mediator pattern where the airport control room works as a mediator for communication between different flights. The mediator works as a router between objects and it can have it’s own logic to provide a way of communication. Check out Mediator Pattern post for implementation details with example program.

3. Chain of Responsibility Pattern

The chain of responsibility pattern is used to achieve loose coupling in software design where a request from the client is passed to a chain of objects to process them. Then the object in the chain will decide who will be processing the request and whether the request is required to be sent to the next object in the chain or not.

We know that we can have multiple catch blocks in a try-catch block code. Here every catch block is kind of a processor to process that particular exception. So when an exception occurs in the try block, it’s sent to the first catch block to process. If the catch block is not able to process it, it forwards the request to the next object in chain i.e next catch block. If even the last catch block is not able to process it, the exception is thrown outside of the chain to the calling program.

ATM dispense machine logic can be implemented using Chain of Responsibility Pattern, check out the linked post.

4. Observer Pattern

An observer design pattern is useful when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the object that watches on the state of another object is called Observer and the object that is being watched is called Subject.

Java provides an inbuilt platform for implementing Observer pattern through java.util.Observable class and java.util.Observer interface. However, it’s not widely used because the implementation is really simple and most of the time we don’t want to end up extending a class just for implementing Observer pattern as java doesn’t provide multiple inheritances in classes.

Java Message Service (JMS) uses Observer pattern along with Mediator pattern to allow applications to subscribe and publish data to other applications. Check out Observer Pattern post for implementation details and example program.

5. Strategy Pattern

Strategy pattern is used when we have multiple algorithms for a specific task and the client decides the actual implementation be used at runtime.

A strategy pattern is also known as Policy Pattern. We define multiple algorithms and let client applications pass the algorithm to be used as a parameter. One of the best examples of this pattern is the Collections.sort() method that takes the Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.

Check out Strategy Pattern post for implementation details and example program.

6. Command Pattern

Command Pattern is used to implement lose coupling in a request-response model. In command pattern, the request is send to the invoker and invoker pass it to the encapsulated command object. Command object passes the request to the appropriate method of Receiver to perform the specific action.

Let’s say we want to provide a File System utility with methods to open, write, and close the file and it should support multiple operating systems such as Windows and Unix.

To implement our File System utility, first of all, we need to create the receiver classes that will actually do all the work. Since we code in terms of Java interfaces, we can have FileSystemReceiver interface and it’s implementation classes for different operating system flavors such as Windows, Unix, Solaris, etc. Check out Command Pattern post for the implementation details with example program.

7. State Pattern

The state design pattern is used when an Object changes its behavior based on its internal state.

If we have to change the behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. The state pattern is used to provide a systematic and loosely coupled way to achieve this through Context and State implementations.

Check out State Pattern post for implementation details with example program.

8. Visitor Pattern

The visitor pattern is used when we have to perform an operation on a group of similar kinds of Objects. With the help of a visitor pattern, we can move the operational logic from the objects to another class.

For example, think of a Shopping cart where we can add a different type of items (Elements), when we click on the checkout button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move out this logic to another class using the visitor pattern. Let’s implement this in our example of a visitor pattern. Check out Visitor Pattern post for implementation details.

9. Interpreter Pattern

is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar.

The best example of this pattern is a java compiler that interprets the java source code into byte code that is understandable by JVM. Google Translator is also an example of an interpreter pattern where the input can be in any language and we can get the output interpreted in another language.

Check out Interpreter Pattern post for example program.

10. Iterator Pattern

Iterator pattern in one of the behavioral patterns and it’s used to provide a standard way to traverse through a group of Objects. Iterator pattern is widely used in Java Collection Framework where Iterator interface provides methods for traversing through a collection.

Iterator pattern is not only about traversing through a collection, but we can also provide different kinds of iterators based on our requirements. Iterator pattern hides the actual implementation of traversal through the collection and client programs just use iterator methods. Check out Iterator Pattern post for example program and implementation details.

11. Memento Pattern

The memento design pattern is used when we want to save the state of an object so that we can restore later on. Memento pattern is used to implement this in such a way that the saved state data of the object is not accessible outside of the object, this protects the integrity of saved state data.

Memento pattern is implemented with two objects – Originator and Caretaker. The originator is the object whose state needs to be saved and restored and it uses an inner class to save the state of Object. The inner class is called Memento and it’s private so that it can’t be accessed from other objects.

Check out Memento Pattern for sample program and implementation details.

Miscellaneous Design Patterns

There are a lot of design patterns that doesn’t come under GoF design patterns. Let’s look at some of these popular design patterns.

1. DAO Design Pattern

DAO design pattern is used to decouple the data persistence logic to a separate layer. DAO is a very popular pattern when we design systems to work with databases. The idea is to keep the service layer separate from the Data Access layer. This way we implement the separation of Logic in our application.

Checkout DAO Pattern for complete details and example program.

2. Dependency Injection Pattern

Dependency Injection allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable, and maintainable. We can implement dependency injection in java to move the dependency resolution from compile-time to runtime. Spring framework is built on the principle of dependency injection.

Read more about Dependency Injection Pattern to understand how to implement it in our Java application.

3. MVC Pattern

MVC Pattern is one of the oldest architectural patterns for creating web applications. MVC stands for Model-View-Controller.

Checkout MVC Pattern for more details and complete example code.

That’s all for different design patterns in Java. This post intent is to provide an index to browse all of them easily.

You can checkout Java Design Patterns example code from our GitHub Repository.


  1. Nilesh says:

    Hi Pankaj,

    Thanks for these pdf books. Within 2 minutes of registration all the books was available in my mail box. Really appreciate your efforts. Looking forward for books on Spring Security, Spring REST and many more.

  2. Shubham Bhopale says:

    Hi Pankaj,

    I really love your blogs as they are quite detailed. The only thing which is bothering me is that the ADD pop-ups on your website. They are really ruining the User Experience which I hope you understand is one of the important part of any website UI.

    If you can do something about it then that would really help.


    1. Pankaj says:

      We have ads because they pay the bills for the website as well as my expenses.

  3. Perk says:

    Which one are J2EE Design Patterns, are they on the list above?
    And which one are the most common and must know them on interview?

    One more question. All those tutorials for beginners java developers (yt, udemy,…) are created usually in which design pattern?

    I never before pay attention on design patterns. On all tutorials which I use, free and bought I never heard any of those teacher that they are mentioned any design pattern. I know they exist but how I see at the interview they ask about them.

  4. Adhithyan says:

    Thanks for this excellent collection.

  5. Saurabh says:

    This is the 100th time I am returning to this page. Great content I always come here to get the information about the design patterns to re-revise. Thank you for the content

    1. Pankaj says:

      Thanks for the appreciation friend, I hope you have liked all our content. We believe in Quality over Quantity…

  6. Gaurav says:

    Not receiving the book. Button only sticks to sending…

  7. Santosh Sali says:

    Nice Article. thanks for walking extra mile for us.

  8. APRILIA says:

    thank you for your sharing

  9. Enzo Cheng says:

    No subscription link found in my mail box, spam or trash, please help

    1. Mohammed says:

      Hi Pankaj Sir,

      I love reading your articles here as they are in simple English and easy to understand the way you have explained.
      I have also subscribed to your newsletter.
      Can’t wait more for the ebook about Design Patterns.

      Thank you and keep helping us 🙃🙃

  10. Fantine says:

    How can I get the ebook please?

  11. thereader says:

    Can you please tell us, what are all the bunch of technologies & tools used to build this website?

  12. Pantifik says:

    Hi, i also subscribed but did’t receive e-mail 🙁

    1. Pankaj says:

      Please check your spam folder. Also, did you click the subscription confirmation button in the first email?

  13. Sujeet Kumar says:

    i subscribed this website but i unable to download the eBook (130+ pages) . please help

    1. Pankaj says:

      Check your email for the download link.

  14. subrat says:

    hi pankaj kindly tell me the profiler design pattern………………………..

  15. Ganesh says:

    awesome bro. great article. I really appreciate your effort.

  16. Rimpi says:

    B. B
    LL. BL
    UUU. BLU
    How to print this pattern

    1. Anirban says:

      Scanner sc = new Scanner ( );

      //Input your String

      String inputString = sc.nextLine();

      int lengthOfString = inputString.length();

      for(int i = 0; i < lengthOfString ; i ++ ) {

      for ( int j = 0; j <= i ; j ++ ) {

      System.out.print ( inputString.charAt (i ));


      System.out.println ( inputString.substring ( 0, i + 1 ). );


    2. mahesh says:

      String s=”BLUEJ”;
      StringBuffer sb;
      StringBuffer sb2;
      char [] c = s.toCharArray();
      for(int i=1; i<=c.length; i++){
      sb=new StringBuffer();
      sb2=new StringBuffer();
      for(int j=1; j<=i; j++){

    3. raksha says:

      System.out.println(“B. B”);
      System.out.println(“LL. BL”);
      System.out.println(“UUU. BLU”);
      System.out.println(“EEEE. BLUE”);
      System.out.println(“JJJJJJ BLUEJ”);
      System.out.println(“How to print this pattern”);

      ez af.

      1. Sr says:

        It’s just funny answer.. Haha

  17. Abbin Varghese says:

    Very nice article. Thanks for all the information.

    One thing i missed in these is that, the explanations are according to the package structure. I think first we should think about the use case, and then the pattern.

    For eg. “Mediator design pattern is very helpful in an enterprise application where multiple objects are interacting with each other.” But when do we decide objects should interact with each other and why not Observer Pattern or Visitor Pattern? What we should or shouldn’t use this patterns from a real life scenario ?

    If these informations are added, this will be a perfect article.. 🙂

  18. KRISHNA KANT says:

    How can I download ebook for of this tutorial ?

    1. Iqbal Hossain says:

      How can I download ebook for of this tutorial ?

      1. Abdullah says:

        How can I download ebook for of this tutorial ?

        1. pratk says:

          How can I download ebook for of this tutorial?

          1. Pankaj says:

            Subscribe to the newsletter and you will get the eBook in the email.

  19. Kiran Kanaparthi says:

    Can You sort the Design pattern names Alphabetically(just like the in GOF book), then it will be easier to follow them and memorize.

    1. Manish Nandaniya says:

      Dear Pankaj, is a cool website, the contents also are good. I prefer to read java tutorials from here. I use android phone for reading. This website is completely mobile friendly and responds good in both landscape and portrait modes. Just one minor issue I face, is that, the top JournalDev toolbar (having navigation menu button on left and search button on right) covers much of the content in landscape mode leaving less readable screen. Can you improve the site view in this way, if possible? Thanks 🙂

  20. xubing says:

    could you send the pdf ebook for me

  21. Uday says:

    How do we adapt the version changes of common library like Apache in our existing code ?

    For example , if I am using method of some common library in multiple classes and method signature get changed in upgrade version ?

    what is the best solution not to make changes in all classes rather then in single point ?

    My guess : Creat a separate class and use the common method inside the class and use this class reference everywhere .

    1. Nishant says:

      Adapter patter serves best here , the client program would adapt to the changes via the adapter class.

    2. Nishant says:

      An adapter pattern would server best here. I was a bit surprised as the Apache libs are usually backward compatible.

  22. This is by far the most comprehensive tutorial / guide I’ve come across.

  23. Emanuel says:

    How to do this please is very important
    W I N D H O E K
    W I N D H O E
    W I N D H O
    W I N D H
    W I N D
    W I N
    W I
    L I
    L I N
    L I N G
    L I N G U
    L I N G U A

    1. S U R A J says:

      for i in range(0,len(s)):
      for j in range(0,len(s)-i):
      print(s[j],end=” “)
      if i!=len(s)-1:
      for i in range(0,len(t)+1):
      for j in range(0,i):
      print(t[j],end=” “)

    2. Roy El Asmar says:

      public class MyClass {
      public static void main(String args[]) {
      String s1=”WINDHOEK”;
      String s2=”LINGUA”;
      for(int i=s1.length()-1;i>=0;i–){
      for(int j=0;j<=s2.length()-1;j++){

    3. Abhishek says:

      String a=”WINDHOEK”;
      String b=”LINGUA”;
      String s=””;
      int temp=a.length();

      for(int i=a.length()-1;i>=0;i–)
      for(int j=0;j<=i;j++)

      for(int i=0;i=0;j–)

  24. Geethu says:

    Hi Pankaj,

    Consider a situation where our management has decided to integrate a new jar instead of old one. The new jar provides the same set of operations which was used by old jar, but the number of arguments or the datatype of the argument ( header parameter of the function) is different from the existing. It will be very difficult to change the method parameters across the application.
    Which design pattern suits well in this case with minimum number of modification in the application?


    1. Amit Bhatia says:


  25. Stefan says:

    Slight typo on the section for Bridge Pattern it says ” When we have interface hierarchies in both interfaces as well as implementations, then builder design pattern “….. but we are talking about the Bridget Pattern and Structural Patterns

    1. Pankaj says:

      Thanks for the tip, corrected the typo error.

  26. ArsalImam says:

    Great blog

  27. Luke Fan says:

    It’s good for me. Thank you for these.

  28. tathagata bhattacharya says:

    I need help.Can you help me in this:

    15 14 13 12 11
    10 9 8 7
    6 5 4
    3 2

    1. Anonymous says:

      void main()
      int i,j,a=15;
      for(i =1;i=I;j–)


    2. Maruthi says:

      void main()
      int i,j,a=15;

      for(i =5;i<1;i–)
      for(j =1;j<i;j++)

    3. Srikanth says:

      public static void main(String[] args) {

      Scanner s = new Scanner(;
      System.out.println(“Enter the number”);
      int value = Integer.parseInt(;
      int numberOfNumbers =0;
      int count=1;
      int row =1;
      for(int i = 1;i<=value;i++){
      row =i;
      numberOfNumbers = i * count;

      } else {
      numberOfNumbers = (i*count)+count;


      if(numberOfNumbers == value){

      } else if (numberOfNumbers value){




      System.out.println(“all “+numberOfNumbers+” numbers to be displayed in number of rows is “+row);

      for(int i=row; i>=1;i–){
      for(int rows=1;rows<=i;rows++){
      System.out.print(numberOfNumbers–+" ");

    4. George V Joseph says:

      int itrns = 5;
      int maxNum = 15;
      int printCnt = 0;

      for (; itrns >= 1; itrns–) {

      for (; printCnt < itrns; maxNum–) {

      System.out.print(maxNum + " ");

      maxNum = maxNum;
      printCnt = 0;

  29. anjali says:

    Hi i need the ebook
    java design patterns

    1. Nikhil Aggarwal says:

      Download Head first design patterns book.

  30. Ranga Kalyan says:

    This blog post on design patterns is great! I particularly like your links that show examples. Very helpful.

    I use a lot of design patterns in my Java work. I come to your blog often, to clarify their differences.

    Thank you for posting it.

  31. Ranga says:

    Great post.. Thanks!

  32. Balaji says:

    Hi Pankaj,

    I just want to thank you. The work you are doing so great, it’s making developers life easier.
    Thank a lot for your great work again.

    One query i have that might be wrong but just to clarify:
    1. In Decorator Pattern – We are using inheritance or aggregation to extend the behavior of an object…..

    and not the “Composition”, I think Aggregation is correct to say here than Composition.

    what you say?

  33. a says:

    how to print
    1 2 1
    1 2 3 2 1
    1 2 3 4 3 2 1
    1 2 3 2 1
    1 2 1

    1. Lalit Sharma says:

      public void printStars(int num, int limit)
      if (num > limit)
      for (int q = 1; q <= num; q++){


      printStars(num +1, limit);

      for (int q = 1; q <= num; q++){




    2. Veera says:

      public void printStars(int num, int limit)
      int count =0;
      if (num > limit)
      for (int q = 1; q 1;q–)

      printStars(num +1, limit);
      for (int q = 1; q 1;q–)

      1. Veera says:

        Please use the above code to display the required format

      2. vinay says:

        still i am getting errors in program

  34. Padam Dhariwal says:

    Very nice articles.

  35. Prashanth says:

    Brother, add examples or link it in another page. It would be quite helpful.

    1. Prashanth says:

      Nice examples and easily understandable.
      Seems links are not working only for me.

      1. Pankaj says:

        can you tell me which link is not working?

  36. Vikram says:

    Very Nice article and well written with very good examples

  37. Atul says:


    Write a program to print this series.


    1. Hayawan says:

      public class numbers () {

      system.out.println (129876 “+” 245335 “+” 483728 “+” 092872 “+” 387763);
      return null;


    2. Hayawan says:

      public class Numbers {
      public static void main(String[] args) {


      this is the right way, i was rushing before, sorry.

  38. chetan says:

    Hi Pankaj,

    Singleton Design Pattern hyperlink not working.

    1. Pankaj says:

      Thanks Chetan for noticing and pointing out, I was doing some post update and mistakenly removed the link. I have corrected it. Thanks again.

      1. Shailendra says:

        0 1 2 3
        0 1 2
        0 1
        0 1
        0 1 2
        0 1 2 3

      2. Shailendra says:

        3 4
        2 3 4
        1 2 3 4
        0 1 2 3 4
        1 2 3 4
        2 3 4
        3 4

  39. Boovaragan says:

    Hi Sir,
    what about Service Locator patter?
    under which category will it come?

  40. Vijay Kumar says:

    Awesome articles on Design patterns so far I have read.

    1. Pankaj says:

      Thanks Vijay, make sure to get the eBook by subscribing to the newsletter.

  41. Java Learner says:


    This is great, no words the way you wrote the article.
    Love it, Love it, Love it.


    1. Pankaj says:

      You made my day brother.

    1. Pankaj says:

      Thanks Don, appreciate the nice words.

  42. ejakhan says:

    1 2 3 4 5
    10 9 8 7 6
    11 12 13 14 15
    20 19 18 17 16

    1. Pankaj says:

      I don’t understand what you are asking, and how it’s anywhere related to java design patterns.

  43. shreya says:

    1 3 5 7 9
    3 5 7 9 1
    5 7 9 1 3
    7 9 1 3 5
    9 1 3 5 7

    help please!!!!!

    1. Suyash says:

      int[] arr = new int[]{1, 3, 5, 7, 9};
      for (int i = 0; i < 5; i++) {
      for (int j = 0; j < arr.length; j++) {
      System.out.print(arr[j] % 10 + " ");
      arr[j] = arr[j] + 2;

      1. Pankaj says:

        Thanks Suyash for responding and helping Shreya.

  44. mahesh says:

    wow Super Pankaj ,very easy to understand

    1. Pankaj says:

      Thanks Mahesh, get the eBook too. 🙂

  45. Santeepa says:

    plzz tell me how to do this
    NO Data Pattern
    1 5
    3 5 10
    5 5 10 15

    1. Vishnu says:

      public class Pattern {

      static int c = 1;
      static int p = 5;
      static int x = 2;

      public static void main(String[] args) {

      for (int i = 2; i < 5; i++) {

      for (int j = 0; j < x; j++) {
      if (j == 0)
      else {
      p += 5;

      c += 2;
      p = 5;



      1. Pankaj says:

        Thanks Vishnu for responding and quick solution, I hope it helps Santeepa.

    2. khushi says:

      plz solve it anybody
      if user gives(3,2)as an input then the output should be
      7 9 11
      3 5
      3 5
      plz solve this question in and share thiis code.

  46. Kush says:

    Very simple examples and nicely explained. It would not have been possible to learn design patterns without your book. Thanks a ton for your effort sir.

    1. Pankaj says:

      Wow, one of the nicest comment I have got recently.

  47. Chirag Sharma says:

    There should be some real time problem also as a example to complete this tutorial.

    1. Pankaj says:

      If I will provide real life problem, it will become too specific and too lengthy. Also there are many ways to solve a real life problem, it depends on your project specific situation. You should learn these design patterns and use them wisely. You should not use a design pattern just because you know it.

      Always remember, simple code is the best code.

  48. Vidita Daga says:

    Thank you so much…This is really helpful to learn.

    1. Pankaj says:

      Appreciate your lovely words, Vidita. 🙂

  49. suresh atta says:

    Simply awsome. I llike your write ups and examples.

    1. Pankaj says:

      Thanks Suresh, I hope you will like my eBook for design patterns too. It’s absolutely free for my email subscribers.

  50. Himalaya says:

    Hi, Blog information is really nice. Please provide a “Scroll to Top” option in your website. Many thanks 🙂

    1. Pankaj says:

      Hmm, nice suggestion. I want to do that but it will add some more resources and slow down page speed. I have kept bare minimum things to make sure page load fast for everyone. 🙂

  51. Ranga says:

    Great work. I’m a great believer that understanding the context where a Design Pattern is applicable is more important than the actual implementation details. This article gives a good overview. I think this video will also be a good guide. Video

    1. Pankaj says:

      Thanks for the nice words Ranga.

  52. Aryan says:

    Nice article, good examples, easy to follow. I am using it to prepare for Software Engineering exam which is in two days. Thank you.

    1. Pankaj says:

      I am replying late but I wish you did well.

  53. sree says:

    is MVC pattern belongs to which category?

    1. Pankaj says:

      It belongs to Java EE patterns.

  54. Neeraj says:

    In One For Loop

    public class Test {
    public static void main(String arg[]){
    int c =1;
    int d =1;
    int till =15;
    for(int b=till;b>0;b–){

    System.out.print(b+” “);





    1. Pankaj says:

      What is your query here?

  55. Atmprakash Sharma says:

    nice ..well manged data…i read most of your blog and get confident in java….keep it up….

    1. Pankaj says:

      Thanks Atmprakash, good to hear from a regular read.

  56. Oleg says:

    It would be creat to see tutotials about DAO and MVC patterns and how to use them with JDBC.

    1. Pankaj says:

      Added to my TODO list, will publish it soon.

      1. abhinav says:

        still waiting for the same.

  57. j says:

    Simple explanations on common design patterns. Thanks!

    1. Pankaj says:

      You are welcome ‘J’. 🙂

  58. Tanmoy says:

    how to do this program
    1 2 3 4 5
    6 7 8 9
    10 11 12
    13 14

    1. rao arsalan says:

      here is your program!!!!!!

      class Pattern{

      public static void main(String a[]){
      int k=5;
      int i,j;
      int z;
      for( i=1;i<=15;i=z){

      for( j=i;j<=k;j++){



      1. Ganesh Ahiwale says:


        1. Pankaj says:

          Thanks guys for pitching in and helping Tanmoy.

  59. jayesh says:

    how to do

    1. Vijay Bharwani says:

      I am not sure whether you solved it or not. But it is pretty simple. Below is the program for this pattern

      public static void main(String args[]) {
      int lines = 4;
      for (int i = 1; i <= lines; i++) {
      for (int j = 1; j <= i; j++) {

      1. Pankaj says:

        i hope your program helped Jayesh.

  60. Ashakant says:

    This is also very nice simple explanation :

    public interface Duck
    public void quack() ;
    public void fly() ;

    public interface Turkey
    public void gobble() ;
    public void fly() ;

    public class TurkeyAdapter implements Duck
    private Turkey mTurkey;
    public void quack() {
    // TODO Auto-generated method stub
    mTurkey.gobble() ;


    public void fly() {
    // TODO Auto-generated method stub
    for(int i=0;i<5;i++) ;

    TurkeyAdapter link between Duck and Turkey

    1. Pankaj says:

      You need implementation of Turkey interface and then inject it to TurkeyAdapter private variable mTurkey by setter method or through constructor. My 2 cents, however I am not sure if there was a query here. 😉

  61. Chidambar Dorairaj says:

    Awesome tutorials Pankaj. Keep up the good work.

    1. Pankaj says:

      Thanks Chidambar, appreciate nice words.

  62. groovy says:

    Some developers becomes so obsessed with design patterns that they over-engineer.

    1. vijay says:

      But for most, it is a good learning.

      1. Pankaj says:

        Design patterns are good to know, but don’t use it just because you know it. See your requirement and if there is a benefit in using design pattern, then only apply it.

        Simple code is the Best Code. 🙂

  63. Rama says:

    Really good for refreshing the concepts. Thanks a lot 🙂

    1. Pankaj says:

      Yeah I know, I also come by this once in a while to refresh my learning too. 🙂

  64. Marquis says:

    2 words Thank you!

    1. Pankaj says:

      2 words – “Appreciate it” 🙂

  65. Cristian Manoliu says:


    I’ve been struggling with design patterns, but this document explains them so well.

    Thank you for the lesson.

    Best regards,

    1. Pankaj says:

      Hey Cristian, thanks for nice words. You can get my Design Pattern PDF eBook too by subscribing to my email newsletter.

  66. Hossein Moradi says:

    Thanks a lot for the instructive tutorial…

    1. Pankaj says:

      You are welcome brother.

  67. jitendra says:

    This is excellent tutorial with best & simplified examples, compared to other tutorials on design pattern its easy to understand with great knowledge. The description given about each pattern helps you to decide which pattern should be used where. I read it like a story book.

    1. Pankaj says:

      Thanks Jitendra, you just made me smile. 🙂

  68. jerry says:

    very useful. thanks a lot.

    1. Pankaj says:

      Thanks Jerry, I hope Tom is not giving you a lot of trouble these days. 😀

  69. Pranay says:

    great work…

  70. Delli Babs says:

    This is excellent work sir !!! really helpful

    1. Pankaj says:

      You are welcome Delli.

  71. chandrani says:

    Great work!

    1. Pankaj says:

      You are welcome Chandrani.

  72. SRK says:

    Excellent site to know about all design patterns.

    1. Pankaj says:

      I tried to cover as much as possible, to the best of my knowledge. 🙂

  73. says:

    This is a really good blog, and I always follow your blog whenever I need any clearance.

    1. Pankaj says:

      Thanks for appreciation.

  74. Ravikumar says:

    Excellent Explanation, Wonderful examples to understood easily… Thanks

    1. Pankaj says:

      You are welcome Ravikumar.

  75. Usha says:

    One of the best article on Design pattern, Thanks.

    1. Pankaj says:

      Thanks Usha for kind words.

  76. Varun says:

    This tutorial was very helpful ; thanks Pankaj …waiting for J2EE Design Patterns tutorial

    1. Pankaj says:

      I have added it on my TODO list, hope to start soon on them.

  77. Naveen says:

    Hi your blog is really good, I request you to post more on struts2 from basics to advance.

    1. Pankaj says:

      Struts2 tutorials are posted, i hope you find them useful.

  78. Syam says:

    Hi Pankaj,
    Thanks a lot for the tutorial.
    Could you please also include J2EE Design Patterns also. (MVC, Business Delegates..)

    1. Pankaj says:

      They are coming next, mostly in next month.

  79. Nestor says:

    Hey your blog is really good. congratulation

    1. Deepika Gurav says:

      how to print
      0 1
      1 0 1
      0 1 0 1
      1 0 1 0 1

      1. jay says:

        public class Pattern {

        public static void main(String[] args) {

        for(int i=1;i<6;i++){
        for(int j=1;j<i;j++){




        1. Pankaj says:

          Thanks for the help buddy.

      2. Ymg says:

        You can refer this code

        class demo
        public static void main(String args[])
        int i,j,zero=0,one=1;
        if(j==1 || j==3 || j==5)
        System.out.print(one+ “t”);
        else if(j==2 || j==4)
        System.out.print(zero+ “t”);


Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages