CS2030 AY19/20 Semester 2
  • Introduction
  • Textbook Contributions
  • Peer Learning Tasks
  • Piazza Participation
  • Setting Up Lab Environment
  • Setting Up Java
  • Setting Up Vim
  • Setting Up MacVim
  • Setting Up Sunfire and PE Nodes
  • Setting Up Checkstyle
  • Textbook
  • CS2030 Java Style Guide
  • CS2030 Javadoc Specification
  • JDK 11 Download Link
  • Codecrunch
  • Github Repo
  • Piazza Forum

  • Factory Methods


    Edit the material here!

    Definition of Factory Method:

    "The Factory Method pattern is a design pattern used to define a runtime interface for creating an object. It's called a factory because it creates various types of objects without necessarily knowing what kind of object it creates or how to create it."

    Application in lecture notes:

    The method createCircle was used to check the validity of the input parameters and prevent the creation of invalid objects.

    static Circle createCircle(Point centre, double radius){
    if (radius > 0)
    return new Circle(centre, radius);
    else
    return null;
    }

    Note: Factory methods is static.

    Static methods belongs to a class instead of an instance of the class.

    Static methods is a form of encapsulate object creation.

    According to my understanding, factory method is defined as static so that it can be called without the need of creating an instance.

    Advantages of Factory Methods:

    1. Constructors cannot be named, while readable names can be assigned to factory methods.
    2. Constructors can only return same type as the class name, however, factory methods can return other objects.
    3. Factory methods promote the idea of using interface instead of implementation, and would generate more flexible codes.
    4. Unlike constructors, factory methods doesn't require a new object to be created everytime they are called.
      • Instantiate a static object as a default value, say an empty box
      • private static final BOX EMPTY_BOX = new BOX();
      • Factory method just has to return this specific instance of empty box whenever required instead of creating tons of new empty boxes
        public static Box empty() {
        return EMPTY_BOX;
        }
    5. Examples of factory methods in JDK are as such:
      • The String class
      • The Optional class
      • The Collections class

    Please feel free to edit if I have made any mistakes or add on more content.😄