CSCI 370 – Midterm Review Sheet

March 20 Lecture

Lecture Focus: Design Patterns - Factory and Singleton


1. Factory Design Pattern

Definition: The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. In simpler terms, it lets you delegate the instantiation logic to a separate component (the factory).

Problem It Solves:

Example from Lecture:

Initially, the user can instantiate any of these classes freely, which leads to potential misuse.

Bicycle b = new Tricycle(); // Anyone can do this

Refactor Using Factory:

public class BicycleFactory {
    public static Bicycle getNewBicycle(int age) {
        if (age < 6) return new Tricycle();
        else if (age < 19) return new TenSpeedBicycle();
        else return new Motorcycle();
    }
}

Benefit:


2. Singleton Design Pattern

Definition: The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it.

Why Not Use Regular Globals?

Illustration from Lecture:

public class Invoice {
    public int id;
}

Invoice i1 = new Invoice();
i1.id = 3;
Invoice i2 = new Invoice();
System.out.println(i2.id); // prints 0 (not what we want)

Better Approach:

public class Invoice {
    public static int globalId = 0;
    public int id;

    public Invoice() {
        id = ++globalId;
    }
}

Now, each new invoice automatically gets a new, incremented ID.

Problem with Static Global:

Singleton as a Solution:

Preview of Singleton Implementation (to be completed in next lecture):

public class IdGenerator {
    private static IdGenerator instance;
    private int currentId = 0;

    private IdGenerator() {} // private constructor

    public static IdGenerator getInstance() {
        if (instance == null) {
            instance = new IdGenerator();
        }
        return instance;
    }

    public int getNextId() {
        return ++currentId;
    }
}

Summary:


Best Practices from Lecture:


Next Lecture Preview:


Instructor’s Anecdotes:

“If you ever see globals, run away!”