Tuesday, April 24, 2012

Inheritance vs Composition vs Aggregation



There are two fundamental mechanisms for building new classes from existing ones: inheritance and aggregation---Khalid Mughal



Inheritance: (IS-A)

“Wiki” definition: inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined.

Other definition: One class can use features from another class to extend its functionality (an “Is a” relationship) i.e., a Car is a Automobile.

Inheritance is the inclusion of behaviour (i.e. methods) and state (i.e. variables) of a base class in a derived
class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse.

The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.

Inheritance is uni-directional. For example Car is a Vehicle. But Vehicle is not a Car. Inheritance uses extends key word. Composition: is used when Car has a Engine. It is incorrect to say Car is a
Engine. Composition simply means using instance variables that refer to other objects. The class Car will have an instance variable, which refers to a Engine object.


public class  Vehicle{
 . . .
}
public class  Car extends Vehicle {
 . . .
}


There are two types of inheritances:

1. Implementation inheritance (aka class inheritance)
2. Interface inheritance (aka type inheritance)


Which one to use?

Prefer interface inheritance to implementation inheritance because it promotes the design
concept of coding to an interface and reduces coupling. Interface inheritance can achieve code reuse with the help of object composition. If you look at Gang of Four (GoF) design patterns, you can see that it favours interface inheritance to implementation inheritance.



 ASSOCIATION: (HAS-A)

  1. Composition 
  2. Aggregation  

Composition

Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part CANNOT exist without a whole. If a whole is deleted then all parts are deleted.

“Wiki” definition: “object composition (not to be confused with function composition) is a way to combine simple objects or data types into more complex ones.”

Other definition: Allowing a class to contain object instances in other classes so they can be used to perform actions related to the class (an “has a” relationship) i.e., a person has the ability to walk.


As we know, inheritance gives us an 'is-a' relationship. To make the understanding of composition easier, we can say that composition gives us a 'part-of' relationship. Composition is shown on a UML diagram as a filled diamond.
        






If we were going to model a car, it would make sense to say that an engine is part-of a car. Within composition, the lifetime of the part (Engine) is managed by the whole (Car), in other words, when Car is destroyed, Engine is destroyed along with it.


public class Engine
{
 . . .
}
public class Car
{
    Engine e = new Engine();
    .......
}


As you can see in the example code above, Car manages the lifetime of Engine.



Which one to use?

The guide is that inheritance should be only used when subclass ‘is a’ superclass.



  •  Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the superclass is modified.
  •  Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse



Aggregation:


Aggregation is an association in which one class belongs to a collection. This is a part of a whole
relationship where a part CAN exist without a whole.

Just like composition, aggregation occurs when an object is composed of multiple objects. However, with composition, the internal objects (such as Tyre , Seat and Engine ) are owned by the main object ( Car ). If you destroy the Car , you also likely want the Tyre , Seat and Engine instances destroyed because they are a composition which, together, form a single Car.





The Car instance certainly doesn't own the Driver and you probably shouldn't assume that the Driver is destroyed if the Car is destroyed. Further, the Driver exists independent of the Car . The Driver can leave this Car and sit in another one. This independence makes a great deal of difference so this combination of objects is referred to as an aggregation instead of composition. When designing your applications, it is important to note that difference



public class Car
{
     private Driver driver;

     public Car(Driver driver)        // Constructor
     {
         this.driver = driver;
     }
     . . .
}


Car would then be used as follows:

Driver driver = new Driver ();


Car ford = 
new Car(driver);
or
Car ford = new Car(new Driver());

Wednesday, April 11, 2012

Introduction to features introduced in Java 5


The J2SE 5.0 release is focused along certain key themes:


  • Ease of Development
  • Scalability and Performance
  • Monitoring and Manageability
  • Desktop Client

There are a small number of features that are just as important but didn't neatly fit in with the themes; they are listed at the end:

Miscellaneous Features
Ease of Development

The changes include

  • Generic types
  • Metadata
  • Autoboxing
  • Enhanced for loop
  • Enumerated types
  • Static import
  • C style formatted input/output
  • Variable arguments
  • Concurrency utilities
  • Simpler RMI interface generation


JSR-201 contains four of these language changes; enhanced for loop, enumerated types, static import and autoboxing;
JSR-175 specifies the new metadata functionality
JSR-14  details generic types.


Metadata
The metadata feature in J2SE 5.0 provides the ability to associate additional data alongside

  • Java classes
  • Interfaces
  • Methods
  • Fields

This additional data, or annotation, can be read by the javac compiler or other tools, and depending on configuration can also be stored in the class file and can be discovered at runtime using the Java reflection API.

One of the primary reasons for adding metadata to the Java platform is to enable development and runtime tools to have a common infrastructure and so reduce the effort required for programming and deployment. A tool could use the metadata information to generate additional source code, or to provide additional information when debugging.

In beta2 Java announce the availability of an annotation processing tool called apt.

Apt includes

  1. set of new reflective APIs 
  2. supporting infrastructure to process program annotations. 

The apt reflective APIs provide a build-time, source-based, read-only view of program structure which cleanly models the Java programming language's type system.

First, apt runs annotation processors that can produce new source code and other files.
Next, apt can cause compilation of both original and generated source files, easing development. For more information on apt refer to the apt guide.

In the following example code you can additionally create an AnnotationFactory processor for apt to generate code or documentation when finding the debug annotation tag.

import java.lang.annotation.*;
import java.lang.reflect.*;
                                                                             
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface debug  {
    boolean  devbuild() default false;
    int counter();
}
                                                                             
public class MetaTest {
    final boolean production=true;

    @debug(devbuild=production,counter=1) public void testMethod()  {
    }

                                                                             
    public static void main(String[] args) {
                                                                             
        MetaTest mt = new MetaTest();
        try {
            Annotation[] a = mt.getClass().getMethod("testMethod").getAnnotations();
            for (int i=0; i<a.length ; i++)  {
                 System.out.println("a["+i+"]="+a[i]+" ");
             }
         } catch(NoSuchMethodException e) {
             System.out.println(e);
         }
     }
 }

With a metadata processing tool, many repetitive coding steps could be reduced to a concise metadata tag. For example, the remote interface required when accessing a JAX-RPC service implementation could be implemented as follows:

Before

public interface PingIF extends Remote {
      public void ping() throws RemoteException;
  }

  public class Ping implements PingIF {
     public void ping() {
     }
  }

After

public class Ping {
     public @remote void ping() {
     }
  }

Generic Types
One of the first places to see generic types in action is the Collections API. The Collections API provides common functionality like LinkedLists, ArrayLists and HashMaps that can be used by more than one Java type.
Following example uses the 1.4.2 libraries and the default javac compile mode.

ArrayList list = new ArrayList();
  list.add(0, new Integer(42));
  int total = ((Integer)list.get(0)).intValue();

The cast to Integer on the last line is an example of the typecasting issues that generic types aim to prevent. The issue is that the 1.4.2 Collection API uses the Object class to store the Collection objects, which means that it cannot pick up type mismatches at compile time. The first notification of a problem is a ClassCastException at runtime.

The same example with the generified Collections library is written as follows:

ArrayList<Integer> list =  new ArrayList<Integer>();
   list.add(0, new Integer(42));
   int total = list.get(0).intValue();

The user of a generified API has to simply declare the type used at compile type using the <> notation. No casts are needed and in this example trying to add a String object to an Integer typed collection would be caught at compile time.

Generic types therefore enable an API designer to provide common functionality that can be used with multiple data types and which also can be checked for type safety at compile time.


Autoboxing and Auto-Unboxing of Primitive Types
Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like Integer and Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only needed for a method call to the Collections API, for example.

The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow. In the next example an int is being stored and then retrieved from an ArrayList. The 5.0 version leaves the conversion required to transition to an Integer and back to the compiler.

Before

ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(0, new Integer(42));
  int total = (list.get(0)).intValue();

After

ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(0, 42);
  int total = list.get(0);

Enhanced for Loop
The Iterator class is used heavily by the Collections API. It provides the mechanism to navigate sequentially through a Collection. The new enhanced for loop can replace the iterator when simply traversing through a Collection as follows. The compiler generates the looping code necessary and with generic types no additional casting is required.

Before

ArrayList<Integer> list = new ArrayList<Integer>();
  for (Iterator i = list.iterator(); i.hasNext();) {
         Integer value=(Integer)i.next();
    }

After

ArrayList<Integer> list = new ArrayList<Integer>();
     for (Integer i : list) { ... } //compiler generates the looping code necessary and with generic types no additional casting is required

Enumerated Types
This type provides enumerated type when compared to using static final constants. If you have previously used the identifier enum in your own application, you will need to adjust the source when compiling with javac -source 1.5 (or its synonym -source 5).

public enum StopLight { red, amber, green };

Static Import
The static import feature, implemented as "import static", enables you to refer to static constants from a class without needing to inherit from it. Instead of BorderLayout.CENTER each time we add a component, we can simply refer to CENTER.

import static java.awt.BorderLayout.*;

 getContentPane().add(new JPanel(), CENTER);

Formatted Output
Developers now have the option of using printf-type functionality to generate formatted output. This will help migrate legacy C applications, as the same text layout can be preserved with little or no change.

Most of the common C printf formatters are available, and in addition some Java classes like Date and BigInteger also have formatting rules. See the java.util.Formatter class for more information. Although the standard UNIX newline '\n' character is accepted, for cross-platform support of newlines the Java %n is recommended.

System.out.printf("name count%n");
    System.out.printf("%s %5d%n", user,total);

Formatted Input
The scanner API provides basic input functionality for reading data from the system console or any data stream. The following example reads a String from standard input and expects a following int value.

The Scanner methods like next and nextInt will block if no data is available. If you need to process more complex input, then there are also pattern-matching algorithms, available from the java.util.Formatter class.

Scanner s= new Scanner(System.in);
    String param= s.next();
    int value=s.nextInt();
    s.close();

Varargs
The varargs functionality allows multiple arguments to be passed as parameters to methods. It requires the simple ... notation for the method that accepts the argument list and is used to implement the flexible number of arguments required for printf.

void argtest(Object ... args) {
      for (int i=0;i <args.length; i++) {
      }
    }
 
    argtest("test", "data");

Concurrency Utilities
The concurrency utility library, led by Doug Lea in JSR-166, is a special release of the popular concurrency package into the J2SE 5.0 platform.

It provides powerful, high-level thread constructs, including executors, which are a thread task framework, thread safe queues, Timers, locks (including atomic ones), and other synchronization primitives.

One such lock is the well known semaphore. A semaphore can be used in the same way that wait is used now, to restrict access to a block of code. Semaphores are more flexible and can also allow a number of concurrent threads access, as well as allow you to test a lock before acquiring it. The following example uses just one semaphore, also known as a binary semaphore. See the java.util.concurrent package for more information.

final  private Semaphore s= new Semaphore(1, true);

    s.acquireUninterruptibly(); //for non-blocking version use s.acquire()

try {  
   balance=balance+10; //protected value
} finally {
  s.release(); //return semaphore token
}

rmic -- The RMI Compiler
You no longer need to use rmic, the rmi compiler tool, to generate most remote interface stubs. The introduction of dynamic proxies means that the information normally provided by the stubs can be discovered at runtime. See the RMI release notes for more information.

Scalability and Performance
The 5.0 release promises improvements in scalability and performance, with a new emphasis on startup time and memory footprint, to make it easier to deploy applications running at top speed.

One of the more significant updates is the introduction of class data sharing in the HotSpot JVM. This technology not only shares read-only data between multiple running JVMs, but also improves startup time, as core JVM classes are pre-packed.

Performance ergonomics are a new feature in J2SE 5.0. This means that if you have been using specialized JVM runtime options in previous releases, it may be worth re-validating your performance with no or minimal options.

Monitoring and Manageability
Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform.

The J2SE 5.0 release provides comprehensive monitoring and management support: instrumentation to observe the Java virtual machine, Java Management Extensions (JMX) framework, and remote access protocols. All this is ready to be used out-of-the-box. (See the Management and Monitoring release notes for more details.)

The JVM Monitoring & Management API specifies a comprehensive set of instrumentation of JVM internals to allow a running JVM to monitored. This information is accessed through JMX (JSR-003) MBeans and can accessed locally within the Java address space or remotely using the JMX remote interface (JSR-160) and through industry-standard SNMP tools.

One of the most useful features is a low memory detector. JMX MBeans can notify registered listeners when the threshold is crossed, see javax.management and java.lang.management for details.

J2SE 5.0 provides an easy way to enable out-of-the-box remote management of JVM and an application (see Out-of-the-Box for details). For example, to start an application to be monitorable by jconsole in the same local machine, use the following system property:

java -Dcom.sun.management.jmxremote -jar Java2Demo.jar

and to monitor it remotely through JMX without authentication:

java -Dcom.sun.management.jmxremote.port=5001
       -Dcom.sun.management.jmxremote.ssl=false
       -Dcom.sun.management.jmxremote.authenticate=false -jar Java2Demo.jar

For an idea of how easy the new API is to use, the following reports the detailed usage of the memory heaps in the HotSpot JVM.

import java.lang.management.*;
import java.util.*;

public class MemTest {
     public static void main(String args[]) {
          List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
          for (MemoryPoolMXBean p: pools) {
               System.out.println("Memory type="+p.getType()+" Memory usage="+p.getUsage());
         }
     }
}

New JVM Profiling API (JSR-163)
The release also contains a more powerful native profiling API called JVMTI. This API has been specified through JSR-163 and was motivated by the need for an improved profiling interface. However, JVMTI is intended to cover the full range of native in-process tools access, which in addition to profiling, includes monitoring, debugging and a potentially wide variety of other code analysis tools.

The implementation includes a mechanism for bytecode instrumentation, Java Programming Language Instrumentation Services (JPLIS). This enables analysis tools to add additional profiling only where it is needed. The advantage of this technique is that it allows more focused analysis and limits the interference of the profiling tools on the running JVM. The instrumentation can even be dynamically generated at runtime, as well as at class loading time, and pre-processed as class files.

The following example creates an instrumentation hook that can load a modified version of the class file from disk. To run this test, start the JRE with java -javaagent:myBCI BCITest

//File myBCI.java
 import java.lang.instrument.Instrumentation;

 public class myBCI {
     private static Instrumentation instCopy;
   
     public static void premain(String options, Instrumentation inst) {
         instCopy = inst;
     }
     public static Instrumentation getInstrumentation() {
         return instCopy;
     }
 }

 //File BCITest.java

 import java.nio.*;
 import java.io.*;
 import java.nio.channels.*;
 import java.lang.instrument.*;

 public class BCITest {
     public static void main (String[] args) {
         try {
             OriginalClass mc = new OriginalClass();
             mc.message();
       
             FileChannel fc=new FileInputStream(
new File("modified"+File.separator+"OriginalClass.class")).getChannel();
             ByteBuffer buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
             byte[] classBuffer  = new byte[buf.capacity()];
             buf.get(classBuffer, 0, classBuffer.length);
             myBCI.getInstrumentation().redefineClasses(
new ClassDefinition[] {
new ClassDefinition(mc.getClass(), classBuffer)});
             mc.message();
         }catch (Exception e){}
     }
 }

 //OriginalClass.java
 //Compile in current directory
 //Copy source to modified directory,change message and recompile

 public class OriginalClass {
     public void message() {
         System.out.println("OriginalClass");
     }
 }

Improved Diagnostic Ability
Generating Stack traces has been awkward if no console window has been available. Two new APIs, getStackTrace and Thread.getAllStackTraces provide this information programmatically.

StackTraceElement e[]=Thread.currentThread().getStackTrace();
for (int i=0; i <e.length; i++) {
     System.out.println(e[i]);
    }
System.out.println("\n"+Thread.getAllStackTraces());

The HotSpot JVM includes a fatal error handler that can run a user-supplied script or program if the JVM aborts. A debug tool can also connect to a hung JVM or core file using the HotSpot JVM serviceability agent connector.

-XX:OnError="command"
   

-XX:OnError="pmap %p"
-XX:OnError="gdb %p"

optional %p used as process id

Desktop Client
The Java Desktop client remains a key component of the Java platform and as such has been the focus of many improvements in J2SE 5.0.

This Beta release contains some of the early improvements in startup time and memory footprint. Not only is the release faster, but the Swing toolkit enjoys a fresh new theme called Ocean. And by building on the updates in J2SE 1.4.2, there are further improvements in the GTK skinnable Look and Feel and the Windows XP Look and Feel.


Linux and Solaris users, and new in beta2, Windows users, who have the latest OpenGL drivers and select graphic cards can get native hardware acceleration from Java2D using the following runtime property:

java -Dsun.java2d.opengl=true -jar Java2D.jar

The Linux release also has the fast X11 toolkit, called XAWT, enabled by default. If you need to compare against the motif version you can use the following system property:

java -Dawt.toolkit=sun.awt.motif.MToolkit -jar Notepad.jar

(the X11 toolkit is called sun.awt.X11.XToolkit)

The X11 Toolkit also uses the XDnD protocol so you can drag-and-drop simple components between Java and other applications like StarOffice or Mozilla.

Miscellaneous Features
Core XML Support
J2SE 5.0 introduces several revisions to the core XML platform, including XML 1.1 with Namespaces, XML Schema, SAX 2.0.2, DOM Level 3 Support and XSLT with a fast XLSTC compiler.

In addition to the core XML support, future versions of the Java Web Services Developer Pack will deliver the latest web services standards: JAX-RPC & SAAJ (WSDL/SOAP), JAXB, XML Encryption, and Digital Signature and JAXR for registries.

Supplementary Character Support
32-bit supplementary character support has been carefully added to the platform as part of the transition to Unicode 4.0 support. Supplementary characters are encoded as a special pair of UTF16 values to generate a different character, or codepoint. A surrogate pair is a combination of a high UTF16 value and a following low UTF16 value. The high and low values are from a special range of UTF16 values.

In general, when using a String or sequence of characters, the core API libraries will transparently handle the new supplementary characters for you. However, as the Java "char" still remains at 16 bits, the very few methods that used char as an argument now have complementary methods that can accept an int value which can represent the new larger values. The Character class in particular has additional methods to retrieve the current character and the following character in order to retrieve the supplementary codepoint value as below:

String u="\uD840\uDC08";
    System.out.println(u+"+ "+u.length());
    System.out.println(Character.isHighSurrogate(u.charAt(0)));
    System.out.println((int)u.charAt(1));
    System.out.println((int)u.codePointAt(0));

See the Unicode section in Character for more details.

JDBC RowSets
There are five new JDBC RowSet class implementations in this release. Two of the most valuable ones are CachedRowSet and WebRowSet. RowSet objects, unlike ResultSet objects, can operate without always being connected to a database or other data source. Without the expensive overhead of maintaining a connection to a data source, they are much more lightweight than a ResultSet object. The CachedRowSet contains an in-memory collection of rows retrieved from the database that can, if needed, be synchronized at a later point in time. The WebRowSet implementation, in addition, can write and read the RowSet in XML format.

The following code fragment shows how easy it is to create and use a WebRowSet object.

Class.forName("org.postgresql.Driver");
      WebRowSetImpl wrs = new WebRowSetImpl();
      wrs.setCommand("SELECT COF_NAME,TOTAL FROM COFFEES");
                                                                             
      wrs.setUsername("postgres");
      wrs.setPassword("");
      wrs.setUrl("jdbc:postgresql:test");
      wrs.execute(); // executes command and populates webset all coffees

      wrs.absolute(1); // moves cursor to the first row of wrs
      wrs.updateInt(2, 10); // reset total field to 10
      wrs.updateRow(); // finishes edits to this row
      wrs.acceptChanges(); // writes new total to the data source
      wrs.writeXml(System.out); // also exports rowset in XML format
      wrs.close();

Shared from http://java.sun.com/developer/technicalArticles/releases/j2se15/

Design Patterns





Creational Design Patterns:

Singleton - Ensure that only one instance of a class is created and Provide a global access point to the object.

Factory(Simplified version of Factory Method) - Creates objects without exposing the instantiation logic to the client and Refers to the newly created object through a common interface.

Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.

Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.

Builder - Defines an instance for creating an object but letting subclasses decide which class to instantiate and Allows a finer control over the construction process.

Prototype - Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Object Pool - reuses and shares objects that are expensive to create..




Behavioral Design Patterns:


Chain of Responsibiliy - It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too. The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.

Command - Encapsulate a request in an object, Allows the parameterization of clients with different requests and Allows saving the requests in a queue.

Interpreter - Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language / Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design

Iterator - Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Mediator - Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

Observer - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Strategy - Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Template Method - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses / Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure.

Visitor - Represents an operation to be performed on the elements of an object structure / Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Null Object - Provide an object as a surrogate for the lack of an object of a given type. / The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.




Structural Design Patterns:


Adapter - Convert the interface of a class into another interface clients expect. / Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

Bridge - Compose objects into tree structures to represent part-whole hierarchies. / Composite lets clients treat individual objects and compositions of objects uniformly.

Composite - Compose objects into tree structures to represent part-whole hierarchies. / Composite lets clients treat individual objects and compositions of objects uniformly.

Decorator - add additional responsibilities dynamically to an object.

Flyweight - use sharing to support a large number of objects that have part of their internal state in common where the other part of state can vary.

Memento - capture the internal state of an object without violating encapsulation and thus providing a mean for restoring the object into initial state when needed.

Proxy - provide a “Placeholder” for an object to control references to it.




Design patterns in your Java project

  • Strategy
  • Iterator
  • Decorator
  • Visitor
  • Singleton
  • Factory
  • Command
  • MVC
Strategy pattern

By definition Strategy design pattern  allow an object to change  its behaviour when its internal state changes. The object will appear to change its class. The Strategy design pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The algorithms can also be expressed independently of the data they are using.



Strategy - defines an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.

ConcreteStrategy - each concrete strategy implements an algorithm.

Context
contains a reference to a strategy object.
may define an interface that lets strategy accessing its data.
The Context objects contains a reference to the ConcreteStrategy that should be used. When an operation is required then the algorithm is run from the strategy object. The Context is not aware of the strategy implementation. If necessary, addition objects can be defined to pass data from context object to strategy.

The context object receives requests from the client and delegates them to the strategy object. Usually the ConcreteStartegy is created by the client and passed to the context. From this point the clients interacts only with the context.

Note:
The strategy design pattern splits the behavior (there are many behaviors) of a class from the class itself. This has some advantages, but the main draw back is that a client must understand how the Strategies differ. Since clients get exposed to implementation issues the strategy design pattern should be used only when the variation in behavior is relevant to them.
Passing data to/from Strategy object

Usually each strategy need data from the context have to return some processed data to the context. This can be achieved in 2 ways.
creating some additional classes to encapsulate the specific data.
passing the context object itself to the strategy objects. The strategy object can set returning data directly in the context.
When data should be passed the drawbacks of each method should be analyzed. For example, if some classes are created to encapsulate additional data, a special care should be paid to what fields are included in the classes. Maybe in the current implementation all required fields are added, but maybe in the future some new strategy concrete classes require data from context which are not include in additional classes. Another fact should be specified at this point: it's very likely that some of the strategy concrete classes will not use field passed to the in the additional classes.

On the other side, if the context object is passed to the strategy then we have a tighter coupling between strategy and context.

Strategy and Bridge Design Pattern
Both of the patterns have the same UML diagram. But they differ in their intent since the strategy is related with the behavior and bridge is for structure. Further more, the coupling between the context and strategies is tighter that the coupling between the abstraction and implementation in the bring pattern.







public interface IBehaviour {
                public int moveCommand();
}

public class Fast implements IBehaviour{
                public int moveCommand()
                {
                                System.out.println("\tFast Behaviour: Wont go beyond 200 kph");
                                return 1;
                }
}

public class Moderate implements IBehaviour{
                public int moveCommand()
                {
                                System.out.println("\Moderate Behaviour: Wont go beyond 150 kph");
                                return -1;
                }
}

public class Slow implements IBehaviour{
                public int moveCommand()
                {
                                System.out.println("\tSlow Behaviour: Wont go beyond 100 kph");
                                return 0;
                }
}

public class Car {
                IBehaviour behaviour;
                String name;

                public Car(String name)
                {
                                this.name = name;
                }

                public void setBehaviour(IBehaviour behaviour)
                {
                                this.behaviour = behaviour;
                }

                public IBehaviour getBehaviour()
                {
                                return behaviour;
                }

                public void move()
                {
                                System.out.println(this.name + ": Based on current position" +
                                                                                 "the behaviour object decide the next move:");
                                int command = behaviour.moveCommand();
                                // ... send the command to mechanisms
                                System.out.println("\tThe result returned by behaviour object " +
                                                                                "is sent to the movement mechanisms " +
                                                                                " for the Car '"  + this.name + "'");
                }

                public String getName() {
                                return name;
                }

                public void setName(String name) {
                                this.name = name;
                }
}


public class Main {

                public static void main(String[] args) {

                                Car r1 = new Car("Honda City");
                                Car r2 = new Car("Swift");
                                Car r3 = new Car("Nano");

                                r1.setBehaviour(new Fast());
                                r2.setBehaviour(new Moderate());
                                r3.setBehaviour(new Slow());

                                r1.move();
                                r2.move();
                                r3.move();

                                r1.setBehaviour(new Moderate());
                                r2.setBehaviour(new Fast());

                                r1.move();
                                r2.move();
                                r3.move();
                }
}


Singleton pattern

A singleton is a class that can be instantiated only one time in a JVM per class loader. Repeated calls always
return the same instance. Ensures that a class has only one instance, and provide a global point of access. It
can be an issue if singleton class gets loaded by multiple class loaders.

public class OnlyOne {
             private static OnlyOne one = new OnlyOne();
             private OnlyOne(){… } //private constructor. This class cannot be instantiated from outside.
             public static OnlyOne getInstance() {
                           return one;
                           }
                }


To use it:
//No matter how many times you call, you get the same instance of the object.
OnlyOne myOne = OnlyOne.getInstance();

Note: The constructor must be explicitly declared and should have the private access modifier, so that it cannot be
instantiated from out side the class. The only way to instantiate an instance of class OnlyOne is through the getInstance() method with a public access modifier.

When to use: Use it when only a single instance of an object is required in memory for a single point of access.

For example the following situations require a single point of access, which gets invoked from various parts of
the code.

􀂃 Accessing application specific properties through a singleton object, which reads them for the first time from
a properties file and subsequent accesses are returned from in-memory objects. Also there could be
another piece of code, which periodically synchronizes the in-memory properties when the values get
modified in the underlying properties file. This piece of code accesses the in-memory objects through the
singleton object (i.e. global point of access).

􀂃 Accessing in-memory object cache or object pool, or non-memory based resource pools like sockets,
connections etc through a singleton object (i.e. global point of access).
What is the difference between a singleton class and a static class? Static class is one approach to make a class singleton
by declaring the class as “final” so that it cannot be extended and declaring all the methods as static so that you can’t create any
instance of the class and can call the static methods directly.




A Factory method pattern (aka Factory pattern) is a creational pattern. The creational patterns abstract the object instantiation process by hiding how the objects are created and make the system independent of the object creation process. An Abstract factory pattern is one level of abstraction higher than a factory method pattern,
which means it returns the factory classes.

Factory method pattern (aka Factory pattern)

Factory for what? Factory pattern returns one of the several product subclasses. You should use a factory pattern If you have a super class and a number of subclasses, and based on some data provided, you have to return the object of one of the subclasses.

 Let’s look at a sample code:


public interface Const {
             public static final int SHAPE_CIRCLE =1;
             public static final int SHAPE_SQUARE =2;
             public static final int SHAPE_HEXAGON =3;
        }


public class ShapeFactory {
             public abstract Shape getShape(int shapeId);
     }


public class SimpleShapeFactory extends ShapeFactory throws BadShapeException {

public Shape getShape(int shapeTypeId) {

Shape shape = null;

if(shapeTypeId == Const.SHAPE_CIRCLE) {
             //in future can reuse or cache objects.
             shape = new Circle();
    }
else if(shapeTypeId == Const.SHAPE_SQUARE) {
             //in future can reuse or cache objects
             shape = new Square();
     }
else throw new BadShapeException
             (“ShapeTypeId=”+ shapeTypeId);

return shape;
       }
}



Now let’s look at the calling code, which uses the factory:

ShapeFactory factory = new SimpleShapeFactory();
//returns a Shape but whether it is a Circle or a
//Square is not known to the caller.
Shape s = factory.getShape(1);
s.draw(); // circle is drawn
//returns a Shape but whether it is a Circle or a
//Square is not known to the caller.
s = factory.getShape(2);
s.draw(); //Square is drawn



Abstract factory pattern


An Abstract factory pattern is one level of abstraction higher than a factory method pattern, which means the abstract factory returns the appropriate factory classes, which will later on return one of the product subclasses.

 Let’s look at a sample code:
public class ComplexShapeFactory extends ShapeFactory {
throws BadShapeException {

public Shape getShape(int shapeTypeId){

Shape shape = null;

if(shapeTypeId == Const.SHAPE_HEXAGON) {
               shape = new Hexagon();//complex shape
}
else throw new BadShapeException(“shapeTypeId=” + shapeTypeId);
              return shape;
}
}


Now let’s look at the abstract factory, which returns one of the types of ShapeFactory:

public class ShapeFactoryType throws BadShapeFactoryException {

public static final int TYPE_SIMPLE = 1;
public static final int TYPE_COMPLEX = 2;


public ShapeFactory getShapeFactory(int type) {

            ShapeFactory sf = null;
                  if(type == TYPE_SIMPLE) {
                           sf = new SimpleShapeFactory();
                       }
                  else if (type == TYPE_COMPLEX) {
                          sf = new ComplexShapeFactory();
                        }
                  else throw new BadShapeFactoryException(“No factory!!”);

               return sf;
            }
}


Now let’s look at the calling code, which uses the factory:

ShapeFactoryType abFac = new ShapeFactoryType();
ShapeFactory factory = null;
Shape s = null;
//returns a ShapeFactory but whether it is a SimpleShapeFactory or a ComplexShapeFactory is not known to the caller.
factory = abFac.getShapeFactory(1);//returns SimpleShapeFactory
//returns a Shape but whether it is a Circle or a Pentagon is not known to the caller.
s = factory.getShape(2); //returns square.
s.draw(); //draws a square
//returns a ShapeFactory but whether it is a SimpleShapeFactory or a ComplexShapeFactory is not known to the caller.
factory = abFac.getShapeFactory(2);
//returns a Shape but whether it is a Circle or a Pentagon is not known to the caller.
s = factory.getShape(3); //returns a pentagon.
s.draw(); //draws a pentagon


Why use factory pattern or abstract factory pattern?

Factory pattern returns an instance of several (product hierarchy) subclasses (like Circle, Square etc), but the calling code is unaware of the actual implementation class.

The calling code invokes the method on the interface (for example Shape) and using polymorphism the correct draw() method gets invoked . So, as you can see, the factory pattern reduces the coupling or the dependencies between the calling code and called objects like Circle, Square etc. This is a very powerful and common feature in many frameworks. You do not have to create a new Circle or a new Square on each invocation as shown in the sample code, which is for the purpose of illustration and simplicity. In future, to conserve memory you can decide to cache objects or reuse objects in your factory with no changes required to your calling code. You can also load objects in your factory based on attribute(s) read from an external properties file or some other condition. Another benefit going for the factory is that unlike calling constructors directly, factory patterns have more meaningful names like getShape(…), getInstance(…) etc, which may make calling code more clear.



Can we use the singleton pattern within our factory pattern code?

 Yes. Another important aspect to consider when writing your factory class is that, it does not make sense to create a new factory object for each invocation as it is shown in the sample code, which is just fine for the illustration purpose.

ShapeFactory factory = new SimpleShapeFactory();

To overcome this, you can incorporate the singleton design pattern into your factory pattern code. The singleton design pattern will create only a single instance of your SimpleShapeFactory class. Since an abstract factory pattern is unlike factory pattern, where you need to have an instance for each of the two factories (i.e. SimpleShapeFactory and ComplexShapeFactory) returned, you can still incorporate the singleton pattern as an access point and have an instance of a HashMap, store your instances of both factories. Now your calling method uses a static method to get the same instance of your factory, hence conserving memory and promoting object

reuse:
ShapeFactory factory = ShapeFactory. Ge/tFactoryInstance();
factory.getShape();