YouTip LogoYouTip

Factory Pattern

# Factory Pattern The Factory Pattern is one of the most commonly used design patterns in Java. It provides a way to create objects, separating the process of object creation from the process of using the object. The Factory Pattern provides a way to create objects without specifying the exact class of object that will be created. By using the Factory Pattern, the logic for creating objects can be encapsulated within a factory class, rather than instantiating objects directly in the client code. This improves the maintainability and scalability of the code. ### Types of Factory Pattern **1. Simple Factory Pattern**: * The Simple Factory Pattern is not a formal design pattern, but it is the foundation of the Factory Pattern. It uses a single factory class to create different objects, deciding which type of object to create based on the parameters passed in. **2. Factory Method Pattern**: * The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. The Factory Method lets a class defer instantiation to subclasses. **3. Abstract Factory Pattern**: * The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. * * * ## Overview ### Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory Pattern lets a class defer instantiation to subclasses. ### Problem Solved The problem of interface selection. ### When to Use When we need to create different instances under different conditions. ### Solution By letting subclasses implement the factory interface, returning an abstract product. ### Key Code The object creation process is implemented in the subclass. ### Application Examples 1. **Automobile Manufacturing**: You need a car, you just pick it up from the factory, without needing to care about the manufacturing process and its internal implementation. 2. **Hibernate**: When switching databases, you only need to change the Dialect and Driver to switch between different databases. ### Advantages 1. The caller only needs to know the name of the object to create it. 2. High scalability. If a new product needs to be added, only a new factory class needs to be extended. 3. Shields the specific implementation of the product. The caller only cares about the product's interface. ### Disadvantages Every time a new product is added, a new concrete class and corresponding factory need to be added, doubling the number of classes in the system, increasing system complexity and dependency on concrete classes. ### Use Cases 1. **Logging**: Logs might be recorded to the local hard disk, system events, remote servers, etc. Users can choose where to record the logs. 2. **Database Access**: When the user does not know which database the final system will use, or when the database might change. 3. **Server Connection Framework Design**: Need to support "POP3", "IMAP", "HTTP" three protocols. These three protocols can be treated as product classes, all implementing a common interface. ### Considerations The Factory Pattern is suitable for scenarios involving the creation of complex objects. If the object is relatively simple and can be created using `new`, there is no need to use the Factory Pattern. Using the Factory Pattern introduces a factory class, increasing system complexity. ### Structure The Factory Pattern contains the following main roles: * **Abstract Product**: Defines the common interface or abstract class for the product. It can be the parent class or interface of the concrete product classes, specifying the common methods for product objects. * **Concrete Product**: Implements the abstract product interface, defining the specific behavior and attributes of the concrete product. * **Abstract Factory**: Declares the abstract method for creating products. It can be an interface or an abstract class. It can have multiple methods for creating different types of products. * **Concrete Factory**: Implements the abstract factory interface, responsible for actually creating the objects of the concrete products. ## Implementation We will create a _Shape_ interface and concrete classes implementing the _Shape_ interface. The next step is to define a factory class _ShapeFactory_. The _FactoryPatternDemo_ class uses _ShapeFactory_ to get _Shape_ objects. It will pass information (_CIRCLE / RECTANGLE / SQUARE_) to _ShapeFactory_ to get the type of object it needs. ![Image 2: UML Diagram of Factory Pattern](#) ### Step 1 Create an interface: ## Shape.java public interface Shape{void draw(); } ### Step 2 Create concrete classes implementing the interface. ## Rectangle.java public class Rectangle implements Shape{ @Override public void draw(){System.out.println("Inside Rectangle::draw() method."); }} ## Square.java public class Square implements Shape{ @Override public void draw(){System.out.println("Inside Square::draw() method."); }} ## Circle.java public class Circle implements Shape{ @Override public void draw(){System.out.println("Inside Circle::draw() method."); }} ### Step 3 Create a factory to generate objects of given information. ## ShapeFactory.java public class ShapeFactory{//use getShape method to get object of shape type 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; }} ### Step 4 Use the factory to get objects of type by passing type information. ## FactoryPatternDemo.java 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 Square shape3.draw(); }} ### Step 5 Execute the program, outputting the result: Inside Circle::draw() method.Inside Rectangle::draw() method.Inside Square::draw() method. ### Other Related Articles >
← Abstract Factory PatternDesign Pattern Intro β†’