Saturday, January 25, 2014

Struts Interview Questions

Q.
What is Struts?
A.
The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, Java Beans, Resource Bundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with Java Server Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

Q.  What is Jakarta Struts Framework?
A.  Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

Q.  What is ActionServlet?
A.  The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the Jakarta Struts Framework this class plays the role of controller. All the requests to the server go through the controller. Controller is responsible for handling all the requests.

Q.  How you will make available any Message Resources Definitions file to the Struts Framework Environment?
A.  Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter=”MessageResources” />
     
Q.  What is Action Class?
A.  The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute()  method. In the Action Class all the database/business processing is done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (command) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
   
Q.  Write code of any Action Class?
A.  Here is the code of Action Class that returns the ActionForward object.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
  
public class MyAction extends Action
{
   public ActionForward execute(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) throws Exception
   {
           //business logic
         return mapping.findForward(\”newAction\”);
   }

 }



Q.  What is ActionForm?
A.  An ActionForm is a Java Bean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
  
Q.  What is Struts Validator Framework?
A.  Struts Validator Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.
   
Q.  Give the Details of XML files used in Validator Framework?
A.  The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Q.  How you will display validation fail errors on jsp page?
A.  The following tag displays all the errors:
<html:errors/>
  
Q.  How you will enable front-end validation based on the xml in validation.xml?
A.  The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName=”myForm” dynamicJavascript=”true” staticJavascript=”true” /> generates the client side java script for the form “myForm” as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

Q.  Is struts thread safe? Give an example?
A.  Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.

Q.  What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
A.  tiles-def.xml is an xml file used to configure tiles with the struts application. You can define the layout/header/footer/body content for your View.

The resourcebundle.properties file is used to configure the message (error/info/warning/other messages) for the struts applications.

The validation.xml file is used to declare sets of validations that should be applied to Form Beans.

Q.  What is the difference between perform() and execute() methods?
A.  Perform method is the method which was deprecated in the Struts Version 1.1. In Struts1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform(). Now execute just throws Exception.

Q.  What are the various Struts tag libraries?
A.  Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:
# Bean tag library - Tags for accessing JavaBeans and their properties.
# HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
# Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
# Tiles or Template tag library - For the application using tiles
# Nested tag library - For using the nested beans in the application

Q.  What do you understand by DispatchAction?
A.  DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operations to be mapped to the different functions in the same Action class.
For example:
A package might include separate Add, Modify and Delete Actions, which just perform different operations on the same Bean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action. A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.

Q.  How Struts relates to J2EE?
A.  Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.

Q.  What is Struts actions and action mappings?
A.  A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward. An action can perform tasks such as validating a user name and password.

An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action.

An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.

Q.  Can I setup Apache Struts to use multiple configuration files?
A.  Yes Struts can use multiple configuration files. Here is the configuration example:
<servlet>
<servlet-name>banking</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Q.  What are the disadvantages of Struts?
A.  Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.
b) Harder to learn
Struts are harder to learn, benchmark and optimize.

Q.  What are the difference between <bean:message> and <bean:write>?
A.  <bean:message>: This tag is used to output locale-specific text (from the properties files) from a Message Resources bundle.

<bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.

Q.  What is LookupDispatchAction?
A.  An abstract Action that dispatches to the subclass mapped execute() method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping.

Q.  What are the components of Struts?
A.  Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.

Model: Components like business logic/business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

Q.  What are the core classes of the Struts Framework?
A.  Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.

Q.  What are difference between ActionErrors and ActionMessage?
A.  ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property. Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).

Q.  How you will handle exceptions in Struts?
A.  In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:
<exception
key="database.error.duplicate"
path="/UserExists.jsp"
type="mybank.account.DuplicateUserException"/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.

Q.  What do you understand by JSP Actions?
A.  JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/>


Wednesday, January 8, 2014

Design Patterns Interview Questions

Q. Which are the three main categories of design patterns?
A. There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

Creational Patterns

 Abstract Factory: Creates an instance of several families of classes
 Builder: Separates object construction from its representation
 Factory: Creates an instance of several derived classes
 Prototype: A fully initialized instance to be copied or cloned
 Singleton: A class in which only a single instance can exist 


Note: - The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States)

Structural Patterns


 Adapter: Match interfaces of different classes
 Bridge: Separates an object’s abstraction from its implementation
 Composite: A tree structure of simple and composite objects
 Decorator: Add responsibilities to objects dynamically
 Facade: A single class that represents an entire subsystem
 Flyweight: A fine-grained instance used for efficient sharing
 Proxy: An object representing another object


Note : To remember structural pattern best is (ABCDFFP)

Behavioral Patterns


 Mediator: Defines simplified communication between classes.
 Memento: Capture and restore an object's internal state.
 Interpreter: A way to include language elements in a program.
 Iterator: Sequentially access the elements of a collection.
 Chain of Resp: A way of passing a request between a chain of objects.
 Command: Encapsulate a command request as an object.
 State: Alter an object's behaviour when its state changes.
 Strategy: Encapsulates an algorithm inside a class.
 Observer:  A way of notifying change to a number of classes.
 Template Method: Defer the exact steps of an algorithm to a subclass.
 Visitor:-Defines a new operation to a class without change.


Note: - Just remember Music....... 2 MICS On TV (MMIICCSSOTV).

Q. What is Singleton class?
A. Singleton is a class which has only one instance in whole application and can be accessed by  getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

Q. Which kind of class do you make Singleton in Java?
A.
 Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class, since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.

Q. Can you write code for getInstance() method of a Singleton class in Java?
A. Few examples of creating singleton object in java.

Using Enum keyword:

/**
* Singleton pattern example using Java Enumj
*/
public enum EasySingleton{
    INSTANCE;
}

You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.

Double Checked Locking Singleton creation:

public class SingletonEx{
     
private volatile SingletonEx sg;
  
     
private SingletonEx(){}
  
     
public static SingletonEx getInstance(){
         
if(sg == null){
            
synchronized(SingletonEx.class){
                
//double checking Singleton instance
                
if(sg == null){
                    sg 
= new SingletonEx();
                
}
            
}
         
}
         
return sg;
     
}
}

Static Final instance singleton creation..

public class SingletonEx{
    
//initailzed during class loading
    private static final SingletonEx sg 
= new SingletonEx();
  
    
//to prevent creating another instance of SingletonEx
    private SingletonEx
(){}

    public static SingletonEx getInstance
(){
        return sg
;
    
}
}
In later two examples you can get singleton object using SingletonEX.getInstance();
however, in Static final example Singleton instance is static and final and it is initialized when class is first loaded into memory so creation of instance is inherently thread-safe.

Q. What is lazy and early loading of Singleton and how will you implement it?
A.
 As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.

Q. Example of Singleton in standard Java Development Kit?
A. There are many Singleton objects in JDK. Few examples are
  • Java.lang.Runtime with getRuntime() method
  • Java.awt.Toolkit with getDefaultToolkit()
  • Java.awt.Desktop with  getDesktop()

Q. What is double checked locking in Singleton?
A.
Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

public static Singleton getInstance(){
     
if(_INSTANCE == null){
         
synchronized(Singleton.class){
         
//double checked locking - because second check of Singleton instance with lock
                
if(_INSTANCE == null){
                    _INSTANCE = 
new Singleton();
                
}
            
}
         
}
     
return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable as mentioned in above question.

Q. How do you prevent for creating another instance of Singleton using clone() method?
A.
 Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as  “Cannot create clone of Singleton class”.

Q. How do you prevent for creating another instance of Singleton using reflection?
A. In my opinion throwing exception from constructor is an option.
Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”

Q. How do you prevent for creating another instance of Singleton during serialization?
A. You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance.  Other way of preventing not to create multiple object for persistence singleton object is creating singleton using enum because serialization of enum is taken care by JVM and it provides guaranteed of that.


Q. Why you should avoid the singleton anti-pattern at all and replace it with DI?
A. Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.
Singleton Anti-Pattern: with more and more classes calling getInstance the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).

Q. How many ways you can write Singleton Class in Java?
A.  I know at least four ways to implement Singleton pattern in Java
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums

Q. How to write thread-safe Singleton in Java?
A. Thread safe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple threads at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by class loader.

Q. When to use Strategy Design Pattern in Java?
A. Strategy pattern is quite useful for implementing set of related algorithms e.g. compression algorithms, 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).

Q. What is Observer design pattern in Java? When do you use Observer pattern in Java?
A. This is one of the most common Java design pattern interview question. Observer pattern is based upon 
notification; there are two kinds of objects Subject and Observer. Whenever there is change on subject's state observer will receive notification.

Q. Difference between Strategy and State design Pattern in Java?
A. 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 their state itself.

Q. What is decorator pattern in Java? Can you give an example of Decorator pattern?
A. 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.
·         Decorator design pattern is used to enhance the functionality of a particular object at run-time or dynamically.
·         At the same time other instance of same class will not be affected by this so individual object gets the new behaviour.
·         Basically we wrap the original object through decorator object.
·         Decorator design pattern is based on abstract classes and we derive concrete implementation from that classes,
·         It’s a structural design pattern and most widely used

Q. When to use Composite design Pattern in Java? Have you used previously in your project?
A. 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 their individual part. One of the good examples 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.

Q. When to use Template method design Pattern in Java?
A. 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 cannot override and change steps of algorithm, but same time individual step should be abstract, so that child classes can implement them.


Q. What is Factory pattern in Java? What is advantage of using static factory method to create object?
A. Factory is a creational design pattern. It is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class. Factory should be an interface and clients first either creates factory or get factory which later used to create objects.

There are many advantage of providing factory methods e.g. caching immutable objects, easy to introduce new objects etc.

Q. Difference between Decorator and Proxy pattern in Java?
A. 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 its constructor, while Proxy actually creates objects.

Q. When to use Setter and Constructor Injection in Dependency Injection pattern?
A. Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory dependency of an object, without which it cannot work.
 Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring's IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring managed bean.

Q. What is difference between Factory and Abstract factory in Java?
A. Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.

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

A. Use Adapter pattern when you need to make two classes 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.

Q. Can you write code to implement producer consumer design pattern in Java?
A. Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple ways. If you are working in Java 5 then it is better to use Concurrency util to implement producer consumer pattern instead of plain old
wait and notify in Java.

Q. What is Open closed design principle in Java?
A. These principle advices that a code should be open for extension but closed for modification. One of the key examples 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 or strategy.

Q. What is Builder design pattern in Java? When do you use Builder pattern?
A. Builder pattern in Java is another creational design pattern in Java and it is used for its specific use when you need to build an object which requires multiple properties some optional and some mandatory.

Q. What is Service Locator pattern? 
A. The Service Locator pattern locates J2EE services for clients and thus abstracts the complexity of network operation and J2EE service lookup as EJB (Enterprise Java Bean) - Home and JMS (Java Message Service) component factories. The Service Locator hides the lookup process's implementation details and complexity from clients. To improve application performance, Service Locator caches service objects to eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that occurs in a lookup operation.


Q. What is Session Facade pattern? 
A. Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the interactions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there is enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored. 


As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor re-usability and maintainability.

The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest. 


Q. What is Data Access Object pattern? 
A.
DAO pattern separates a data resource's client interface from its data access mechanisms. The DAO pattern allows data access mechanisms to change independently of the code that uses the data. The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, LDAP database, an external service like a B2B exchange or a business service accessed via CORBA or low-level sockets.

The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source.

Q. What design patterns are used in Struts?
A. Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
       Service to Worker
       Dispatcher View
       Composite View (Struts Tiles)
       Front Controller
       View Helper
       Synchronize Token


Q. How can I make sure at most one instance of my class is ever created? 
A. 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...
        }


Q. What major patterns do the Java APIs utilize? Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:
A.
  • The Model-View-Controller design pattern is used extensively throughout the Swing API.
  • The getInstance() method in java.util.Calendar is an example of a simple form of the Factory Method design pattern.
  • The classes java.lang.System and java.sql.DriverManager are examples of the Singleton pattern, although they are not implemented using the approach recommended in the GoF book but with static methods.
  • The Prototype pattern is supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning.
  • The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class.
  • The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern.
  • The Adapter pattern is used extensively by the adapter classes in java.awt.event.
  • The Proxy pattern is used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features.
  • The structure of Component and Container classes in java.awt provide a good example of the Composite pattern.
  • The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.

J2EE design patterns
Presentation-tier patterns

Q. What is Intercepting Filter pattern?
A. Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.

Q. What is Front Controller pattern?
A. It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.

Q. What is View Helper pattern?
A. There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.

Q. What is Composite View pattern?
A. This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.

Q. What is Service to Worker pattern?

A. This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.

Q. What is Dispatcher View pattern?

A. This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.


Q. What is Business Delegate pattern?
A. This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.

Q. What is Value Object (VO) pattern?

A. Value Object is a serializable object which would contain lot of atomic values. These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation.



Business tier patterns for business logic (EJB) tier
Business delegate, Value Object, Session Facade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.

Q. What is Session Facade pattern?

A. This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.

Q. What is Value Object Assembler pattern?

A. This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects.

Q. What is Value List Handler pattern?

A. This pattern provides a sound solution for query execution and results processing.

Q. What is Service Locator pattern?

A. It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance.

Q. What is Data Access Object pattern?

A. It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer.

Q. What is EJB Command pattern?

A. Session Facade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations.

Q. What is Version Number pattern?

A. This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.

Q. What all patterns are used to improve performance and scalability of the application?
A. VO, Session Facade, Business Delegate and Service Locator.

Q. What design patterns could be used to manage security?
A. Single Access Point, Check point and Role patterns


Q. Describe the observer pattern and an example of how it would be used?A. Event notification when model changes to view