Factory
Patterns
It is one of the most commonly used design pattern, it comes
under creational patterns where we will create objects while hiding the
internal logic.
In such type of designs we will create a separate class
/factory to generate objects of concrete class based on supplied details
Let us suppose we need to create a design for Robot industries.
We have a contract to design a software for XYZRobot ltd , As per
the initial requirements these people want us to design robots which must be
different in design and appearance.
Based on such initial requirement we came up with a design
prototype taking three types of designs into consideration
1) RobotsLikeHuman
2) RobotsLikeAnimal
3) RobotsLikeMachine
Here in this design
- We are going to create a Robot interface and concrete classes(RobotsLikeHuman,RobotsLikeAnimal,RobotsLikeMachine) will implement this interface.
- We will create a factory class which will generate objects known to be as RobotFactory.
- We will create RobotPrototype class which will use RobotFactory class to get a Robot object based on its type as needed.
XYZRobot.ltd Design
Example:
/*
@author -- shashank
*/
package robotprototype;
interface Robot
{
public void
design();
}
class RobotLikeHuman implements Robot
{
public void
design()
{
System.out.println("I am a Human");
}
}
class RobotLikeAnimal implements Robot
{
public void
design()
{
System.out.println("I am an Animal");
}
}
class RobotLikeMachine implements Robot
{
public void
design()
{
System.out.println("I am a Machine");
}
}
class Robotfactory
{
public Robot getdesign(String
designtype)
{
if(designtype=="HUMAN")
{
return new
RobotLikeHuman();
}
else
if(designtype=="MACHINE")
{
return new
RobotLikeMachine();
}
else if(designtype=="ANIMAL")
{
return new
RobotLikeAnimal();
}
return null;
}
}
public class RobotPrototype {
/**
* @param args the
command line arguments
*/
public static void
main(String[] args) {
Robotfactory
rf = new Robotfactory();
Robot r =
rf.getdesign("HUMAN");
r.design();
Robot ra =
rf.getdesign("ANIMAL");
ra.design();
Robot rm =
rf.getdesign("MACHINE");
rm.design();
// TODO code
application logic here
}
}

No comments:
Post a Comment