Idiotechie.com solve design problems using factory pattern

  • 413 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
413
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
4
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Solve design problems using Factory Patternhttp://idiotechie.com/?p=480 July 12, 2012Factory design pattern is one of the most commonly used patterns in objectoriented environment. It is again from the Creational Design pattern category i.e. allabout object creation.There are certain cases where the object creation is complex and might require somelevel of abstraction so that the client code is unaware of these complexities and ie. cominternal implementation details. There might be scenarios where object creation isscattered and repetitive in various parts of the code.The Factory pattern resolves these issues by echdefining an interface which specifically creates the object but gives the flexibility to the implementation otclasses to decide on which class to instantiate. :// idi tttopdefine an interface for creating objects but Definition: h The Factory method pattern is © delegates the object creation to the subclasses.Objective:Looking at the problem statement the objective should be: Client should be unaware of the object instantiation Client should access the objects through a common interface. Do you know? Factory method design pattern is commonly used in various frameworks such as Struts, Spring, Apache in conjunction with decorator design pattern. There are various J2EE patterns which are based on this Factory pattern e.g. DAO pattern.Which principle of Object Oriented Design is used in Factory pattern?Encapsulation : because it encapsulates the creation code from the client. And obviously you can thenthink that the benefits of encapsulation are also applicable for this pattern like loose coupling andcohesion.Practical Example:Consider a Garment Factory which produces various types of garments like shirt, trousers. Theconsumers can request for the required types of garments through the factory. However fromconsumer’s perspective they are completely unaware of who is creating this object. They just know thatthe Factory is providing them the required garments.Problem Statement:It is a standard practice that objects are created by calling the “new” keyword. Imagine a scenario thatthere are multiple cases in the client class and we call multiple new keywords for creating new objects.if (selection.equalsIgnoreCase("Trouser")) {
  • 2. return new Trouser(); } else if (selection.equalsIgnoreCase("Shirt")) { return new Shirt(); }If we now have to add jacket or sweater we have to keep on modifying the client code and further addthe new keyword. This creates a dependency on the client code and in turn makes it difficult tomaintain.Another problem is that the client application has to know how many types of concrete classes are comavailable upfront. Later if we have to add another concrete class e.g. sweater or jacket then client codehas to be changed and recompiled. ie. echSolution: otTo resolve above problems factory pattern can be used explicitly. idi The first problem of accessing too many new keyword can be resolved by using a Factory class. :// h ttp The second problem can be solved by using an interface which the concrete classes will implement and the client will always point to the interface class rather than the concrete classes. © So in this way client will be completely unaware of various types of concrete classes which will be required. What is an interface? An Interfacein Java is a collection of method definitions without implementation. The class which implements the interface has to provides the implementation and must implement all the methods described in the interface. The interface is a contract which tells the classes what to be done leaves it for the classes to decide on how they can be implemented. interface Bounceable { void setBounce(); }The below class diagram will give a complete overview of implementation of Factory Pattern:Let’s take a look at the sample code to implement
  • 3. Let’s take a look at the sample code to implementthe Factory Pattern: GarmentType.java public interface GarmentType { String print(); } ie. com ot ech :// idi Factory Pattern Class Diagram Trouser.java h ttp © public class Trouser implements GarmentType { @Override public String print() { System.out.println("Trouser Created"); return "Trouser"; } } Shirt.java public class Shirt implements GarmentType { @Override public String print() { System.out.println("Shirt Created"); return "Shirt"; } } GarmentFactory.java public class GarmentFactory { public static GarmentType createGarments(String selection) { if (selection.equalsIgnoreCase("Trouser")) { return new Trouser(); } else if (selection.equalsIgnoreCase("Shirt")) { return new Shirt(); } throw new IllegalArgumentException("Selection doesnot exist"); } } Client.java
  • 4. public class Client { public static void main(String[] args) { System.out.println("Enter your selection:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String selection = null; try { selection = br.readLine(); } catch (IOException e) { e.printStackTrace(); com } GarmentType objGarmentType = ie. GarmentFactory.createGarments(selection); ech System.out.println(objGarmentType.print()); } } ot :// idiAdvantage of Factory Pattern: h ttpa)This client does not need to know about the subclass of objects which requires to be created. It ©requires the reference to the interface and the factory object.b)The object creation processes are taken away from the client to the factory and thereby decouplingthe client code with the object creation code. This in turn will help in reusability as this code can beused by other clients.c)The Factory pattern also helps in the scalability of the application as the client code only refers to theinterface and we can add more products implementing the interface without making many changes inthe client code.d)Code maintainability is a beneficial if the application uses Factory pattern as the object creation iscentralized.