When will you use Strategy design pattern in Java?
Strategy pattern is used to select an algorithm at runtime from a family of algorithms. Create an abstraction (interface) that clients interact with and multiple implementations behind it. Use it when you want to hide algorithm details from the client. Examples: sorting strategy - file format selection. Collections.sort() uses Strategy pattern
What is Strategy design pattern?
Strategy is a behavioral design pattern where a family of algorithms is encapsulated behind an interface. The client selects the algorithm at runtime without knowing the implementation details. The algorithm can vary based on the type of request
What are the examples of Strategy design pattern in JDK?
java.util.Comparator uses Strategy - the compare() method changes the sort strategy for Collections.sort(). javax.servlet.http.HttpServlet uses Strategy - doGet() and doPost() allow implementors to select their own processing strategy
MEMORY BOOSTER: Strategy pattern
Strategy = family of algorithms + same interface + swap at runtime. Client calls interface - implementation varies. Collections.sort(list - comparator) = Strategy in action - comparator IS the strategy. Remember: Strategy = WHAT algorithm to use. State = WHAT state the object is in
What is Observer design pattern?
In Observer pattern a Subject maintains a list of Observers that are notified when the Subject changes. Subject broadcasts updates to all registered observers. Classic use: Model View Controller (MVC) architecture. Risk: can cause memory leaks if observers are not de-registered since Subject holds strong references
What are the examples of Observer design pattern in JDK?
java.util.Observer and java.util.Observable - javax.servlet.http.HttpSessionAttributeListener - javax.servlet.http.HttpSessionBindingListener - all implementations of java.util.EventListener in Swing packages - javax.faces.event.PhaseListener
What is the main risk of Observer design pattern?
Memory leaks. The Subject holds strong references to all registered observers. If observers are not de-registered when no longer needed they remain in memory preventing garbage collection even if nothing else references them
MEMORY BOOSTER: Observer pattern
Observer = Subject (broadcaster) + Observers (listeners). Subject notifies all observers on change. MVC uses Observer: Model = Subject + View = Observer. Risk: memory leaks from unreleased strong references. Fix: always de-register observers when done. JDK: EventListener + java.util.Observer
How is Strategy design pattern different from State design pattern?
State pattern manages an object’s internal states - the state changes based on internal object conditions and actions taken on the object. Strategy pattern selects an algorithm based on external client input at runtime. State = driven by internal object state. Strategy = driven by external client invocation
MEMORY BOOSTER: Strategy vs State pattern
Strategy = client picks algorithm via external input = no object state involved. State = object changes behavior based on its own internal state. Both are behavioral patterns and look similar. Key difference: who drives the change. Strategy = caller. State = the object itself based on its own current state
What is Decorator design pattern?
Decorator (also called Wrapper) adds behavior to an individual object without changing the behavior of other objects of the same class. All decorated versions implement the same interface. java.io package is the classic example: FileInputStream -> BufferedInputStream -> GzipInputStream -> ObjectInputStream
What are the examples of Decorator design pattern in JDK?
java.io subclasses of InputStream/OutputStream/Reader/Writer (wrapping constructors add behavior). java.util.Collections methods: synchronizedList() - unmodifiableList() - checkedList() decorate collections with extra behavior. javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper
MEMORY BOOSTER: Decorator pattern
Decorator = add behavior to ONE object without changing other instances. All decorators implement same interface. Classic: IO streams - FileInputStream wrapped in BufferedInputStream wrapped in GzipInputStream. Think: layers of wrapping - each layer adds a feature. Also called Wrapper pattern
What is a good scenario for using Composite design pattern?
Tree structures: Org chart where Manager is also an Employee. Recursion: algorithms that need uniform treatment of individual objects and compositions. Graphics: grouping shapes into higher-level groups. Composite treats individual objects and groups of objects uniformly through the same interface
MEMORY BOOSTER: Composite pattern
Composite = tree structure + leaf and composite nodes implement same interface. Clients treat individual objects and groups the same way. Examples: File system (file + folder) - Org chart (employee + manager) - UI components (button + panel containing buttons). Think: part-whole hierarchies
What are the main uses of Singleton design pattern in Java?
java.lang.Runtime (one interface to JVM environment). Java Enum values (globally accessible single instances). Application properties (one shared copy for all classes). Spring beans (default scope is Singleton per container). Database connection pools. Logging objects
Why is java.lang.Runtime a Singleton in Java?
Runtime is the single interface between the Java process and its environment. Methods like totalMemory() - maxMemory() - exit() and gc() must be controlled. Multiple exit() callers or multiple GC instances running simultaneously would be dangerous. One Runtime ensures one controlled interface to the JVM
What are the examples of Singleton design pattern in JDK?
java.lang.Runtime.getRuntime() - java.lang.System.getSecurityManager() - java.awt.Desktop.getDesktop()
MEMORY BOOSTER: Singleton pattern
Singleton = one instance in JVM = private constructor + static instance + getInstance(). Main uses: Runtime - Enum - Properties - Spring beans (default). Implementation options: Double-checked locking (volatile + synchronized) - Bill Pugh (static inner class) - Enum (simplest + thread-safe). Spring beans are Singleton by default per container
What are the ways to implement a thread-safe Singleton in Java?
Three main approaches: 1) Double Checked Locking - use volatile field + synchronized block checking null twice. 2) Bill Pugh - use a private static inner class to hold the instance - class loading guarantees thread safety. 3) Enum - simplest and most thread-safe - JVM guarantees single enum instance
What is Bill Pugh Singleton implementation?
Bill Pugh Singleton uses a private static inner class to hold the Singleton instance. The inner class is only loaded when getInstance() is called providing lazy initialization. Class loading is thread-safe by JVM guarantees so no explicit synchronization is needed
What is Double Checked Locking in Singleton?
Double Checked Locking checks if the instance is null twice - once outside the synchronized block and once inside. The instance field must be volatile to prevent instruction reordering. This avoids synchronization overhead on every call after the instance is created
Why must the instance field be volatile in Double Checked Locking Singleton?
Without volatile the JVM can reorder instructions so a partially constructed object may be visible to other threads. volatile prevents this instruction reordering ensuring that the fully constructed instance is visible before the reference is assigned
MEMORY BOOSTER: Thread-safe Singleton options
3 options: 1) Double-checked locking = volatile field + synchronized(this) + check null twice. 2) Bill Pugh = private static inner class = lazy + thread-safe by class loading. 3) Enum = public enum SingletonEnum { INSTANCE } = simplest + thread-safe + serialization-safe. Recommended: Enum or Bill Pugh