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()”.
1 | package com.sample.patterns; |
3 | public abstract class Vechicle |
6 | public abstract String ride(); |
Subclass – Car, BikeThe sub classes “Bike” and “Car” extends the abstract class “Vechicle” and each provides the implementation for the “ride()” method.
Car.java
1 | package com.sample.patterns; |
2 | public class Car extends Vechicle |
7 | return "Riding car is pleasant" ; |
Bike.java
01 | package com.sample.patterns; |
02 | public class Bike extends Vechicle |
08 | return "Riding bike is thrill" ; |
Factory class – FactoryVechicleThis class contains a static method named “getVechicleObject” which returns the subclass object based on the data provided.
01 | package com.sample.patterns; |
03 | public class FactoryVechicle |
05 | public static Vechicle getVechicleObject(String name) |
07 | if(name.equalsIgnoreCase( "Bike" )) |
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
01 | package com.sample.patterns; |
03 | public class FactoryTest |
05 | public static void main(String args[]) |
07 | Vechicle bike = FactoryVechicle.getVechicleObject( "Bike" ); |
08 | System.out.println(bike.ride()); |
09 | Vechicle car = FactoryVechicle.getVechicleObject( "Car" ); |
10 | System.out.println(car.ride()); |
The output of the preceding program will be displayed as the below,
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:
Post a Comment