Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Wednesday, January 7, 2015

Top 18 design patterns interview questions in Java to know

This is (almost) verbatim from the Java67 blog (to which the appropriate credit must be given), with some links in addition to Java 8.

Design pattern interview question are integral part of any good list of core Java interview questions. Java is a popular Object oriented programming language and have lots of design pattern and design principles, contributed by many developers and open source framework. As a Java programmer it is expected from you to know OOPS concept like Abstraction, Encapsulation and polymorphism, what is design pattern in Java, some popular Java design pattern and, most importantly, when to use those design pattern in Java application. Purpose of asking design pattern interview question in Java is to check whether a Java programmer is familiar to those essential design patterns or not. Design patterns in Java interviews are as important as multi-threading, collection and programming questions. If you are senior or experienced Java programmer than expect more complex and tough design pattern in Java interview, e.g. Chain of responsibility design pattern, and solving real time software design questions.



Top Java design pattern questions and answers

Here is my list of top 10 design pattern interview question in Java. I have also provided answer of those Java design pattern question as link. no matter which level of Javainterview are you going e.g. programmer, software engineer, senior software engineer inJava, you can expect few question from Java design pattern.

1. When to use Strategy Design Pattern in Java?

Strategy pattern in quite useful for implementing set of related algorithms e.g. compressionalgorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules. This pattern follow open closed design principle and quite useful in Java. One example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface, which is a strategy interface and defines strategy for comparing objects. Because of this pattern, we don't need to modify sort()method (closed for modification) to compare any object, at same time we can implement Comparator interface to define new comparing strategy (open for extension).


A more detailed review of the Strategy pattern, in the same blog,  is here. However, Java 8, changes the scenario. Here and here some examples of using the strategy pattern with lambdas.

2. What is Observer design pattern in Java? When do you use Observer pattern in Java?

This is one of the most common Java design pattern interview question. Observer pattern is based upon notification, there are two kinds of object Subject and Observer. Whenever there is change on subject's state observer will receive notification. See What is Observer design pattern in Java with real life example for more details.


3. Difference between Strategy and State design Pattern in Java?

This is an interesting Java design pattern interview questions as both Strategy and State pattern has same structure. If you look at UML class diagram for both pattern they look exactly same, but there intent is totally different. State design pattern is used to define and mange state of object, while Strategy pattern is used to define a set of interchangeable algorithm and let's client to choose one of them. So Strategy pattern is a client driven pattern while Object can manage there state itself.

4. What is Decorator pattern in Java? Can you give an example of Decorator pattern?

Decorator pattern is another popular java design pattern question which is common because of its heavy usage in java.io package. BufferedReader and BufferedWriter are good example of decorator pattern in Java. See How to use Decorator pattern in Java fore more details.

5. When to use Composite design Pattern in Java? Have you used previously in your project?

This design pattern question is asked on Java interview not just to check familiarity with Composite pattern but also, whether candidate has real life experience or not. Composite pattern is also a core Java design pattern, which allows you to treat both whole and part object to treat in similar way. Client code, which deals with Composite or individual object doesn't differentiate on them, it is possible because Composite class also implement same interface as there individual part. One of the good example of Composite pattern from JDK is JPanel class, which is both Component and Container. When paint() method is called on JPanel, it internally called paint() method of individual components and let them draw themselves. On second part of this design pattern interview question, be truthful, if you have used then say yes, otherwise say that you are familiar with concept and used it by your own. By the way always remember, giving an example from your project creates better impression.

6. What is Singleton pattern in Java?

Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole application. java.lang.Runtime is good example of Singleton pattern in Java. There are lot's of follow up questions on Singleton pattern see 10 Java singleton interview question answers for those followups

7. Can you write thread-safe Singleton in Java?

There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using double checked locking, by using static Singleton instance initialized during class loading. By the way using Java enum to create thread-safe singleton is most simple way. See Why Enum singleton is better in Java for more details.

8. When to use Template method design Pattern in Java?

Template pattern is another popular core Java design pattern interview question. I have seen it appear many times in real life project itself. Template pattern outlines an algorithm in form of template method and let subclass implement individual steps. Key point to mention, while answering this question is that template method should be final, so that subclass can not override and change steps of algorithm, but same time individual step should be abstract, so that child classes can implement them.

9. What is Factory pattern in Java? What is advantage of using static factory method to create object?
Factory pattern in Java is a creation Java design pattern and favorite on many Javainterviews.Factory pattern used to create object by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to introduce new objects etc. See What is Factory pattern in Java and benefits for more details.

10. Difference between Decorator and Proxy pattern in Java?

Another tricky Java design pattern question and trick here is that both Decorator and Proxy implements interface of the object they decorate or encapsulate. As I said, many Java design pattern can have similar or exactly same structure but they differ in there intent. Decorator pattern is used to implement functionality on already created object, while Proxy pattern is used for controlling access to object. One more difference between Decorator and Proxy design pattern is that, Decorator doesn't create object, instead it get object in it's constructor, while Proxy actually creates objects.

11. When to use Setter and Constructor Injection in Dependency Injection pattern?

Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory dependency of an object, without which it can not work. This question is related to Dependency Injection design pattern and mostly asked in context of Spring framework, which is now become an standard for developing Java application. Since Spring provides IOC container, it also gives you way to specify dependencies either by using setter methods or constructors. You can also take a look my previous post on same topic.

12. What is difference between Factory and Abstract factory in Java

see here to answer this Java design pattern interview question.

13. When to use Adapter pattern in Java? Have you used it before in your project?

Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter pattern can also be used to encapsulate third party code, so that your application only depends upon Adapter, which can adapt itself when third party code changes or you moved to a different third party library. By the way this Java design pattern question can also be asked by providing actual scenario.

14. Can you write code to implement Producer Consumer design pattern in Java?

Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple way. if you are working in Java 5 then its better to use Concurrency util to implement producer consumer pattern instead of plain old wait and notify in Java. Here is a good example of implementing producer consumer problem using BlockingQueue in Java.

15. What is Open closed design principle in Java?

Open closed design principle is one of the SOLID principle defined by Robert C. Martin, popularly known as Uncle Bob. This principle advices that a code should be open for extension but close for modification. At first this may look conflicting but once you explore power of polymorphism, you will start finding patterns which can provide stability and flexibility of this principle. One of the key example of this is State and Strategy design pattern, where Context class is closed for modification and new functionality is provided by writing new code by implementing new state of strategy. Seethis article to know more about Open closed principle.

16. What is Builder design pattern in Java? When do you use Builder pattern ?

Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews because of its specific use when you need to build an object which requires multiple properties some optional and some mandatory. See When to use Builder pattern in Java for more details

17. Can you give an example of SOLID design principles in Java?

There are lots of SOLID design pattern which forms acronym SOLID, read this list of SOLID design principles for Java programmer to answer this Java interview question.

18. What is difference between Abstraction and Encapsulation in Java?

I have already covered answer of this Java interview question in my previous post as Difference between encapsulation and abstraction in Java. See there to answer this question.

This was my list of 10 popular design pattern interview question in Java. I have not included MVC (Model View Controller) design pattern because that is more specific to J2EE and Servlet JSP interview, but if you are going for any Java interview which demands experience in J2EE than you must prepare MVC design pattern. That's all on Java design pattern interview question and answers. Please let us know if you have any other interesting question on Java design pattern.

P.S. - Here a synthetic discussion on how Java 8 can change the design pattern implementation, which can be completed by this stackoverflow post.  A discussion of some IBM authors of the same topic  can be found hereHere , instead an example of the "Commander" (observer-like) pattern, and, in the second part of the post, a new example of the strategy pattern in Java 8. 

Sunday, November 9, 2014

Design Patterns

Programming the object oriented (OO) way is not simply writing down algorithms that do “for" loops. The core concept to understand, for a OO programmer, is how many classes have to be implemented on the basis of the analysis of the problem under scrutiny, and to be eventually managed by a client (the “main” method in C family of languages)  to solve a task. Therefore, a series of questions arise:
  • Are there strategies for producing a minimum number of classes without loosing functionalities  in the work done and promote its extensibility  ? 
  • What goes into a class, and what in other OO features (like methods of a class) ? 
  • How to create classes with a minimum of generality that can be reused in other problems ? 
  • How to build classes that can be easily maintained, modified and evolved without disrupting other parts of codes ? 
(In practise the questions are those for which OO was born but knowing an OO language does not directly answer them, just offers an infrastructure for finding the answers).

An entire discipline, software engineering (SE), was established to find the answers, and various behaviors were codified to improve software writing practice and management (but software engineering also covers the organisation of software production, and the methods to give  clear specifications to pariah-programmers for practical coding).
The key actions implied by the answers, however, are not the ones a scientific programmer was used to face: s/he would expect to have a formalised mathematical problem and the scope of her/his work to consist in fact in finding the best (shortest, fastest, cleanest) algorithms to solve it (see the classical Knuth’s books, or the popularisation of Numerical Recipes - I hate their licensing scheme) but not to answer questions about the organisation of the code.
Maintainability and efficiency comes to a cost and OO adds a further level of complexity to the programming practice that scientists are not always ready to face: and it is quite paradoxical that these aspects of SE are not wide recognised as a fundamental task in our times when computer programs have entered in the daily practice of many scientists (see also the introduction to this paper of ours). As a matter of fact bad code practices easily develop in bad science.

Back to the general questions posed at the beginning of the post, proficient programmers observed that, certain problems were recurrents and that some solutions were better than others in term of maintainability and generality. These were called "design patterns”:

"The elements of this language are entities called patterns. Each pattern describes a problem that occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice."  (from A Pattern Language by Christopher Alexander, that is said to be inspirational for the the Gang of Four book - see below).
Other definitions of patterns can be fond in the Portland Patterns Repository and in The Hillside group on patterns,.

The patterns idea gained popularity after the book of Gamma, Helm, Johnson & Vlissides, Design Patterns, which actually presents 23 free patterns, grouped in three categories, called


Beyond these initial patterns, other were identified, for instance for parallel computing (see Concurrency patterns), and  in other fields.
The patterns style and  use (and concept) are not immediate to grasp. They in fact derive from long practicing some specific software issues, and a subsequent conceptualisation and abstraction. As often happens, their abstraction makes them general but  quite difficult to be assimilated without going back to develop many examples.
A few guiding ideas are behind the selection of patterns: code should be made easy to modify without large refactoring efforts, and encapsulation of code parts maintained as much as possible. Subclassing maintained to a minimum. An explicit slogan was "program to interface and not to implementation”. Roughly speaking this means: first implement abstract classes or interfaces (in C-family of languages), the, for what is possible, delay the use of concrete classes at run time. Instead of creating subclasses, create other classes to which "delegate responsability”, in order to reduce coupling between classes. The reader is invited to browse the web to understand her/himself what it does mean, advising her/him that explanations are usually full of computer science slang (I think, actually that the language is part of the success of the book).
In any case, the right way to get used to Design Patterns, is, as I said, to use and practice them a lot by trial and error. Java aficionados can have several vulgarisations, many of them can be found on the web [Ava Java].

However, the relevant questions here, in this blog,  are:

  • which of the original (as well as other) patterns are useful in scientific programming ?
  • Are there any pattern that is characteristic to hydrological problems ?


Certainly there exists hydrologists that apply some patterns for the tasks the patterns were created. I do not know if experienced hydrology programmers apply  patterns to some specific of hydrology. Please let me know if you are someone of those, and I will really likely exchange ideas and a (very few) experiences.

In the general science framework, instead, I find a few more references. The first books I can reference are




Other resources come from the paper by the Izaguirre group, and are referenced below.


Further Readings


Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides: Design Patterns: Elements of Reusable Object-Oriented Software
Thinking in patterns’ Notes by Bruce Eckel

[Portland Patterns Repository] - Patterns are the recurring solutions to the problems of design. People learn patterns by seeing them and recall them when need be without a lot of effort. Patterns link together in the mind so that one pattern leads to another and another until familiar problems are solved. That is, patterns form languages, not unlike natural languages, within which the human mind can assemble correct and infinitely varied statements from a small number of elements.

[The Hillside group on patterns] - Fundamental to any science or engineering discipline is a common vocabulary for expressing its concepts, and a language for relating them together. The goal of patterns within the software community is to create a body of literature to help software developers resolve recurring problems encountered throughout all of software development. Patterns help create a shared language for communicating insight and experience about these problems and their solutions. Formally codifying these solutions and their relationships lets us successfully capture the body of knowledge which defines our understanding of good architectures that meet the needs of their users. Forming a common pattern language for conveying the structures and mechanisms of our architectures allows us to intelligibly reason about them. The primary focus is not so much on technology as it is on creating a culture to document and support sound engineering architecture and design

- [Design Pattern for scientific software] by Dan Gezelter. He pointed to some papers on Design Pattern is scientific computing by the Izaguirre group of which I found [1] and [2]

Design Patterns in Wikipedia

Monday, September 8, 2014

Improve GEOtop informatics !

I take the occasion of the actual structure of GEOtop main to argue about best practices in programming and introduce the topic of design patterns. For browsing the actual code you can see here , while my more specific comments are available at the GEOtop Developers forum

I argued that a much simpler  form for the main, should be represented by a scheme like the following (dots represent missing code, the code is assumed to be C++ - please be merciful with me: my knowledge of C++ details is very limited -  but, the arguments are for every generic language with support of object orientation):

where three main phases are distinguished: an initialization phase (with allocation and initialisation of variables), an execution phase (where the real stuff is done), and a closure phase (where all the memory if freed, and whatever is needed is performed). This best practice is a suggestion that comes from many recent numerical modeling efforts, like ESMF, OpenMI, OMS and allows an encapsulation of the processes in their own part of the project, but everybody, I think, can appreciate its simplicity and cleanness. 
A structure like this should be not very difficult to obtain in a few days of work of a proficient programmer. This structure does not alter the internal of the code and rationalise what is present now, introduce some encapsulation of the procedure,  but IT IS NOT object oriented (OO) programming.
Object oriented programming has to do with the choices of appropriate classes, and instantiation of the appropriate objects, and doing OO design, for implementing the code.

Who is suited to procedural programming, for instance interprets algorithms as “procedure calls”. My view, and understanding of the matter, is instead that procedures should be instantiation of classes, a.k.a. “objects”. Therefore, a proper evolution of the above could be:

In this second case, the organisation of the code remains the same. However the execution of the single procedure is written differently, i.e., for instance:

EnergyBalance.execute( ); 

This is intended to mean that EnergyBalance is an object and .execute() (please notice without arguments) is a method called on this object. One of the advantage of making the each procedure an object, has several argument in its favour. The first is that each object, now, contains its own inputs as fields, and encapsulation is certainly improved. This makes all the code easier to maintain, and the input data for each of the procedures easy to control and parse (out of the time loop, obviously). For a simpler, but a conceptually similar, example in Java, please see here.
Doing this step is not matter of a day, it certainly require more thinking and a sequence of modifications also in the structure of the data containers actually present in GEOtop which propagates down into the inner routines.

In case, also the print( ) method is part of a class, with the rational that with proper software engineering, it can be sent in parallel with the core calculation, on different processors, and therefore, interfering the less possibile with the ‘core’ computational time. I personally bet that, at moment, a consistent part of computational time of GEOtop is wasted in printing to screen data. So, maybe we spent months to have a fast algorithm for finding the solution, and that we use that time saved to put thousands of number on the screen or to write them to disk subtracting power to the computation. 

Actually, the one above is just the beginning of the story. Opening the way to classes, open the way to use some well known  Design Patterns to make the code more maintainable, flexible and evolvable. One case, obvious to all GEOtop aficionados is that, in reality, either the water budget and the other procedures, are a bundle of different alternatives. With OO there exists at least one neat scheme to treat this case, which is called, the “Strategy pattern” where, the object really chosen is one out of a group of options which are implementation of a common interface  (I am going to use the technical OO slang here). So actually, the "main( )" can be programmed to accept a generic type of solution (algorithm) to that problem (as specified by the abstract interface), and eventually this solution can be chosen at run time among the subclasses that implement it.  Solutions can then be added to the code without the need to modify (almost) anything else of the code than just adding a new subclass.

References (you will not find them easy to read ... but take it quietly, cross-check with the web, and something will pass slowly). Besides the basic, also adressed here fro Java, try to give a look to:

Gamma, E; Helm, R.; Johnson, R; Vlissides, J; Design Patterns: Elements of Reusable Object Oriented Software, Addison-Wesley, 1995

Martin Fowler's, UML Distilled: A Brief Guide to the Standard Object Modeling Language, Addison Wesley, 1999

Freeman, Eric T; Elisabeth Robson, Bert Bates, Kathy Sierra (2004). Head First Design Patterns. O'Reilly Media. ISBN 0-596-00712-4

Bruce Eckel, Thinking in patterns', notes. 

Various Authors, Design Pattern,  from Indian Student Association of University of Nebraska at Omaha