Design Patterns Interview Questions
Design Patterns Interview Questions
• Pattern Name and Classification : A short, meaningful name for the pattern, usually
only one or two words. Names provide a vocabulary for patterns, and they have implied
semantics – choose names carefully. Following the GoF book, we can also group patterns
into higher level classifications such as creational, structural, and behavioral patterns.
• Problem : A general description of the problem context and the goals and constraints that
occur repeatedly in that context. A concrete motivational scenario can be used to help
describe the problem. The problem description should provide guidance to assist others in
recognizing situations where the pattern can be applied.
• Solution : The classes and/or objects that participate in the design pattern, their structure
(e.g., in terms of a UML class diagram), their responsibilities, and their collaborations. The
solution provides an abstract description that can be applied in many different situations.
Sample Code in an object-oriented language can be used to illustrate a concrete realization
of the pattern.
• Consequences : A discussion of the results and tradeoffs of applying the pattern.
Variations and language-dependent alternatives should also be addressed.
• Known Uses : Examples of the pattern in real systems. Look for applications of the
pattern in language libraries and frameworks, published system descriptions, text books,
etc. Not every good solution represents a pattern. A general rule of thumb is that a
candidate pattern (also called a “proto-pattern”) should be discovered in a minimum of
three existing systems before it can rightfully be called a pattern.
The following quote by Robert Martin highlights the importance of providing pattern descriptions:
“The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in
which those patterns are documented. ... Prior to the GoF book, the only good way to learn
patterns was to discover them in design documentation, or (more probably) code.”
The programmer would access the single instance of this class by writing something similar to
Singleton.getInstance().someMethod()
or similar to
Singleton s = Singleton.getInstance();
s.method1();
...
s.method2();
...
For a more complete discussion of the Singleton pattern, see the chapter “Singleton” in the book
Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of Four” (Addison-
Wesley, 1995), or the chapter “Singleton” in the book Patterns in Java, Volume 1 by Mark Grand
(John Wiley & Sons, 1998). For information about variations on the Singleton Pattern, see the
chapter entitled “To Kill a Singleton” in the book Pattern Hatching: Design Patterns Applied by
John Vlissides or the article “Implementing the Singleton Pattern in Java” by Rod Waldhoff.
8) How can I make sure at most one instance of my class is ever created?
This is an instance where the Singleton design pattern would be used. You need to make the
constructor private (so nobody can create an instance) and provide a static method to get the sole
instance, where the first time the instance is retrieved it is created:
public class Mine {
private static Mine singleton;
private Mine() {
}
public static synchronized Mine getInstance() {
if (singleton == null) {
singleton = new Mine();
}
return singleton;
}
// other stuff...
}
10) Which patterns were used by Sun in designing the Enterprise JavaBeans
model?
Many design patterns were used in EJB, and some of them are clearly identifiable by their naming
convention. Here are several:
1. Factory Method: Define a interface for creating classes, let a subclass (or a helper class)
decide which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the
EJBObject implementations. They are actually created by a generated container class. See
InitialContextFactory interface that returns an InitialContext based on a properties
hashtable.
2. Singleton: Ensure a class has only one instance, and provide a global point of access to it.
There are many such classes. One example is javax.naming.NamingManager
3. Abstract Factory: Provide an interface for creating families of relegated or dependent
objects without specifying their concrete classes.
We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has
methods to get InitialContext.
4. Builder: Separate the construction of a complex factory from its representation so that the
same construction process can create different representations.
InitialContextFactoryBuilder can create a InitialContextFactory.
5. Adapter: Convert the interface of a class into another interface clients expect.
In the EJB implementation model, we implement an EJB in a class that extends
SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces.
EJB container generates a class that adapts the EJBObject interface by forwarding the calls
to the enterprise bean class and provides declarative transaction, persistence support.
6. Proxy: Provide a surrogate for other object to control access to it.
We have remote RMI-CORBA proxies for the EJB's.
7. Memento: Without violating encapsulation, capture and externalize an object's internal
state so that the object can be restored to this state later.
Certainly this pattern is used in activating/passivating the enterprise beans by the
container/server.
NOTE: The 2nd check for if (instance_ == null) is needed to avoid making another unnecessary
construct.
Don't let this byte you! ;-)
18) How and where did the concept of design patterns get started?
Work on patterns has been influenced by the works of Christopher Alexander who published on
topics related to urban planning and building architecture in the late 1970s. The history of
patterns for software design began in the late 1980s and reached an important milestone with the
publishing of the first book fully dedicated to this subject by the "Gang of Four", Erich Gamma,
Richard Helm, Ralph Johnson and John Vlissides, Design Patterns - Elements of Reusable Object-
Oriented Software). In conjunction, the emergence of object-oriented software development
fostered the work on other topics related to design patterns such as application frameworks,
analysis patterns, language idioms, and so on.
19) Where can I find good examples of the Prototype pattern?
The prototype pattern is actually quite simple to implement in Java.
Recall that the idea of prototype is that you are passed an object and use that object as a
template to create a new object. Because you might not know the implementation details of the
object, you cannot create a new instance of the object and copy all of its data. (Some of the data
may not be accessible via methods). So you ask the objectitself to give you a copy of itself.
Java provides a simple interface named Cloneable that provides an implementation of the
Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to
create a new instance of the object with the same values.
The trick here is that you must override the clone() method to increase its visibility, and just call
super.clone(). This is because the implementation of clone(), defined in java.lang.object, is
protected. For example:
public class CopyMe implements Cloneable {
public Object clone() {
return super.clone();
}
}
Note that Cloneable is an empty interface! It merely acts as a tag to state that you really want
instance of the class to be cloned. If you don't implement Cloneable, the super.clone()
implementation will throw a CloneNotSupportedException.
The Object implementation of clone() performs a shallow copy of the object in question. That is, it
copies the values of the fields in the object, but not any actual objects that may be pointed to. In
other words, the new object will point to the same objects the old object pointed to.
As an example of using the cloning:
CopyMe thing = new Copyme();
CopyMe anotherThing = (Copyme)thing.clone();
This example is pretty trivial, but the real power comes when you don't know what you're actually
cloning.
For example, suppose you define an interface that represents a customer:
public interface Customer extends Cloneable {
public Object clone(); // require making it public!
public String getName();
public void setName(String name);
...
}
You might have several different implementations of this interface, possibly storing data in a file,
database, or using EJB Entity beans. If a shallow copy of the data is sufficient to represent a copy
of the object, Java's clone() method works great.
You might have a method that needs to make a copy of the data to store it in a Hashtable, for
example:
public void storeCustomer(Customer customer) {
Customer copy = (Customer)customer.clone();
dataStore.put(copy);
}
Note that this method knows nothing about what type of customer we're getting. This pattern will
work for any actual type of Customer, no matter how the data is stored. For example:
FileBasedCustomer c1 = new FileBasedCustomer(...);
RDBMSBasedCustomer c2 = new RDBMSBasedCustomer(...);
EJBBasedCustomer c3 = new EJBBasedCustomer(...);
manager.storeCustomer(c1);
manager.storeCustomer(c2);
manager.storeCustomer(c3);
25) Is there some kind of Design pattern which would make it possible to
use the Same code base in EJB and non EJB context?
A good suggestion would be using Delegation
class PieceOfCode {
public Object myMethod() {}
}
class EJBImpl ... {
PieceOfCode poc = new PieceOfCode();
public Object myMethod() {
return poc.myMethod();
}
}
This should not be a violation of EJB specs, since EJBs can use simple java classes for their use.
Think aboutDependant Objects and so on.
28) How can I implement the MVC design pattern using JSP?
The MVC (Model View Controller) design pattern is a pattern/architecture that can be used by
GUI's. It seperates the application's data, user interface and control logic into three separate
entities. This ensures the system will be more maintainable in the future as changes to one
component will not have an affect on the others.
The MVC pattern also conforms with the JSP Model 2 architecture.
The MVC pattern can be easily implemented in web applications using JSTL core, JSP, Servlets and
JavaBeans.
JSTL makes it easy for HTML designers to use dynamic data in their pages without having to learn
in depth java. The tags are in a recognizable HTML like format meaning a smaller learning curve
than taking on the JSP specification after taking on the Java specification.
JSTL also makes it easy for web developers who are developing all aspects of the application in
helping you keep the content separate from the display by keeping your JSP clean from any Java
code. Since JSTL and its EL (expression Language) are really only suited for accessing data, it
forces you to use a MVC pattern so long as you keep all JSP and Java syntax/code out of the JSP
pages.
A common scenario might look like this, a user sends a request to a server. The request is handled
by a Servlet (the controller) which will initialize any JavaBeans (the model) required to fulfill the
user's request. The Servlet (the controller) will then forward the request, which contains the
JavaBeans (the model), to a JSP (the view) page which contains only HTML and JSTL syntax. The
JSTL will format the data into a human readable format before being sent back to the user. Thus
completing the full MVC process.
JSTL also has a tag library for XML processing, this could be used in an MVC environment as you
could replace the JavaBeans with an XML document to describe your data, so long as the XML is
still constructed in a controller such as a Servlet before being passed to the JSP (the view).
JSTL also has a tag library for database access, using this in your JSP (the view) pages would NOT
comply to the MVC pattern as there will be no separation between the model and the view.