Java Design Patterns Part1
Java Design Patterns Part1
Singleton Pattern
Definition: Ensures only one instance of a class is created and provides a global point of access to
it.
Analogy: Imagine a print spooler - your computer must have one and only one print manager to
Code Example:
class PrinterSpooler {
private static PrinterSpooler instance = new PrinterSpooler();
private PrinterSpooler() {
System.out.println("Spooler Initialized.");
}
public static PrinterSpooler getInstance() {
return instance;
}
public void print(String doc) {
System.out.println("Printing: " + doc);
}
}
Analogy: Think of a pizza store. You order a pizza, and the store decides whether to give you a Veg
or a Non-Veg pizza.
Code Example:
interface Pizza {
void prepare();
}
class PizzaFactory {
public Pizza getPizza(String type) {
if (type.equalsIgnoreCase("veg")) return new VegPizza();
else if (type.equalsIgnoreCase("chicken")) return new ChickenPizza();
return null;
}
}
When to Use: When object creation logic needs to be hidden from the client.