Member-only story
7 Rare but Invaluable Java Patterns
Powerful but Overlooked Patterns in Java
Below are some less-common (or lesser-discussed) patterns in Java that can still be incredibly useful in the right contexts. These aren’t always given as much attention as the “Gang of Four” or widely known patterns (like Singleton, Factory, Strategy, etc.).
1. Null Object Pattern
The Null Object Pattern provides a non-operational or “do-nothing” object that can safely stand in for a null
reference. Instead of constantly checking for null
before calling methods, you provide a “null object” that implements the same interface but performs neutral or no-op actions.
Why It’s Useful
- Eliminates repetitive
null
checks. - Reduces the risk of
NullPointerException
. - Keeps code clean by avoiding conditionals around method calls (e.g.,
if (obj != null)
everywhere).
public interface Payment {
void pay();
}
public class CreditCardPayment implements Payment {
@Override
public void pay() {
System.out.println("Processing credit card payment...");
}
}
public class NullPayment implements Payment {
@Override
public void pay() {
// Do nothing, this is the "null" operation
}
}
// Usage
public class…