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.

UML

UML
The UML puts some notations to out software model. Usually, a single class is represented with a box that is divided into three parts:
  1. The upper section contains the class name.
  2. The middle section has lists attributes of the class.
  3. The lower section lists methods of the class.
The members of the class in the middle and lower sections can be prefixed with a symbol to indicate the access level or visibility:
  • +: a public member
  • -: a private member
  • #: a protected member
We can tell the relationships between classes by using various styles of connecting lines and arrowheads:
  • Association: A simple dependency between two classes where neither owns the other, indicated as a solid line. Association can be directional, shown with an open arrowhead (">").
  • Aggregation: A has-a, or whole/part, relationship where neither class owns the other, indicated as a solid line with a hollow diamond.
  • Composition: A has-a relationship where the lifetime of the part is managed by the whole. This is shown as a solid line with a filled diamond.
  • Generalization: A subclass relationship between classes, represented as a hollow triangle arrowhead.
Each side of a relationship can also be annotated to define its multiplicity. This lets us specify whether the relationship is one to one, one to many, or many to many:
  • 0..1 = zero or one instance
  • 1 = one instance
  • 0..* = zero or more instances
  • 1..* = one or more instances

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