Java Design Patterns
Java Design Patterns
Java Design Patterns
Singleton Pattern
Ensures that a class has only one instance and provides a global access point to it.
class Singleton {
private static Singleton instance;
private Singleton() {}
Provides an interface for creating objects, but allows subclasses to decide which class to
instantiate.
interface Shape {
void draw();
}
class ShapeFactory {
public static Shape getShape(String type) {
if (type.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (type.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}
interface Animal {
void makeSound();
}
class Car {
private String engine;
private int wheels;
Creates new objects by copying an existing object, reducing the overhead of creating
complex objects.
import java.util.HashMap;
import java.util.Map;
class PrototypeRegistry {
private static Map<String, Animal> registry = new HashMap<>();
static {
registry.put("Sheep", new Sheep());
}