Abstract Factory Pattern

Definition

Provides one level of interface higher than the factory pattern. It is used to return one of several factories.

Where to use & benefits

  • Creates families of related or dependent objects like Kit.
  • Provides a class library of products, exposing interface not implementation.
  • Needs to isolate concrete classes from their super classes.
  • A system needs independent of how its products are created, composed, and represented.
  • Try to enforce a constraint.
  • An alternative to Facade to hide platform-specific classes
  • Easily extensible to a system or a family

 

Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.

There is also a view that abstract factory is ‘also’ implemented using prototype instead of factory methords pattern. Beginners for now please don’t yourself with that. Just go with factory methods pattern.

As there is a word ‘abstract’ in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is from object oriented programming paradim.

Sample abstract factory design pattern implementation in Java API

XML API implements abstract factory. There is a class name SchemaFactory. This acts as a factory and supports implemenation of multiple schemas using abstract factory design pattern.

Sample Java Source Code for Factory Method Design Pattern

Following is the interface, that will be returned as the final end product from the factories.


package com.javapapers.sample.designpattern.abstractfactory;

public interface Animal {
 public void breathe();
}

Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.


package com.javapapers.sample.designpattern.abstractfactory;

public interface AnimalFactory {
 public Animal createAnimal();
}

One of the factory from a predefined set which will instantiate the above interface.


package com.javapapers.sample.designpattern.abstractfactory;

public class SeaFactory implements AnimalFactory {

 public Animal createAnimal() {
 return new Shark();
 }

}

Second factory from a predefined set which will instantiate the Animal interface.


package com.javapapers.sample.designpattern.abstractfactory;

public class LandFactory implements AnimalFactory {
 public Animal createAnimal() {
 return new Elephant();
 }
}

Implementation of an Animal. This class is grouped with the first abstract factory.


package com.javapapers.sample.designpattern.abstractfactory;

public class Shark implements Animal {
 public void breathe() {
 System.out.println("I breathe in water! He he!");
 }
}

Implementation of an Animal. This class is grouped with the second abstract factory.


package com.javapapers.sample.designpattern.abstractfactory;

public class Elephant implements Animal {
 public void breathe() {
 System.out.println("I breathe with my lungs. Its easy!");
 }
}

Following class consumes the abstract factory.


package com.javapapers.sample.designpattern.abstractfactory;

public class Wonderland {
 public Wonderland(AnimalFactory factory) {
 Animal animal = factory.createAnimal();
 animal.breathe();
 }
}

Testing the abstract factory design pattern.


package com.javapapers.sample.designpattern.abstractfactory;

public class SampleAbstractFactory {

 public static void main(String args[]){
 new Wonderland(createAnimalFactory("water"));
 }

 public static AnimalFactory createAnimalFactory(String type){
 if("water".equals(type))
 return new SeaFactory();
 else
 return new LandFactory();
 }
}

Output of the above sample program for abstract factory pattern


<code>I breathe in water! He he!</code>

Advertisements

Factory Method Pattern

Definition

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.

Where to use & benefits

  • Connect parallel class hierarchies.
  • A class wants its subclasses to specify the object.
  • A class cannot anticipate its subclasses, which must be created.
  • A family of objects needs to be separated by using shared interface.
  • The code needs to deal with interface, not implemented classes.
  • Hide concrete classes from the client.
  • Factory methods can be parameterized.
  • The returned object may be either abstract or concrete object.
  • Providing hooks for subclasses is more flexible than creating objects directly.
  • Follow naming conventions to help other developers to recognize the code structure.

 

A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.

Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Sample factory method design pattern implementation in Java API

For a reference of how the factory method design pattern is implemented in Java, you can have a look at SAXParserFactory. It is a factory class which can be used to intantiate SAX based parsers to pares XML. The method newInstance is the factory method which instantiates the sax parsers based on some predefined logic.

Block diagram for The Design Pattern

Sample Java Source Code for Factory Method Design Pattern

Based on comments received from users, I try to keep my sample java source code as simple as possible for a novice to understand.

Base class:


package com.javapapers.sample.designpattern.factorymethod;

//super class that serves as type to be instantiated for factory method pattern
public interface Pet {

 public String speak();

}

First subclass:


package com.javapapers.sample.designpattern.factorymethod;

//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {

 public String speak() {
 return "Bark bark...";
 }
}

Second subclass:


package com.javapapers.sample.designpattern.factorymethod;

//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
 public String speak() {
 return "Quack quack...";
 }
}

Factory class:


package com.javapapers.sample.designpattern.factorymethod;

//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {

 public Pet getPet(String petType) {
 Pet pet = null;

 // based on logic factory instantiates an object
 if ("bark".equals(petType))
 pet = new Dog();
 else if ("quack".equals(petType))
 pet = new Duck();
 return pet;
 }
}

Using the factory method to instantiate


package com.javapapers.sample.designpattern.factorymethod;

//using the factory method pattern
public class SampleFactoryMethod {

 public static void main(String args[]){

 //creating the factory
 PetFactory petFactory = new PetFactory();

 //factory instantiates an object
 Pet pet = petFactory.getPet("bark");

 //you don't know which object factory created
 System.out.println(pet.speak());
 }

}

Output of the above sample program for Factory Method Pattern


<code>Bark bark</code>

Introduction To Design Patterns

Pattern is a defined, used and tested solution for a know problem. Design patterns is all about re-use. Software design patterns evolved as a subject of study only when object oriented programming started becoming popular. OOPS and design patterns became inseparable.

In OOPS, we should have well defined boundaries for objects. That is every object should have its roles and responsibilities well defined. Then at next level, we should have a clear interaction plan between objects. If you design a OO software with the above principle, then by default you will be following some of the already defined design patterns.

A formal definition for design patterns, “A design pattern addresses a recurring design problem that arises in specific design situations and presents a solution to it” (Buschmann, et. al. 1996)

Java widely uses design patterns in its APIs. It started as early as Java 1.2 in java foundation classes. By then you can see the widespread use of commonly know design patterns in collections framework and IO packages. When I say commonly known design patterns, I mention about the set of 23 design patterns by Gang of Four (GOF). Gamma, Helm, Johnson and Vlissides known as Gang of Four (GOF) published a book “Design Patterns — Elements of Reusable Software” (1995) based on their series of technical meetings. It is one of the best seller in computer science books till date.

In China gang of four means different set of people. Jiang Qing (Mao Zedong’s fourth wife), Zhang Chunqiao, Yao Wenyuan, and Wang Hongwen were very popular leaders of cultural revolution. They almost seized power after Mao Zedong’s death. But they were finally arrested and imprisoned for life.

Our GOF divided the 23 design patterns into three types creational design patterns, structural design patterns and behavioral design patterns.

Creational design patterns can be used to instantiate objects. Instead of instantiating objects directly, depending on scenario either X or Y object can be instantiated. This will give flexibility for instantiation in high complex business logic situations.

Structural design patterns can be used to organize your program into groups. This segregation will provide you clarity and will enable you for easier maintainability.

  • Adapter Pattern
  • Bridge Pattern
  • Composite Pattern
  • Decorator Pattern
  • Facade Pattern
  • Flyweight Pattern
  • Proxy Pattern

Behavioral design patterns can be used to define the communication and control flow between objects.

  • Chain Of Responsibility Pattern
  • Command Pattern
  • Interpreter Pattern
  • Iterator Pattern
  • Mediator Pattern
  • Memento Pattern
  • Observer Pattern
  • State Pattern
  • Strategy Pattern
  • Template Method Pattern
  • Visitor Pattern

Reference Book : Design Pattern Book

Access Modifiers In JavaAccess Modifiers In Java

Access modifiers specifies who can access them. There are four access modifiers used in java. They are public, private, protected, no modifer (declaring without an access modifer). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

I) Class level access modifiers (java classes only)

Only two access modifiers is allowed, public and no modifier

  • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
  • If a class has ‘no modifer’, then it CAN ONLY be accessed from ’same package’.

II) Member level access modifiers (java variables and java methods)

All the four public, private, protected and no modifer is allowed.

  • public and no modifier – the same way as used in class level.
  • private – members CAN ONLY access.
  • protected – CAN be accessed from ’same package’ and a subclass existing in any package can access.

For better understanding, member level access is formulated as a table:


Access Modifiers

Same Class Same Package Subclass Other packages
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N

First row {public Y Y Y Y} should be interpreted as:

  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ’same class’.
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ’same package’.
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ’subclass’.
  • Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’.

Second row {protected Y Y Y N} should be interpreted as:

  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ’same class’.
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ’same package’.
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ’subclass’.
  • N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’.

similarly interpret the access modifiers table for the third (no access modifier) and fourth (private access modifier) records.

What is a java marker interface?

Java marker interface has no members in it. Marker interface ‘was’ used as a tag to inform a message to the java compiler.

Java Marker Interface Examples:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener

Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

Explain the methods used for session tracking.

Following answer is applicable irrespective of the language and platform used. Before we enter into session tracking, following things should be understood.

What is a session?

A session is a conversion between the server and a client. A conversion consists series of continuous request and response.

Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.

When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.

Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.

Session tracking methods:

  1. User authorization
  2. Hidden fields
  3. URL rewriting
  4. Cookies
  5. Session tracking API

The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie alogwith it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:

Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);

Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.

Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using session tracking api.

How many types of java variables are there?

Java variables can be categorized into the following seven types:

  1. Class Variable
  2. Instance Variable
  3. Array Component Variable
  4. Method Parameter Variable
  5. Constructor Parameter Variable
  6. Exception Handler Parameter Variable
  7. Local Variable

1) Class Variable
A java class variable is a field declared using the keyword static within a java class, or with or without the keyword static within a java interface declaration.

2) Instance Variable
Java variables that are declared without static keyword are instance variables.

3) Array Component
Array components are unnamed java variables that are created and initialized to default values whenever a new java array object is created.

4) Method Parameter
Java variables declared in the method declaration signature are method parameter variables. Whenever a java method is invoked a variable is created in the same name as it is declared.

5) Constructor Parameter
This is similar to the java method parameter variable. The same way, for all the java variables declared in the constructor a variable is created whenever it is invoked.

6) Exception Handler Parameter
Java variables that are declared in the catch clause of a java exception handling mechanism. Whenever a java exception is caught, exception handler parameter variable is created.

7) Local Variable
Java variables that are declared in a block inside a java method or for loop is called a java local variable.