Welcome to my blog, hope you enjoy reading
RSS

Friday 18 January 2013

Java – Factory Design Pattern

Java – Factory Design Pattern

Introduction
Factory pattern is used in the scenerio where the project contains a super class and ‘n’ number of sub-classes, In which the subclass object is created depending on the data provided. This article touches the basics of Factory Design Pattern using some sample codes that contains an abstract class named “Vechicle”, Two sub classes named “Car” and “Bike” and a factory class named “FactoryVechicle”.



Abstract class – VechicleThis abstract class acts as a super class which contains a method named “ride()”.
1package com.sample.patterns;
2
3public abstract class Vechicle
4
5{
6public abstract String ride();
7}
8}
Subclass – Car, BikeThe sub classes “Bike” and “Car” extends the abstract class “Vechicle” and each provides the implementation for the “ride()” method.
Car.java
1package com.sample.patterns;
2public class Car extends Vechicle
3{
4@Override
5public String ride()
6{
7return "Riding car is pleasant";
8}
9}
Bike.java
view surce

print
01package com.sample.patterns;
02public class Bike extends Vechicle
03{
04
05@Override
06public String ride()
07{
08return "Riding bike is thrill";
09}
10}
Factory class – FactoryVechicleThis class contains a static method named “getVechicleObject” which returns the subclass object based on the data provided.

01package com.sample.patterns;
02
03public class FactoryVechicle
04{
05public static Vechicle getVechicleObject(String name)
06{
07if(name.equalsIgnoreCase("Bike"))
08{
09return new Bike();
10}
11else
12{
13return new Car();
14}
15}
16}
Test Class – FactoryTestThis class is used to test the Factory design pattern by passing the arguments to the method “getVechicleObject” of the “FactoryVechicle” class.
FactoryTest.java
view source
01package com.sample.patterns;
02
03public class FactoryTest
04{
05public static void main(String args[])
06{
07Vechicle bike = FactoryVechicle.getVechicleObject("Bike");
08System.out.println(bike.ride());
09Vechicle car = FactoryVechicle.getVechicleObject("Car");
10System.out.println(car.ride());
11}
12}
The output of the preceding program will be displayed as the below,
1Riding bike is thrill
2Riding car is pleasant
Thats all folks, This article explains the basics of FactoryDesignPattern and if you find this article is useful to you, Dont forget to leave your valuable comments. Have a joyous code day.

0 comments: