Hmm, the user is asking about design patterns, specifically Singleton and Factory, with examples of their use cases. This is a common software engineering question, likely from someone learning OOP principles.
I should start with a clear definition of design patterns to establish context, then dive into each pattern separately. For Singleton, I'll explain its purpose (ensuring single instance), core implementation (private constructor + static getter), and a practical scenario like configuration management. For Factory, I'll highlight its role in object creation decoupling, contrast it with direct instantiation, and use a payment processor example—something universally relatable.
Need to emphasize that Singleton is for global access control while Factory is for flexible object creation. The scenarios should be concrete but not overly complex. Avoid diving into advanced variations (like thread-safe Singleton) unless asked. Keep it concise but precise—user probably wants foundational understanding, not exhaustive details.
Design Patterns
A design pattern is a reusable, well-proven solution to a common problem in software design. It's not finished code, but a description or template of how to structure classes and objects to solve a design challenge. Patterns promote code reusability, maintainability, flexibility, and help teams communicate using established terminology.
1. Singleton Pattern
Purpose: Ensure a class has only one instance and provide a global point of access to it.
Core Idea:
- Make the constructor private to prevent direct instantiation.
- Create a private static variable to hold the single instance.
- Provide a public static method (often named
getInstance()) that returns the instance, creating it on the first call if needed.
Example (Java-like pseudocode):
public class DatabaseConnection {
private static DatabaseConnection instance;
private DatabaseConnection() { /* private constructor */ }
public static synchronized DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
}
return instance;
}
}
When to use Singleton:
- When exactly one instance must coordinate actions across a system (e.g., configuration manager, logging service, thread pool, hardware access).
- When you need strict control over instance creation (avoiding multiple connections to a DB).
- When a shared resource must be accessed globally without passing references around.
⚠️ Caution: Overuse leads to hidden dependencies, global state issues, and testing difficulties. Prefer dependency injection where possible.
2. Factory Pattern
Purpose: Define an interface for creating objects but let subclasses decide which class to instantiate. It encapsulates object creation logic, making the system more flexible and decoupled.
Core Idea:
- Create objects through a factory method instead of using
new directly.
- Client code calls the factory, not the concrete class constructor.
- Often involves a Creator (factory) and Product (interface/abstract class) hierarchy.
Example:
// Product interface
interface Button { void render(); }
// Concrete products
class WindowsButton implements Button {
public void render() { /* render Windows style */ }
}
class MacButton implements Button {
public void render() { /* render Mac style */ }
}
// Factory
class ButtonFactory {
public Button createButton(String os) {
if (os.equals("Windows")) return new WindowsButton();
else if (os.equals("Mac")) return new MacButton();
throw new UnsupportedOperationException();
}
}
When to use Factory:
- When the exact type of object to create depends on runtime conditions (e.g., user OS, configuration, input).
- When you want to decouple client code from concrete implementations.
- To centralize object creation logic (e.g., complex initialization, caching, pooling).
- In frameworks where you need to create objects without knowing their concrete classes in advance.
Scenario Examples
Singleton Scenario: Application Configuration Manager
Factory Scenario: Cross-Platform Payment Processor
Key Difference
| Aspect | Singleton | Factory |
|---|
| Goal | Control instance count (1). | Control object creation. |
| Focus | Global access to one object. | Flexibility in creating families of objects. |
| Dependency | Often creates its own instance. | Often delegates to subclasses or external config. |
| Testability | Harder (global state). | Easier (inject mock factory). |
Use Singleton when you need exactly one shared resource. Use Factory when you need to abstract creation of varying objects. Both promote cleaner architecture when applied appropriately.