Java Design Patterns - Factory Patterns

The factory mode belongs to the creation mode, there are three types: simple factory mode, method factory mode and abstract factory mode.

1. Simple Factory Mode

Definition:

Simple Factory Pattern, also known as Static FactoryMethod Pattern, is responsible for creating instances of other classes by specifically defining one class, and the created instances usually share a common parent class.

Scenarios applicable:

  • The factory class is responsible for creating fewer objects: because fewer objects are created, the business logic in the factory method is not too complex.
  • The client only knows the parameters passed into the factory class and does not care how the object is created: the client does not need to care about the creation details or even remember the class name; it only needs to know the parameters corresponding to the type.

UML Diagram:

Code:
Define an abstract class or interface as the base class, which takes the form of an interface

public interface Shape {
    public void create();
}

Then create three subclasses to implement this interface:

Circular:

public class Circle implements Shape {
    @Override
    public void create() {
        System.out.println("Create a circle");
    }
}

Rectangle:

public class Rectangle implements Shape {
    @Override
    public void create() {
        System.out.println("Create a rectangle");
    }
}

Square:

public class Square implements Shape {
    @Override
    public void create() {
        System.out.println("Create Square");
    }
}

Simple factory class:

public class SimpleFactory  {
    public static Shape createShape(String shapeName){
        Shape shape = null;
        if (shapeName.equals("rectangle")){
            shape = new Rectangle();
        }else if (shapeName.equals("square")){
            shape = new Square();
        }else if (shapeName.equals("circle")){
            shape = new Circle();
        }
        return shape;
    }
}

Test code:

public class Test {
    public static void main(String[] args) {
        Shape circle = SimpleFactory.createShape("circle");
        circle.create();

        Shape rectangle = SimpleFactory.createShape("rectangle");
        rectangle.create();

        Shape square = SimpleFactory.createShape("square");
        square.create();
    }
}

Print Output:

Create a circle
 Create a rectangle
 Create Square

Advantages and disadvantages:
Advantage:

  • Clients do not need to know the class name of the specific product class they are creating. They only need to know the parameters corresponding to the specific product class. For some complex class names, simple factory mode can reduce the user's memory.

Disadvantages:

  • Because the factory class centralizes all the product creation logic, once it does not work properly, the entire system is affected.
  • The simple factory mode uses a static factory method, which prevents the static method from being inherited
  • System expansion is difficult, once new products are added, factory logic has to be modified. When there are many types of products, factory logic may be too complex to facilitate system expansion and maintenance.

2. Factory Method Mode

Definition:
The factory method mode is a further abstraction and extension of the simple factory mode.Because of the use of object-oriented polymorphism, the factory method mode maintains the advantages of the simple factory mode and overcomes its disadvantages.In the factory method mode, the core factory class is no longer responsible for the creation of all products, but gives the specific creation work to the subclass to do.This core class is responsible only for giving the interfaces that a specific factory must implement, not for which product class is instantiated, which allows the factory method pattern to allow the system to import new products without modifying the factory role.
Scenarios applicable:

  • Delegate the task of creating objects to one of several factory subclasses, and the client can use them without having to care which factory subclass creates the product subclass.
  • Clients don't need to know the class name of a specific product class, they just need to know the factory. Specific product objects are created by a specific factory class. Clients need to know the factory class that created the specific product.

UML diagrams

Or take the above example of creating squares, rectangles, and circles, except that instead of using a simple factory class to create all shape instances, a factory interface is defined so that the subclass decides which class to instantiate.
Code:
The above Shape, Circle, Rectangle, Square classes all have the same code, and I don't paste them all.Seeing changes:
Factory Interface:

public interface MethodFactory {
    public Shape getShape();
}

Three implementation classes:
CircleFactory

public class CircleFactory implements MethodFactory {
    @Override
    public Shape getShape() {
        return new Circle();
    }
}

RectangleFactory

public class RectangleFactory implements MethodFactory {
    @Override
    public Shape getShape() {
        return new Rectangle();
    }
}

SquareFactory

public class SquareFactory implements MethodFactory{

    @Override
    public Shape getShape() {
        return new Square();
    }
}

Test code class:

public class Test {
    public static void main(String[] args) {
        //Create a circle
        MethodFactory methodFactory = new CircleFactory();
        Circle circle = (Circle) methodFactory.getShape();
        circle.create();

        //Create a rectangle
        MethodFactory methodFactory1 = new RectangleFactory();
        Rectangle rectangle = (Rectangle) methodFactory1.getShape();
        rectangle.create();

        //Create Square
        MethodFactory methodFactory2 = new SquareFactory();
        Square square = (Square) methodFactory2.getShape();
        square.create();

    }
}

Print Output:

Create a circle
 Create a rectangle
 Create Square

Advantages and disadvantages:
Advantage:

  • When new products are added to the system, there is no need to modify the interfaces provided by abstract factories and abstract products, nor to modify other specific factories and products, but to add a specific factory and product.In this way, the scalability of the system becomes very good, which fully conforms to the "open and close principle".

Disadvantages:

  • When you add a new product, you need to write a new specific product class, but also provide the corresponding specific factory class, the number of classes in the system will increase in pairs, to some extent, increase the complexity of the system, there are more classes to compile and run, which will bring some additional overhead to the system.
  • There is no relationship between products. If two different products need to be created, two different factory classes are needed, even if the two products have the necessary connection for a clock.

3. Abstract Factory Mode

Definition:
Above we know that the factory method pattern is specific to the factories that produce specific products, each of which is responsible for a specific product.But sometimes we need a factory class to provide multiple products instead of a single product object, which leads to the abstract factory model:
Abstract Factory Pattern: Provides an interface for creating a series of related or interdependent objects without specifying their specific classes.The abstract factory mode, also known as the Kit mode, is an object creation mode.

Scenarios applicable:

  • There are more than one family of products in the system, and only one of them is used at a time.
  • Generate programs for different operating systems.

UML Diagram:

Case:
For example, in the UML diagram above, if a user wants to buy a refrigerator for Haier and a long rainbow TV, we define two interfaces: Tv and Fridge, the implementation class for Long Rainbow TV and Haier TV under Tv, the implementation of Haier refrigerator and Long Rainbow refrigerator under Fridge, and HaierFactory for HaierTv and HaierFridge, which is responsible for Chang Hong Tv.And ChangHong Fridge are ChangHong Factory, which are implementation classes of AbstractFactory, an abstract class (interface).Top Code:

Tv

public interface Tv {
    public void watch();
}

Fridge

public interface Fridge {
    public void open();
}

ChangHongTv

public class ChanghongTv implements Tv {
    @Override
    public void watch() {
        System.out.println("Watch Long Rainbow TV");
    }
}

HaierTv

public class HaierTv implements Tv {
    @Override
    public void watch() {
        System.out.println("Watch Haier TV");
    }
}

ChanghongFridge

public class ChanghongFridge implements Fridge {
    @Override
    public void open() {
        System.out.println("Open Long Rainbow Refrigerator");
    }
}

HaierFridge

public class HaierFridge implements Fridge {
    @Override
    public void open() {
        System.out.println("Open Haier Refrigerator");
    }
}

AbstractFactory

public interface AbstractFactory {
    public Tv getTv();
    public Fridge getFridge();
}

ChanghongFactory

public class ChanghongFactory implements AbstractFactory{
    @Override
    public Tv getTv() {
        return new ChanghongTv();
    }

    @Override
    public Fridge getFridge() {
        return new ChanghongFridge();
    }
}

HaierFactory

public class HaierFactory implements AbstractFactory{

    @Override
    public Tv getTv() {
        return new HaierTv();
    }

    @Override
    public Fridge getFridge() {
        return new HaierFridge();
    }
}

Test class:

public class Test {

    public static void main(String[] args) {
        AbstractFactory factory = new ChanghongFactory();
        ChanghongTv changhongTv = (ChanghongTv) factory.getTv();
        changhongTv.watch();

        AbstractFactory factory1 = new HaierFactory();
        HaierFridge haierFridge = (HaierFridge) factory1.getFridge();
        haierFridge.open();

    }
}

Print Output:

Watch Long Rainbow TV
 Open Haier Refrigerator

Advantages and disadvantages:

Benefits: When multiple objects in a product family are designed to work together, it ensures that clients always use only objects in the same product family

Disadvantages: When adding new product objects, it is difficult to expand Abstract factories to produce new types of products

4. Summary

Significance of factory mode: extracting code from instantiated objects and putting them into a class for unified management and maintenance to decouple dependencies from the main project, thereby improving project scalability and maintainability

Three ways of factory mode: simple factory mode, factory method mode, abstract factory mode

Be careful:

  • When creating an instance object, instead of directly new ing the instance class, place this action in a factory method and return it
  • Do not let classes integrate specific classes, but inherit abstract classes or interfaces
  • Do not override methods already implemented in base classes
Published 8 original articles, received 7 reviews, and received 394 visits
Private letter follow

Posted on Fri, 13 Mar 2020 18:07:02 -0700 by kaushikgotecha