








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









public interface Shape { void draw(); }
public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of circle shape3.draw(); } }
Let’s see some of the sub-classes of cake.
Now we are all set to create different types of cakes.
Notice the code in CakeTest class, we have got several concrete classes BlackForest, BlueBerry, LitchiGateaux, Pineapple being instantiated, and the decision of which class to instantiate is made at run-time depending on the user’s choice. When you see code like the above and when the time comes for changes or extension, you will have to reopen the code and examine what needs to be added or deleted. Suppose I don’t want to offer pineapple cake, I have to reopen the code and delete some codes. Similarly, if later I decide to add 10 new cake types, I have to reopen the code and type 10 more “else if” statements. Which means your code is not “closed for modifications”. Note : Your design should always be “open for extension” but “closed for modifications”. The code in the CakeTest will certainly vary as we decide to delete some cake type or add new cake types.
Now, let’s see how our CakeTest class is going to change.
By separating the cake creation code in a separate factory class, we get following benefits: