Definition -
When you can abstract the functionalities and use that object to call other classes which implement the
Scenario -
Let us take an example of the production line itself, where the client places an order for a vehicle and depending on the order a hatchback or a sedan car is created.
In this case -
1. A abstract class called carmanufacture which have an execute funtion to process the request of the client.
2. There are two sub classes called hatchback and sedan which will extend the abstract class.
hatchback.java
sedan.java
3. To see the pattern in action use the following code -
Place to use -
1) When you want the client to decide on the sub class at run time.
2) When you can abstract a class and there is not too much deviation in the way the different sub classes work.
Place not to use -
1) Can easily over complicate design.
2) When there are too many changes and each change introduces few attributes / functionalities not used by others then it might result in change.
When you can abstract the functionalities and use that object to call other classes which implement the
Scenario -
Let us take an example of the production line itself, where the client places an order for a vehicle and depending on the order a hatchback or a sedan car is created.
In this case -
1. A abstract class called carmanufacture which have an execute funtion to process the request of the client.
package SimpleFactoryPattern;
public class hatchback extends carmanufacture{
@Override
public void manufacture() {
System.out.println("Manufacturing hatchback");
}
}
2. There are two sub classes called hatchback and sedan which will extend the abstract class.
hatchback.java
package SimpleFactoryPattern;
public class hatchback extends carmanufacture{
@Override
public void manufacture() {
System.out.println("Manufacturing hatchback");
}
}
sedan.java
package SimpleFactoryPattern;
public class sedan extends carmanufacture {
@Override
public void manufacture() {
System.out.println("Manufacturing sedan");
}
}
3. To see the pattern in action use the following code -
package SimpleFactoryPattern;
public class factorydemo {
public static void main(String args[]) {
carmanufacture car=null;
String order = "Hatchback";
if(order.equalsIgnoreCase("Hatchback")) {
car = new hatchback();
}
else if(order.equalsIgnoreCase("Sedan")) {
car=new sedan();
}
car.manufacture();
}
}
Place to use -
1) When you want the client to decide on the sub class at run time.
2) When you can abstract a class and there is not too much deviation in the way the different sub classes work.
Place not to use -
1) Can easily over complicate design.
2) When there are too many changes and each change introduces few attributes / functionalities not used by others then it might result in change.