Showing posts with label DESIGN PATTERNS. Show all posts
Showing posts with label DESIGN PATTERNS. Show all posts

Singleton Pattern

Singleton Pattern


The Singleton Pattern ensures a class has only one instance, and provide a global point of access to it.

1.     Synchronize the getInstance() method


public class Singleton{

   private static Singleton uniqueInstance;
   
   private Singleton() { }              // private constructor

   public static synchronize Singleton getInstance() {

       if(uniqueInstance == null)

            uniqueInstance = new Singleton();

    return uniqueInstance;

}


}


But Synchronizing  a method can decrease performance by a factor of 100.


2. Move to eargerly created Instance rather than lazily created one. If performance is an issue in your use of getInstance() method then this method of implementing the Singleton can drastically reduce the overhead.

Using this approach, we rely on the JVM to create the unique instance of the Singleton when class is loaded.The JVM guarantees that the instance will be created before any thread accesses the static uniqueInstance variable.

      public class Singleton{

            private static Singleton uniqueInstance = new Singleton(); 

             private Singleton() {}

            public static Singleton getInstance() {

                       return uniqueInstance;

                 }

      }
  

3. Use "double - checked locking" to reduce the use of Synchronization in getInstance()

    With double -checked locking, we first check to see if an instance is created and if not THEN we synchronize.This way we only synchronize the first time through,just what we want..

Volatile keyword ensures that multiple threads handle the uniqueInstance variable correctly when it is being initialized to the Singleton instance.


     public class Singleton{

            private volatile static Singleton uniqueInstance ; 

             private Singleton() {}

            public static Singleton getInstance() {
  
                       if(uniqueInstance == null){

                        synchronized (Singleton.class) {

                         if( uniqueInstance == null) { 
                                          uniqueInstance = new Singleton();

                               }
                          }

                    }
                       return  uniqueInstance;

      }

}


 





   



Abstract Factory design Pattern

Abstract Factory 

Intent

  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  • A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products".
  • The new operator considered harmful.

Problem

If an application is to be portable, it needs to encapsulate platform dependencies. These "platforms" might include: windowing system, operating system, database, etc. Too often, this encapsulatation is not engineered in advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code.

Discussion

Provide a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The "factory" object has the responsibility for providing creation services for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for them.
This mechanism makes exchanging product families easy because the specific classof the factory object appears only once in the application - where it is instantiated. The application can wholesale replace the entire family of products simply by instantiating a different concrete instance of the abstract factory.
Because the service provided by the factory object is so pervasive, it is routinely implemented as a Singleton.

Structure

The Abstract Factory defines a Factory Method per product. Each Factory Method encapsulates the newoperator and the concrete, platform-specific, product classes. Each "platform" is then modeled with a Factory derived class.
Scheme of Abstract Factory

Example

The purpose of the Abstract Factory is to provide an interface for creating families of related objects, without specifying concrete classes. This pattern is found in the sheet metal stamping equipment used in the manufacture of Japanese automobiles. The stamping equipment is an Abstract Factory which creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes.
Example of Abstract Factory

Check list

  1. Decide if "platform independence" and creation services are the current source of pain.
  2. Map out a matrix of "platforms" versus "products".
  3. Define a factory interface that consists of a factory method per product.
  4. Define a factory derived class for each platform that encapsulates all references to the new operator.
  5. The client should retire all references to new, and use the factory methods to create the product objects.

Composition vs. Aggregation

Composition vs. Aggregation


Aggregation and composition are both strong forms of association. They describe relationship between a whole and as its parts. So, instead of a has-a relationship as a simple association, we are dealing with a relationship says is part or reading the relationship in the other direction, is made up of.
Examples of these kind of relationship:
      Orchestra: Musician
      Orchestra is made up of Musicians
      or Musician is part of Orchestra
      Brochure: Product 
      Brochure is made up of Products
      or Product is part of Brochure
      Building: Room
      Building is made up of rooms
      or Room is part of Building
Composition is even stronger relationship than aggregation. To test if we are dealing withcomposition, use no sharing rule for composition: part can belong to only one whole.
For the #1 and #2, part (Musician/Product) can belong only one (Orchestra/Catalog) whole? Yes! But for #3, room can belong to more than one building. No! No sharing rule applies to this case. So, the relationship #3 is better described by composition than by aggregation.
Besides the no sharing rule, another the rule for composition is: if the whole is destroyed, is the part that makes it up also destroyed?
Only the case #3 follows the additional composition rule. If orchestra breaks it up, will musicians be destroyed? No!
Code Example: A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.
  • University - Department : composition: ownership: destroyed with the whole: strong has arelationship
    The composite object takes ownership of the component. This means the composite is responsible for the creation and destruction of the component parts. An object may only be part of one composite. If the composite object is destroyed, all the component parts must be destroyed.
    Composition enforces encapsulation as the component parts usually are members of the composite object:
    class University
    {
      ...
      private:
     
        Department faculty[20];
    
  • Department - Professors: aggregation: no ownership: may outlive: component may still have weakhas a relationship
    In aggregation, the object may only contain a reference or pointer to the object. The object may not have lifetime responsibility for the reference or pointer:
    class Department
    {
      ...
      private:
        // Aggregation
        Professor* members[5];
      ...
    };
  • Complete code example:
class Professor;
 
class Department
{
  ...
  private:
    // Aggregation
    Professor* members[5];
  ...
};
 
class University
{
  ...
  private:
 
    Department faculty[20];
  ...
 
  create dept()
  {
   ....
     // Composition
     faculty[0]= Department(....);
     faculty[1]= Department(....);
   ....   
  }
};
Source of the code and diagrams: wiki

Aggregation-Composition_A 
In UML, composition is depicted as a filled diamond and a solid line. It always implies a multiplicity of 1 or 0..1, as no more than one object at a time can have lifetime responsibility for another object. The more general form, aggregation, is depicted as an unfilled diamond and a solid line. The image above shows both composition and aggregation. 

ref :http://www.bogotobogo.com/DesignPatterns/introduction.php

Design Patterns

Patterns:

Composite Pattern:

Used under Design Problem: Non -Extensible and error prone design.

Composite Intent:Treat individual objects and multiple,recursively composed objects uniformly.

Bridge Pattern:

Used under Design Problem:Minimizing impact of variability.

Bridge Intent:Separate an abstraction from its implementation.So the two can vary independently.



Design Principles

1.Identify the aspects of your application that vary and separate them from what stays the same.

2.Program to an interface, not an implementation.

3.Favor composition over inheritance.

4.Classes should be open for extension, but closed for modification.

-The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Observer Pattern
� The Observer Pattern defines a one-to-many relationship between objects.
� Subjects, or as we also know them, Observables, update Observers using a common interface.
� Observers are loosely coupled in that the Observable knows nothing about them, other than that they implement the Observer Interface.
� You can push or pull data from the Observable when using the pattern (pull is considered
more “correct”).
� Don’t depend on a specific order of notifcation for your Observers.
� Java has several implementations of the Observer Pattern, including the general purpose java.util.Observable.
� Watch out for issues with the java.util.Observable implementation.
� Don’t be afraid to create your own Observable implementation if needed.
� Swing makes heavy use of the Observer Pattern, as do many GUI frameworks.
� You’ll also find the pattern in many other places, including JavaBeans and RMI.


Decorator pattern

The Decorator Pattern attaches additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending functionality.

� Decorators have the same supertype as the objects they decorate.
� You can use one or more decorators to wrap an object.
� Given that the decorator has the same supertype as the object it decorates, we can pass
around a decorated object in place of the original (wrapped) object.
� The decorator adds its own behavior either before and/or after delegating to the object it
decorates to do the rest of the job.
� Objects can be decorated at any time, so we can decorate objects dynamically at runtime
with as many decorators as we like.

Inversion Of Control(IOC) Design Pattern

Loose coupling is one of the critical elements in object-oriented software development. It allows you to change the implementations of two related objects without affecting the other object. Inversion of Control (IoC) is one approach you can use to achieve loose coupling between several interacting components in an application.

Popular Java IOC/DI Containers:

  • Spring Framework : A substantially large framework which offers a number of other capabilities apart from Dependency Injection.
  • PicoContainer : A fairly small tightly focused DI container framework.
  • HiveMind : Another DI container framework.
  • XWork : Primarily a command pattern framework which very effectively leverages Dependency Injection. While it is an independent framework in its own right, it is often used in conjunction with Webwork

Popular .Net IOC/DI Containers:

ref:

Inversion of Control Containers and the Dependency Injection pattern(Martin Fowler) - http://martinfowler.com/articles/injection.html






Inversion Of Control(Java Boutique) - http://javaboutique.internet.com/tutorials/loose/

Design Patterns

Design Patterns represent solutions to problems what arise when developing software within a particular context.

Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.

Patterns help you learn from other's successes, instead of your own failures.

Three categories of Design Patterns:
  1. Creational Patterns: deal with initializing and configuring classes and objects
  2. Structural Patterns: deal with decoupling the interface and implementation of classes and objects
  3. Behavioral Patterns: deal with dynamic interactions among societies of classes and objects

Creational Patterns:

Abstract Factory: Creates an instance of several families of classes
resource 1
resource 2

Builder: Separates object construction from its representation
resource 1
resource 2

Factory Method: Creates an instance of several derived classes
resource 1
resource 2

Prototype: A fully initialized instance to be copied or cloned
resource 1
resource 2

Singleton: A class of which only a single instance can exist
resource 1
resource 2

Structural Patterns:

Adapter: Match interfaces of different classes
resource 1
resource 2


Bridge: Separates an object’s interface from its implementation
resource 1
resource 2

Composite: A tree structure of simple and composite objects
resource 1
resource 2


Decorator: Add responsibilities to objects dynamically
resource 1
resorce 2

Façade: A single class that represents an entire subsystem
resource 1
resource 2

Flyweight: A fine-grained instance used for efficient sharing
resource 1
resource 2

Proxy: An object representing another object
resource 1
resource 2

Behavioral Patterns:

Chain of Responsibility: A way of passing a request between a chain of objects
resource 1
resource 2

Command: Encapsulate a command request as an object
resource 1
resource 2

Interpreter: A way to include language elements in a program
resource 1
resource 2

Iterator: Sequentially access the elements of a collection
resource 1
resource 2

Mediator: Defines simplified communication between classes
resource 1
resource 2

Memento: Capture and restore an object's internal state
resource 1

Observer: A way of notifying change to a number of classes
resource 1
resource 2

State: Alter an object's behavior when its state changes
resource 1
resource 2

Strategy: Encapsulates an algorithm inside a class
resource 1
resource 2

Template Method: Defer the exact steps of an algorithm to a subclass
resource 1
resource 2

Visitor: Defines a new operation to a class without change
resource 1
resource 2

ref:

Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (also known as Gang of Four)

Huston Design Patterns - http://www.vincehuston.org/dp/

Thinking in Patterns with Java, by Bruce Eckel

Thinking in Patterns with C++, by Bruce Eckel