Search

Useful Links

Friday, September 23, 2011

What is session facade?

A session façade is an EJB design pattern in which a session bean is works like a wrapper over entity beans. A client does not have a direct access to Entity beans but through session beans only for reducing network overhead. Usually stateless session beans are used as single access point for the clients but stateful session beans can also be used for the same purpose. A layer of session beans exposed to clients to access not only gives a clean approach towards client access to bean components but also reduce network calls so as to make the whole system of high performance.

Thursday, September 22, 2011

Difference between Abstract Factory and Factory Method design patterns?


In order to answer this question we must first understand what are Abstract Factory and Factory Method design patterns.

An Abstract Factory(AF) provides an interface for creating families of related or dependent objects without specifying their concrete classes. you usually have multiple factory implementations. Each factory implementation is responsible for creating objects that are usually in a related hierarchy.

In case of Factory Method(or simply called Factory pattern), generally a key or parameter is provided and method obtains an object of that type.The classic example can be creating a Database Connection Factory which is responsible for providing a vendor specific database connection objects(like Oracle,DB2,MS SQL Server etc.) depending upon the kind of parameter is provided.

AF is very similar to the Factory Method pattern.One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and
relies on a subclass to handle the desired object instantiation.

The best example to quote of AF is EJBHome object.When a client composes the home interface and calls a create method to get the component interface. The component interface is the abstract product and the implementation is created by the container. The client composes the abstract factory (home interface) and calls a create method on the abstract factory to create the product.

In nutshell, AF is a creational pattern for the family of objects, whereas the factory method is a way to get one individual member of a family.So in a way, AF uses Factory method.

Wednesday, September 21, 2011

Adapter Design Pattern in Java


Adapter design pattern lets unrelated classes communicate and work with each other.It achieves this objective by creating new interfaces for creating compatibility amongst otherwise non communicable classes.

The adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.

In case of listener interfaces,whenever a class implements such an interface, one has to implement all of the seven methods.In case of WindowListener interface,it has seven methods.WindowAdapter class implements WindowListener interface and make seven empty implementation. When a class subclasses WindowAdapter class, one may choose the implementation of a method as per one's choice of implementation.

Adapter design pattern is also referred as Wrapper pattern when it is introduced by composition of classes.

Tuesday, September 20, 2011

Decorator Design Pattern in Java


Decorator design pattern attaches additional responsibilities or functions, dynamically or statically on an object.One can add new functionalities on an object without affecting other objects enhancing flexibility of an object.

The best example of Decorator pattern in a visual manner can be illustrated from JScrollPane object which can be used to decorate a JTextArea object or a JEditorPane object. The different borders of a window like BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. are other examples of classes working as decorators existent in Java API.

Decorator pattern can be used in a non-visual fashion. For example, BufferedInputStream, DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These decorators are standard Java API classes.

Monday, September 19, 2011

Different types of design patterns?


There are three kinds of design patterns:

Creational patterns:

They are related with how objects and classes are created. While class-creation patterns use inheritance effectively in the instantiation process,while object-creation patterns use delegation to get the job done.

* Abstract Factory groups object factories that have a common theme.
* Builder constructs complex objects by separating construction and representation.
* Factory Method creates objects without specifying the exact object to create.
* Prototype creates objects by cloning an existing object.
* Singleton restricts object creation for a class to only one instance.

Structural patterns:

They are related to class and object composition.This pattern uses inheritance to define new interfaces in order to compose new objects and hence new functionalities.

* Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
* Bridge decouples an abstraction from its implementation so that the two can vary independently.
* Composite composes one-or-more similar objects so that they can be manipulated as one object.
* Decorator dynamically adds/overrides behavior in an existing method of an object.
* Facade provides a simplified interface to a large body of code.
* Flyweight reduces the cost of creating and manipulating a large number of similar objects.
* Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

Behavioral patterns:

These design patterns deal with objects communication. They are specifically concerned with communication between objects.

* Chain of responsibility delegates commands to a chain of processing objects.
* Command creates objects which encapsulate actions and parameters.
* Interpreter implements a specialized language.
* Iterator accesses the elements of an object sequentially without exposing its underlying representation.
* Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
* Memento provides the ability to restore an object to its previous state (undo).
* Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
* State allows an object to alter its behavior when its internal state changes.
* Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
* Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.

Explain Facade Design Pattern in Java


The objective of Facade pattern is to make a complex system simple. It is achieved by providing a unified or general interface, which is a higher layer to these subsystems.Facade pattern decouples subsystems, reduce its dependency, and improve portability,makes an entry point to your subsystems and hides clients from subsystem components and their implementation.

JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.

A client is exposed to certain set of methods like just getting a single instance of database connection or closing it when not required.

Another possibility is designing security of a system with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information, special guests may be allowed to access more information,administrators and executives may be allowed to access the most important information. These subsystems may be generalized by oneinterface. The identified users may be directed to the related
subsystems.

interface PublicMethod{
public void accessPublicMethod();
}

interface SpecialMethod extends PublicMethod{

public void accessSpecialMethod();

}

interface PrivateMethod extends PublicMethod {

public void accessPrivateInfo();

}

class PublicInfo implements PublicMethod{

public void accessPublicMethod() {

//...
}

//...
}

class SpecialInfo extends PublicInfo implements SpecialMethod {

public void accessSpecialMethod() {

//...
}

}

class PrivateInfo extends SpecialInfo implements PrivateMethod {

public void accessPrivateMethod () {

// ...

}

//...
}


The above code example illustrates that the whole system is not exposed to the clients. It depends on the user classification.

When a person is exposed to special information, that person is allowed to access public information also. When a person is exposed to private information, that person is allowed to access public and special information as well.

Sunday, September 18, 2011

What are Design Patterns and why one needs them?


A pattern based designing approach is best suited in devising solutions for problems occurring over and over again.The design patterns are language-independent strategies for solving common object-oriented design problems.

When you design, you should have advanced knowledge of such solutions in order to overcome problems that may occur in your system. GoF, Gang-Of-Four,because of the four authors who wrote, Design Patterns: Elements of Reusable Object-Oriented Software(ISBN 0-201-63361-2) is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. It is language independent approach of designing systems on the based of patterns.

Singleton Design Pattern?


The Singleton Design Pattern is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.

In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.
public class SingletonClass {
private static SingletonClass instance = null;
protected SingletonClass() {
// can not be instantiated.
}
public static SingletonClass getInstance() {
if(instance == null) {
instance = new SingletonClass();
}
return instance;
}
}

In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.

public class SingletonInstantiator {
public SingletonInstantiator() {
SingletonClass instance = SingletonClass.getInstance();
SingletonClass anotherInstance =
new SingletonClass();
...
}
}

In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.

Singleton Pattern

Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance

Thursday, September 15, 2011

10. What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
11. Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.
12. What is cold backup, hot backup, warm backup recovery?
Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is ‘online backup’ ) is a backup taken of each tablespace while the database is running and is being accessed by the users
13. What is the advantage of denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
14. How do you handle your own transaction ?
Connection Object has a method called setAutocommit ( boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.

Tuesday, September 13, 2011

JDBC Interview Question - Part 3

7. What is Connection?
Connection class represents a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
A Connection object’s database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
8. What does Class.forName return?
A class as loaded by the classloader.
9. What is Connection pooling?
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.

Monday, September 12, 2011

JDBC Interview Question - Part 2

. What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query.
5. What is DriverManager ?
DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.
6. What is a ResultSet ?
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

Also,

Resulset could be defined in three ways.
TYPE_SCROLL_SENSITIVE (can scroll forward or backward and sensitive to the changes made in the database)
TYPE_SCROLL_INSENSITIVE ( can scroll forward and backward but insensitive to database changes; It is actually snapshot of database so once data fetched not changed)
TYPE_FORWARD_ONLY (can move only in forward direction)

Saturday, September 10, 2011

What are the different JDBC drivers available?

here are mainly four type of JDBC drivers available. They are: Type 1 : JDBC-ODBC Bridge Driver – A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
Type 4: JDBC Net pure Java Driver – A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

JDBC Interview questions - Part 1

1. What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
2. What are stored procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has it’s own stored procedure language,
3. What is JDBC Driver ?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database.