Tuesday, July 17, 2012

Behavioral Patterns - 4.Iterator Pattern

Nowadays, most of the applications we are developing are dealing with a huge set of data. These sets of data are termed as collections. A collection is nothing but a group of data.
In order to deal with such type of collections we need some mechanism to traverse over the list. Such mechanism can be termed as an Iterator. They are particularly meant for dealing with a set of data.

An Iterator Design pattern provides a design for an iterator to traverse over and deal with a collection of data.
The iterator should provide methods such as first(),next(),previous(),last(),etc in order to fetch the desired data from the collection.This will ease the process of accessing collection data.

For example, we are going to prepare a Name list for students in a class. This list will be our collection.

We are going to use the Student List for MarkSheet preparation. We need an iterator which can sort and iterate the Student Names alphabetically. One more iterator we need, to sort and traverse the list based on the marks.

Here, we have one collection of Student List for which we need two iterators i.e.StudentNameIterator and MarkListIterator.

Let us design our class as mentioned below,


Code Snippet:--------------
Client:

StudentList studentList=new StudentMarkList();
studentList.add(new Student(...));
...
StudentIterator iterator=studentList.createIterator();
iterator.sort();
iterator.next();
iterator.previous();

Monday, June 4, 2012

Behavioral Patterns - 3.Interpreter Pattern

In our day to day coding and development activities, situations may arise where we may need to evaluate/process a sentence or a group of strings in different ways.

A natural language parser could be an example for the above scenario. Such problems, can be handled with the help of Interpreter Pattern.

Generally, we define a Context which contains the sentence that needs to be interpreted. Then we define some interpreters to operate over the context and updates the context with the interpreted result.

There will be an abstraction over the interpreters.Seperate implementations can be written for their own interpretation needs.

For example, we are going to design some encryption algorithms. First of all, we need to define a Context, which contains the string or sentence that needs to be encrypted.

After that, we define an abstraction for the encryption algorithm. Then we define separate implementations for the algorithm that will work over the context and updates it with the encrypted string.

Being built with the Interpreter pattern,it will be a very simple task to change or add an algorithm to the stack with very minimal changes to the code.

Following diagram explains the Interpreter pattern,



Code snippet

Client:

  Context context=new Context(name); //Define the Context
  Cryptography cryptography=new MyCryptography();
  cryptography.interpret(context); 
//Invoke the Interpreter over the context
 
  cryptography=new CustomCryptography(); //Changing algorithm
  cryptography.interpret(context);


Interpretor(Abstraction):

abstract class Cryptography{
 public abstract void interpret(Context context);
//Interpreter method
}


Implementation(Cryptography Algorithm):

 @Override
 public void interpret(Context context) { 
//Interpreter Implementation
  char names[]=context.getName().toCharArray();
  int count=0;
  for(char name:names){
   names[count++]=(char)((int)name+2);
  }
  context.setResult(new String(names));
//Update the Context with result
 }

Sunday, June 3, 2012

Behavioral Patterns - 2.Command Pattern

There could be a need of a programming model which would associate some workflow or operations to an object.

 So that, the task of performing the operation/workflow is delegated to the object.

They can be triggered by a request, wrapped by an external object. We term those objects as Command Objects.

Following are the terminologies most frequently used in Command pattern.

Invoker:- Triggers a command on an object
Receiver:- Receives a request to execute a command.
Client:- Initializes the command and gets the work done.


The workflow that will happen during the executing of a command as follows,
1. Client will initialize and prepare a command with a receiver.
2. Client will initialize the invoker with the command prepared.
3. Client requests the invoker to execute a command
4. Invoker triggers the command
5. The command indentifies the receiver and fires the request over it


For example, we consider a Student/Teacher scenario in a particular class.
The teacher will command the students to either stand/sit. The students will act accordingly to the command issued by the teacher.

Here, Student is the Receiver Object, teacher is an Invoker and Stand/Sit will be a Command object.

The client will prepare the receiver(Student) and associate the command(stand/sit).Then, the invoker(Teacher) will be initialized with the same command(stand/sit) object.

After that, the client requests the invoker(Teacher) to execute the command(Stand/sit). The invoker(Teacher) triggers the command(Stand/Sit). The command identifies the receiver(Student) and gets executed.

The following class diagram explains the above description,


Code Snippet:

Client:

Student student=new Student();
Command standCommand=new Stand(student);
  //Associate the Receiver to the command
Command sitCommand=new Sit(student); //Associate the Receiver to the command


Teacher teacher=new Teacher(standCommand,sitCommand); //Initialize the Invoker with the command

teacher.sitDown(); //Request the Invoker to trigger the Command
teacher.standUp(); //Request the Invoker to trigger the Command

Invoker:

public Teacher(Command standCommand, Command sitCommand) { //Initialize the Invoker with the command
  this.standCommand = standCommand;
  this.sitCommand = sitCommand;
 }


public String standUp(){
  return standCommand.execute();
//Trigger the Command
 }

 public String sitDown(){
  return sitCommand.execute();
//Trigger the Command
 }

Command:

class Sit implements Command{
 private Student student;  
// Command with the Receiver
...
}

public String execute() {
  return student.sit(); //Command Execution
 }

Wednesday, May 30, 2012

Behavioral Patterns - 1.Chain of Responsibility

At times we may need to deal with different objects performing different tasks based on a defined workflow. There may be a need for delegation and processing the tasks between various objects.

Such kind of problems can be solved by the "Chain of Responsibility" pattern.

Consider a situtation where we may need to handle the bank loan approval process.A bank may have approving authorties at various levels like Manager,Director,President,etc.

The approval limit may vary across the levels. For Example, a Manager has a maximum approval limit of Rs.10,000, for a Director it will be RS.50,000 and for a President it will be more than RS.50,000.

Whenever a Manager receives a request for approving Rs.1,00,000, he/she will delegate the request to their immediate predecessor. Here it will be delegated to the Director. Since, the requested approval amount exceeds the Directors limit, it will be furthur delegated to the President. The President can approve the amount.

Here, the responsibility of approval is being delegated to various persons based on their nature. This can be termed as "Chain Of Responsibility".

Please refer the below class diagram for more details on this pattern,



Following code snippet can provide a clear idea over the implementation,

 public void approve(double amount) {
  System.out.println("Manager checking the limits");
  if(amount<=10000)
      System.out.println("Approved!");
  else{
     System.out.println("Approval Limit Exceeds! Delegating to "+predecessor);
     predecessor.approve(amount); //Delegating the responsibility to the predecessor
  }


Code snippet for the client could be,
 
  Approver president=new President(null);
  Approver director=new Director(president);
  Approver manager=new Manager(director);
  manager.approve(200000);

Monday, May 28, 2012

Structural Patterns - 7.Proxy Pattern

Proxy pattern filters and customizes the data you want from the main big subject. Assume, we have a subject with nearly 200 properties into it. But frequently we may need 10 or 20 of them.

So, we will end-up in creating a proxy for the subject by filtering the 10 or 20 properties alone from the main subject.

Whenever we need those properties we may access the proxy instead of the main subject.

This will help us to get way from creating costly objects and business calls.

For example, Student will be our subject which contains data like attendance, marks, age,etc. But we may not interest in all the data except the attendance information. Instead of using the entire Student object, we will create a Proxy to the Student which provides the attendance details alone.

Proxy can add more functionalties before or after getting the attendance details from the Student Object.

Following diagram explains this pattern a bit more,


We can use the proxy object whenever we need to process the attendance for the student.
This proxy will internally communicate with the Student object with a singleton pattern.

Proxy Code snippet in Client:

  Student abc=new ProxyStudent();
  Student def=new ProxyStudent(); //Create Proxies for Student


In the Proxy Class,

public String getAttendance() {
  if(realStudent==null){  //Ensure singleton object for the Subject
   realStudent=new RealStudent();
  }
  return realStudent.getAttendance();
 }


 

Thursday, May 17, 2012

Structural Patterns - 6.FlyWeight Pattern

Have you ever imagined that you are standing in between a huge array of army in the battlefield? The army may consists of horses,elephants,chariots and big mass of soldiers.
Seeing such a scene itself brings a mammoth outlook before your eyes.


How about drafting a design to accomodate the army?

An army may contain thousands/lakhs of soldiers. Think about creating an object for each and every soldier. We have elephants,horses,chariots and soldiers on foot assembled in a disciplined structure with their positions.

How about designing an order of positions for this army?

At first sight, it really looks like a costly effort. Because, we will end up in creating lakhs/thousands of objects to represent the army.

A solution to this type of problems could be a Flyweight Pattern. It helps us to minimize the number of objects created by generalizing the common pattern observed
among them.


This pattern is a collaboration of Factory Method and Singleton design patterns.

Now, let us think a way to simplify the object structure by recognizing the patterns from the army. We can identify some classifications among the soldiers like elephants, horses, chariots and normal soldiers. But, we need to maintain position for each of them.

First, we generalize the soldiers based on their nature, which could be the intrinsic property.So, we will end up in creating just four objects(chariots, elephants, horses, soldiers).

Then, the position to which they need to occupy ,could be more dynamic and explicitly specified.

For example, let us consider we have 1000 soliders in an army.

It consists of 100 chariots, 200 Elephants, 200 Horses, 500 Soldiers and they were positioned in rows 4,3,2 and 1 respectively.

We construct 4 objects for the types of soldiers in an army and we dynamically initialize their position in the battlefield.

Following design explains this approach in a better way,



Soldier is the Flyweight object constructed using the SoldierFactory which is a Flyweight Factory. This flyweight object is a singleton for each and every soldier type.

After receiving the flyweight object client can decide where to position each and every soldier.

FlyweightFactory Code snippet,

private static HashMap<String,Soldier> soldiers=new HashMap<String,Soldier>();
 public static Soldier getSoldier(String type){
  Soldier soldier=soldiers.get(type);
  if(soldier==null){
   soldier=new Soldier(type);
   soldiers.put(type, soldier);
  }
  return soldier;
 }


Client code,

   Soldier soldier;
   for(int i=1;i<=1000;i++){
   if(i<=100){
    soldier=SoldierFactory.getSoldier("Chariot");
    soldier.setPosition(4);
   }
   else if(i<=300){
    soldier=SoldierFactory.getSoldier("Elephant");
    soldier.setPosition(3);
   }
   else if(i<=500){
    soldier=SoldierFactory.getSoldier("Horse");
    soldier.setPosition(2);
   }
   else{
    soldier=SoldierFactory.getSoldier("Soldier");
    soldier.setPosition(1);
   }  


This will result in creating just 4 objects and configure them 1000 times with their position.

Monday, May 14, 2012

Structural Patterns - 5.Facade Pattern

Facade is an exterior view/face of a building. We can understand the whole structure of the building by its exterior view.

But internally, they have lot of rooms, wiring, plumbing, interior decorations,etc., which we may not interested to know.

Day to day we deal with complex business functionalities. We seperate our business requirements into different classes and maintain the inter-operability between them.

We should be able to re-use such components within our application or from an external application whenever there is a need.

Our component may have a complex design with many business processings but we need to provide a simpler interface for other systems to use it. Such type of an interface is a Facade.
A railway reservation system is a complex process involving hundreds of rules or policies while booking a ticket. They have seperate systems to handle the list of stations,trains,quotas,preferences,etc.

We may not have much interest over the internal happenings of the system. We will end up in providing the details about the passenger and the seat preference.

The system will perform the complex processing and generate the ticket for us based on the data provided.


The following class diagram explains the Facade pattern,



Here, the Ticket class offers a simple method bookTicket() which is the facade for the complex ticket reservation process.

 A single call to the bookTicket() will communicate with different systems like stations, preferences, ticket classes, quotas, etc., and generates the ticket for the passenger.

Refer the following code snippet for more details,

// Constructor 

  public Ticket() {
     stations=new Stations();
     train=new Train();
     quota=new Quota();
     preference=new Preference();
 }


// Facade for booking the ticket

public void bookTicket(){
 ticket.setClass(train.getTravelClass());
 ticket.setFromStation(stations.getFrom());
 ticket.setToStation(stations.getTo());
 ticket.setPreference(preference.getPreference());
 ticket.setQuota(quota.getQuota());
 ticket.generate();
}

Thursday, May 3, 2012

Structural Patterns - 4.Decorator Pattern

If we want to add new behaviors to our object during runtime, we can choose Decorator Pattern. In this pattern, we define a class and some set of behaviors applicable to the class separately.

We can patch up the behaviors to the class dynamically with out altering the class implementation.

In other words, the object can be decorated dynamically with various behaviors as per the need. Here,both the decorator and the object to be decorated belong, to the same abstract type.

Consider an example of creating a rainbow. By default, rainbow is having a single color as its behavior. We can add or remove colors to/from the rainbow dynamically.Hence, the rainbow object can be constructed and the colors can be added/removed on the fly.

Rainbow is an implementation of the abstract type Colors. We implement separate decorators for each and every color so that both rainbow and all other decorators belong to the same type, Colors.

Following class diagram will explain the concept in detail,

Here, we can add any new decorator or repeat the existing decorator without altering the Rainbow code.

Based on the above diagram the following code snippet shows the decorator pattern in action,

  Colors rainbow = new Rainbow();
  rainbow = new IndigoDecorator(rainbow); //Decorator 1 (Indigo)
  rainbow = new VioletDecorator(rainbow); // Decorator 2 (Indigo)


Similarly, we can add dynamic behaviors to the rainbow object as,  

  rainbow=new AnyColorDecorator(rainbow);  //Decorator N (Any Color)

we can also, decorate the rainbow class with the same color, repeated for any number of times.


In the Java API, InputStreams, Readers,etc are having decorator implementations.

Thursday, April 26, 2012

Structural Patterns - 3.Composite Pattern

The Composite Pattern is a very simple pattern to represent a complex structure of data. Whenever in an application, if we need to design a tree structure with leaf and nodes then this pattern could be a right candidate.

This pattern treats both the nodes and the leaves in the same way as they are the parts of the same tree.A parent-child hierarchy of many levels is a complex task to handle through the code. A child can have many children so that it will become a parent by itself.

Some children may not become a parent as they may not have any children on their own. This type of relationship can be gone to the depth of any level (ex:-parent/child generations together).

Having a design to maintain or accomodate such complex structure is a hard task. Thanks to Composite pattern which makes our life easy in the above scenario.Let us consider the below class diagram explaining the Composite Pattern,


Here, we have a generic Human Interface having two implementations
a) Child
b) Parent


The child class would be a leaf node which won't have any furthur nodes attached to it whereas a parent class is composed of a list of nodes of type Human.

Again those nodes may be either parent or child. This pattern appears recursively so that we can handle theparent and child objects to any number of generations.

Find below the structure of sample data which operates over the composite pattern,



Following code snippet will explain the above mentioned structure,
 public static void main(String[] args) {
 
  Parent one=new Parent("Gen1Parent");
  Human two=new Child("Gen2Child");
  Parent three=new Parent("Gen2Parent");
  Parent four=new Parent("Gen3Parent");
  Human five=new Child("Gen3Child");
  three.add(five);
  three.add(four);
  one.add(three);
  one.add(two);


  printItems(one); //Method to print all the values from the Tree
 
 }
 

Following code snippet will show how to iterate over the list of values in order to fetch the nodes and their leaves,

 public static void printItems(Parent parent){
         System.out.println(parent.getName());
  for(Human human:parent.getChildren()){
   if(human.getType().equals("Parent")){
   
    printItems((Parent)human);
   }else{
    System.out.println(human.getName());
   }
  }
 }

Tuesday, April 24, 2012

Structural Patterns - 2.Bridge Pattern

There are scenarios where we may need to deal with different combinations of abstractions and their implementations.

Bridge pattern helps us to seperate/decouple the abstraction and its implementation. We can use composition in order to associate an abstraction to a particular implementation. This will help us to design an extensible application.

Here, the abstractions and implementations where nowhere related to each other.

For example, We are having some abstractions of Pen like fountain pen, ball point pen,etc. As an implementation we can have some documents or contents like poem,essay,etc can be written out of a Pen.

Here, we compose Content to the Pen class so that we can use any type of pen to draft any type of content. The following class diagram explains this pattern,







Code to associate an abstraction to an implementation dynamically,


  Pen[] pens=new Pen[]{new BallPointPen(new Essay()),
                                                                 new FountainPen(new Poem())};
  for(Pen pen:pens){  
         System.out.println(pen.write());
  }

In the above code snippet, we dynamically associate the Essay and Poem instances to BallPointPen and FountainPen instances respectively.


In the BallPointPen/FountainPen class, we can handle this association as follows,


            public BallPointPen(Content content) {  
                      this.content=content;
            }
           @Override
           public String write() {  
                      return content.createContent()+" with BallPoint Pen";
           }

Thursday, April 19, 2012

Structural Patterns - 1.Adapter Pattern

So far, we discussed about the ways of creating an object and patterns involved during object creation.

Next we are going to see about the Structural patterns. They mostly deal with the way the classes or interfaces or represented or related. The influence of class structures on achieving a functionality will be widely discussed with a set of patterns.

Adapter Pattern

This is one among the most frequently used Design Patterns. The main benefit in going for the Adapter pattern, is to establish proper communication between two or more incompatible interfaces. In otherwords, adapter makes two different interfaces communicate each other.

There are two types of Adapters,
a) Class Adapters and
b) Object Adapters

Class Adapters

Consider, there are two different interfaces requires communication between each other. The Adapter class will inherit both the interfaces and overrides the implementation by custom code. Message from one interface will be taken and customized in such a way the other interface could process it.

A simple example of Class Adapters can be seen below,



In the above design, we want to transfer some data from a USB device to an HDMI device. So, we defined an Adapter class USBHDMIAdapter by inheriting both USBSource and HDMISource.

While writing the implementation for the method getHDMIData(), we internally fetch the USBData and perform customizations in order to make the data compatible with HDMI. Finally return the data back to the HDMI Source.

Sample code snippet for better understanding,

In the Adapter class we write our implementation for the getHDMIData() as follows,
public String getHDMIData() {
String hdmiData=getData().replace("USB", "HDMI");
return hdmiData;
}


and in the Client class we can invoke the Adapter as stated below,

USBSource usbSource=new USBSource();
usbSource.setData("USB Movie - 123");

HDMISource hdmiSource=new USBHDMIAdapter(usbSource);
System.out.println(hdmiSource.getHDMIData());


Object Adapters

They are very much similar to the Class Adapters but instead of generalization we use composition. We compose the USBSource object and write implementation for the HDMISource with our custom code.

Following design explains the Object Adapter pattern,



The source code for defining the Object Adapter may look as specified below,

class USBHDMIAdapter implements HDMISource{

private USBSource usbSource;

public USBHDMIAdapter(USBSource source) {
this.usbSource=source;
}

@Override
public String getHDMIData() {
String hdmiData=usbSource.getData().replace("USB", "HDMI");
return hdmiData;
}

}

Thursday, March 22, 2012

Creational Patterns - 5.Singleton Pattern

It's a costlier effort to create an object for the class as many times we need. There is a better way to handle such situations. We need to consider re-using the object once its got created.
Let us create an object and re-use it throughout the application wherever needed. Therefore, not more than a single instance of the class exists. This is called as a Singleton pattern.

In general, we create a self composed class with a closed constructor. So that, the instantiation can be customized with the help of a factory method.

Following class diagram shows a singleton class,




In the book class we made the constructor private and defined a static method getInstance().The object creation activity is delegated to the custom getInstance() method and the constructor is closed. As a result, we validate the object whether it already exists or not.
The getInstance() method will not create an instance if one already exists.

class Book{
private static Book book;
private Book() {
}
public static Book getInstance(){
if(null==book)
book=new Book(); // Lazy Initialization
return book;
}
}


The above sample is based on Lazy Initialization pattern.

One simpler way to create the same singleton class without Lazy Initialization is given below,



class Book{
private static final Book book=new Book();
private Book() {
}
public static Book getInstance(){
return book;
}
}



We have one more approach to achieve a perfect singleton with the help of enum types.
Since the data members of the enum types are always constants,the method calls will be happening over a singleton object.

Following design will explain the concept clearly.





Here, Book is a enum type having a constant INSTANCE which can act as a singleton.
Using the singleton object INSTANCE, we can invoke the method getPrice() from the enum Book.

Wednesday, March 14, 2012

Creational Patterns - 4.Prototype Pattern

Generally, object creation is a costlier task in an application development. Whenever creating an object, we need to be more keen on the way how it is being constructed. To optimize the object creation we may consider the creational patterns wherever applicable to our business need.

Consider a scenario, where we need to construct a set of objects belong to a similar kind but with small differences among them.

It would be a costlier operation to create all the individual objects using "new" for the above scenario.

For example,
We are creating a generic LayoutTemplate.Parts of a LayoutTemplate would consists of header,body and footer.
UI providers of various discipline can construct their own layouts using the generic layout template.
Think about a scenario where we need to construct a bunch of layouts like Web Layout, Desktop Layout, Android Layout,etc.,

Instead of creating seperate instances for each and every layout, we create a single layout object(Prototype) and customize it to generate other layouts. This will reduce the overhead of object creation for every layout type.

In order to achieve this, we have to make use of clone() method to our layout class. Clonning will be supported only over a cloneable object. For that, we need to implement the Cloneable interface and override the clone() method.

Note: clone() method should throw CloneNoteSupportedException.

Following class diagram will explain the prototype design pattern.




We can create a Generic Layout object as,

LayoutTemplate genericLayout=new ConcreteLayout("Text header", "Text Footer", "Text body");

This is the Prototype object for our layout creation. Using this,we can create other layouts as specified below.

LayoutTemplate webLayout=(LayoutTemplate)genericLayout.clone();
webLayout.setFooter("HTML Footer");
//Customize the clonned object as per the need

LayoutTemplate desktopLayout=(LayoutTemplate)genericLayout.clone();
desktopLayout.setHeader("JMenubar");
//Customize the clonned object as per the need

Monday, March 5, 2012

Creational Patterns - 3.Builder Pattern

When dealing with the construction of complex objects,there always should be a consideration of builder pattern. This pattern abstracts the construction steps for an object. Different builders can implement the steps on their own way.

There is one more component called Director takes care of driving the builder for constructing an object.

Example Use Case:-

This use case involves the process of constructing a house.

Construction steps for a house may contain the following things,


  • Flooring
  • Wall construction
  • Roofing
We are going to construct,

  1. CountryTiledHouse
  2. TerraceHouse
Both the above mentioned houses are having their own styles for flooring,wall,roof,etc.

Here, we are going to abstract the construction process of the floor,wall and roof.

So that, different types of houses can construct them as per their taste.

Following class diagram will clearly explain the design approach,




The flow of constructing a CountryTiledhouse can be specified as follows,
1) Initialize our builder,

HouseBuilder houseBuilder=new TileHouseBuilder();

2) Ask the director to use the builder,

BuildingDirector director=new BuildingDirector(houseBuilder);


3) Ask the director to build the house

director.buildHouse();

4) Request the house from the builder after being built based on the director's instructions

System.out.println(houseBuilder.getHouse().getFloor());

If we need a TerraceHouse, we just need to change the builder as follows,

HouseBuilder houseBuilder=new TerraceBuilder();

Thursday, February 16, 2012

Creational Patterns - 2.Abstract Factory

Abstract Factory will be the right choice, when you are dealing with different types of objects sharing some common features. We can, abstract those features and define seperate factory implementations for creating the objects.

In otherwords, this is a factory of factories.

Example Use Case:-

This will be an extension to the factory method use case.
Now, the ABC Company needs some variety of cars. They are in need of Sedan Cars and HatchBack Cars. Similarly, PQR and XYZ companies are also demanding the same.

How can we handle this ?

CarFactory factory=new ABCCarFactory();
factory.createCar();


This block of code would be fine for a normal requirement as discussed in factory method
use case. For this new requirement we need some thing like,

CarFactory factory=new ABCCarFactory();
factory.createSedanCar();
factory.createHatchBackCar();


In future, ABC company may ask for SUV cars. so, we need to think for a seam less modification to the design.
Now,we categorize the cars based on their types(Sedan,Hatchback,SUV,etc).Let the companies(ABC,PQR,etc) write their own implementation of the types.

The design looks as specified below,


We have seperate CarFactories for every company. ABCCarFactory deals with the sedan and hatchback cars of ABC Company only.

This will enable us to add new Factories for new companies without any modification to the existing behavior. Similarly, new vehicle types like SUV can also be introduced without much
effort.

Wednesday, February 15, 2012

Creational Patterns - 1.Factory Method

This is the simplest of all the GoF(Gang Of Four) Design patterns. It deals with the task of creating an object for a class. Instead of creating objects in our business classes, we are delegating the task to a Factory class. This will help us to maintain and manage the objects without affecting the business flow.

Example Use Case:-

Consider, we are in a process of creating a Car for ABC Company as mentioned below,
Car car=new Car();
car.createCar();

In future, companies like PQR,XYZ,etc may ask us to create cars for them.
So, we need to maintain the create() for each and every company in our Car class itself.

Car car=new Car();
car.createABCCar();
car.createPQRCar();
car.createXYZCar();


The above approach would create a tight dependency over the Car creation process.
We can solve this problem and create a loose dependency with the following design:-




When we create the cars based on the above design, it would be easier to accommodate any number of new companies for creating their cars. For providing cars to PQR, we need to create a PQRCar Class by inheriting Car and an implementation to the Factory for creating the PQRCar.
The business logic for creating a car would be something similar to,

CarFactory factory=new ABCCarFactory();
CarFactory factory=new PQRCarFactory();

Car car=factory.createCar();


Thus, the car creation logic will be handled by the CarFactory based on the instantiation
of the factory.

Design Patterns Simplified

This will be the first in the series of posts to explain Core Java Design Patterns with simple examples.
This series has been organized in three parts,
  1. Creational Patterns
  2. StructuralPatterns and
  3. Behavioral Patterns
Every Pattern will have an example Use Case and a design to drive it.