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

Sunday, November 27, 2011

Interface


In general, interface is the way just to say something to a media by using another media. Let's take the general life example. TV Remote is the interface because it is the medium to give the command to a TV in order to change the channels or to ON/OFF the TV. Electric switch is also the interface's example.

But in java programming language interface is nothing but the collection of methods with empty implementations and constants variables (variables with static and final declarations). All the methods in an interface are "public and abstract" by default. Since interfaces are abstract in nature so they can not be directly instantiated. To define the methods of an interface the keyword "implements" is used. 

Interfaces are similar to abstract classes but the major difference between these two is that interface have all the methods abstract while in case of abstract classes must have at least one abstract method. Interface combines the two functionality (template and multiple inheritance) of C++ language into one (in itself).  
 
Interface Definition
visibility mode interface InterfaceName {
        constant variable declarations
        
abstract method declarations
}

e.g.
public interface RacingCar {
  
public void startcar (int Obj); 
  
public void changegear (int Obj); 
  
public void incrrace (int Obj);
  
public void stopcar (int Obj);
}

Marker Interface
In java language programming, interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.
e.g.  Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.  
Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class, then a call to the method clone() on Myclass's object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.

Difference between Interfaces and abstract classes
Some important difference between Interface and abstract classes are given here

    Features                             Interface                             Abstract Class
    Methods An interface contains all the methods with empty implementation.An abstract class must have at least one method with empty implementation.        
   VariablesThe variables in interfaces are final and static.Abstract classes may contain both instance as well as static variables.
    Multiple   Inheritance In java multiple inheritance is achieved by using the interface (by implementing more than one interface at a time)Abstract classes does not provide this functionality.
 Additional Functions  If we add a method to an interface then we will have to implement this interface by any class..In Abstract classes we can add a method with default implementation and then we can use it by extending the abstract class. 
Used WhenAll the features are implemented differently in different objects.When there are some common features shared by all the objects.
Diff
Can’t have ConstructorCan have Constructor

IMP TIP: 
Why u can’t create object for Abstract Class: Since abstract class contains incomplete methods, it is not possible to estimate the total memory required to create an object. So JVM can’t create objects to an abstract class.

Tuesday, November 8, 2011

Factory Method Design Pattern

Intent

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • Defining a “virtual” constructor.
  • The new operator considered harmful.

Problem

A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation.

Discussion

Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual “placeholders” for creation steps), and then delegates the creation details to subclasses that are supplied by the client.
Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new operation.
People often use Factory Method as the standard way to create objects; but it isn’t necessary if: the class that’s instantiated never changes, or instantiation takes place in an operation that subclasses can easily override (such as an initialization operation).
Factory Method is similar to Abstract Factory but without the emphasis on families.
Factory Methods are routinely specified by an architectural framework, and then implemented by the user of the framework.

Structure

The implementation of Factory Method discussed in the Gang of Four (below) largely overlaps with that of Abstract Factory. For that reason, the presentation in this chapter focuses on the approach that has become popular since.

Scheme of Factory Method


An increasingly popular definition of factory method is: a static method of a class that returns an object of that class’ type. But unlike a constructor, the actual object it returns might be an instance of a subclass. Unlike a constructor, an existing object might be reused, instead of a new object created. Unlike a constructor, factory methods can have different and more descriptive names (e.g. Color.make_RGB_color(float red, float green, float blue) and Color.make_HSB_color(float hue, float saturation, float brightness)

Scheme of Factory Method


The client is totally decoupled from the implementation details of derived classes. Polymorphic creation is now possible.

Scheme of Factory Method


Example

The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate. Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold.

Example of Factory Method


Check list

  1. If you have an inheritance hierarchy that exercises polymorphism, consider adding a polymorphic creation capability by defining a static factory method in the base class.
  2. Design the arguments to the factory method. What qualities or characteristics are necessary and sufficient to identify the correct derived class to instantiate?
  3. Consider designing an internal “object pool” that will allow objects to be reused instead of created from scratch.
  4. Consider making all constructors private or protected.

Rules of thumb

  • Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype.
  • Factory Methods are usually called within Template Methods.
  • Factory Method: creation through inheritance. Prototype: creation through delegation.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Prototype doesn’t require subclassing, but it does require an Initialize operation. Factory Method requires subclassing, but doesn’t require Initialize.
  • The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
  • Some Factory Method advocates recommend that as a matter of language design (or failing that, as a matter of style) absolutely all constructors should be private or protected. It’s no one else’s business whether a class manufactures a new object or recycles an old one.
  • The new operator considered harmful. There is a difference between requesting an object and creating one. The new operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.
Java Example

public interface ImageReader {
    public DecodedImage getDecodedImage();
}

public class GifReader implements ImageReader {
    public GifReader( InputStream in ) {
        // check that it's a gif, throw exception if it's not, then if it is decode it.
    }

    public DecodedImage getDecodedImage() {
       return decodedImage;
    }
}

public class JpegReader implements ImageReader {
    //...
}