Java Design Patterns Flashcards

(95 cards)

1
Q

When will you use Strategy design pattern in Java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Strategy design pattern?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the examples of Strategy design pattern in JDK?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

MEMORY BOOSTER: Strategy pattern

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Observer design pattern?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the examples of Observer design pattern in JDK?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the main risk of Observer design pattern?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

MEMORY BOOSTER: Observer pattern

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How is Strategy design pattern different from State design pattern?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

MEMORY BOOSTER: Strategy vs State pattern

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is Decorator design pattern?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the examples of Decorator design pattern in JDK?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

MEMORY BOOSTER: Decorator pattern

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a good scenario for using Composite design pattern?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

MEMORY BOOSTER: Composite pattern

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are the main uses of Singleton design pattern in Java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why is java.lang.Runtime a Singleton in Java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the examples of Singleton design pattern in JDK?

A

java.lang.Runtime.getRuntime() - java.lang.System.getSecurityManager() - java.awt.Desktop.getDesktop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

MEMORY BOOSTER: Singleton pattern

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the ways to implement a thread-safe Singleton in Java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is Bill Pugh Singleton implementation?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is Double Checked Locking in Singleton?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Why must the instance field be volatile in Double Checked Locking Singleton?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

MEMORY BOOSTER: Thread-safe Singleton options

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is Template Method design pattern?
Template Method is a behavioral pattern where a parent class defines the skeleton of an algorithm and defers specific steps to subclasses. Subclasses can override individual steps without changing the overall algorithm structure. Example: Game with initializeGame() - makeMove() - endGame() steps implemented differently for Monopoly vs Chess
26
What are the examples of Template Method design pattern in JDK?
java.util.AbstractList - java.util.AbstractSet - java.util.AbstractMap provide template implementations for Collection operations. javax.servlet.http.HttpServlet provides a template where doGet() and doPost() return 405 by default and subclasses override them. java.io.InputStream/OutputStream/Reader/Writer provide non-abstract template methods
27
MEMORY BOOSTER: Template Method pattern
Template Method = skeleton in parent class + steps delegated to subclasses. Parent defines algorithm structure. Subclasses fill in the steps. Classic: HttpServlet defines service() template - doGet/doPost are the steps you override. AbstractList defines the List algorithm - you implement get() and size(). Also good for providing customizable classes
28
What are the examples of Factory Method design pattern in JDK?
java.lang.Class.forName() - java.util.Calendar.getInstance() - java.util.ResourceBundle.getBundle() - java.text.NumberFormat.getInstance() - java.nio.charset.Charset.forName() - java.util.EnumSet.of() - java.net.URLStreamHandlerFactory.createURLStreamHandler()
29
What is the benefit of using a static factory method to create objects?
Factory encapsulates object creation and can select the right implementation at runtime. The caller specifies desired behavior. Factory can also limit resource creation (like ConnectionPool limiting connections). Callers do not need to know the concrete class being created
30
MEMORY BOOSTER: Factory Method pattern
Factory Method = encapsulate object creation. Client calls factory method and gets correct implementation without knowing the concrete class. Calendar.getInstance() returns correct Calendar for locale. ShapeFactory.createShape("Circle") returns a Circle. Benefit: decouple client from concrete classes + runtime type selection
31
What is Builder design pattern?
Builder is a creational pattern for constructing complex objects step by step with multiple options. Each step can be chained. The same construction process can create different representations. Example: building a Meal by adding Starter + Drink + Main Course + Dessert in any combination
32
What are the examples of Builder design pattern in JDK?
java.lang.StringBuilder.append() - java.lang.StringBuffer.append() - java.nio.IntBuffer.put() - javax.swing.GroupLayout.Group.addComponent() - java.lang.Appendable. StringBuilder is the most classic example of Builder pattern
33
MEMORY BOOSTER: Builder pattern
Builder = step-by-step construction of complex object + method chaining. StringBuilder.append().append().toString() is Builder in action. Use when: many constructor parameters OR optional parameters OR want readable construction code. Builder creates variants with fine-grained control. Factory creates broader subtypes
34
What are the examples of Abstract Factory design pattern in JDK?
javax.xml.xpath.XPathFactory.newInstance() - javax.xml.parsers.DocumentBuilderFactory.newInstance() - javax.xml.transform.TransformerFactory.newInstance()
35
What is the difference between Factory and Abstract Factory design pattern?
Factory creates concrete products of one type (CarFactory makes Honda - Toyota - Ford). Abstract Factory creates families of related products - it produces a Factory of factories (DeviceFactory produces AppleDeviceFactory and GoogleDeviceFactory - each then produces a family of products). Abstract Factory already contains Factory pattern inside it
36
MEMORY BOOSTER: Factory vs Abstract Factory
Factory = create ONE type of product (CarFactory creates specific car models). Abstract Factory = create FAMILIES of related products (AppleDeviceFactory creates iPhone + iPad + Mac together). Abstract Factory is one level higher: it produces a factory which then produces products. Abstract Factory contains Factory pattern
37
What are the examples of Proxy design pattern in JDK?
java.lang.reflect.Proxy - java.rmi.* (Remote Method Invocation) - javax.inject.Inject - javax.ejb.EJB - javax.persistence.PersistenceContext
38
What are the different scenarios for using Proxy design pattern?
Virtual Proxy: lazy loading of expensive objects. Remote Proxy: local object providing access to remote object (RMI/RPC stub). Protective Proxy: authentication and authorization control before accessing main object. Smart Proxy: adds tracking - logging or access counting around the main object
39
MEMORY BOOSTER: Proxy design pattern
Proxy = same interface as real object + adds indirection. 4 types: Virtual (lazy loading) + Remote (RMI stub) + Protective (auth/authz guard) + Smart (tracking/logging wrapper). vs Decorator: Proxy provides same interface. Decorator enhances interface with new features. Proxy controls access. Decorator adds behavior
40
What are the examples of Chain of Responsibility design pattern in JDK?
java.util.logging.Logger.log() - multiple log() method variants pass responsibility to the appropriate logger. javax.servlet.Filter.doFilter() - container calls doFilter() and passes FilterChain to allow the filter to forward to the next filter in the chain
41
MEMORY BOOSTER: Chain of Responsibility pattern
Chain of Responsibility = pass request along a chain until one handler handles it. Each handler decides to handle or pass on. Classic: Servlet Filters - each filter processes request and passes to next via FilterChain. Logger chain - logs at appropriate level. Decouples sender from receiver
42
What are the main uses of Command design pattern?
GUI buttons and menu items - Macro recording and playback (series of commands) - Multi-step Undo/Redo in text editors - Sending commands over network - Progress bar tracking (each command estimates time) - Wizard step flows - Transaction management (commit or rollback steps)
43
What are the examples of Command design pattern in JDK?
All implementations of java.lang.Runnable are Command pattern. All implementations of javax.swing.Action are Command pattern
44
MEMORY BOOSTER: Command pattern
Command = encapsulate a request as an object. Supports: Undo/Redo (store commands) + Macro recording (list of commands) + Transactions (commit/rollback) + Queue and schedule commands. Runnable is the classic Java Command. execute() = do the command. undo() = reverse it
45
What are the examples of Interpreter design pattern in JDK?
java.util.Pattern (regex engine interprets pattern expressions) - java.text.Normalizer - subclasses of java.text.Format (DateFormat - MessageFormat - NumberFormat) - subclasses of javax.el.ELResolver (ArrayELResolver - MapELResolver - CompositeELResolver)
46
MEMORY BOOSTER: Interpreter pattern
Interpreter = evaluate sentences in a language. Each keyword/symbol is a class. Sentence is a composite parsed into a syntax tree and interpreted. Classic: SQL parser - regex engine. JDK: java.util.Pattern interprets regex. NumberFormat interprets number patterns. Use when you need a simple grammar interpreter
47
What are the examples of Mediator design pattern in JDK?
java.util.Timer - schedule() acts as Mediator between clients and TimerTask. java.util.concurrent.Executor.execute() - the executor mediates between caller and the Runnable task. java.util.concurrent.ExecutorService. java.lang.reflect.Method.invoke() mediates method calls. ScheduledExecutorService.schedule()
48
MEMORY BOOSTER: Mediator pattern
Mediator = one central object coordinates communication between many objects. Reduces many-to-many relationships to many-to-one. Objects do not reference each other directly - they go through the mediator. Classic: chat room server (mediator) coordinates messages between users. JDK: Executor mediates between caller and Runnable tasks
49
What are the examples of Visitor design pattern in JDK?
javax.lang.model.element.AnnotationValue and AnnotationValueVisitor - java.nio.file.FileVisitor and SimpleFileVisitor - javax.lang.model.type.TypeMirror and TypeVisitor - javax.lang.model.element.Element and ElementVisitor - javax.faces.component.visit.VisitContext and VisitCallback
50
What is Visitor design pattern?
Visitor pattern lets you add new virtual operations to existing class hierarchies without modifying those classes. A Visitor object implements an operation for each class in the hierarchy. You pass the visitor to the objects which then call the appropriate visitor method
51
MEMORY BOOSTER: Visitor pattern
Visitor = add new operations to existing classes without modifying them. Separate algorithm from object structure. Double dispatch: element.accept(visitor) -> visitor.visit(element). JDK: FileVisitor visits files in a directory tree. Use when: object structure is stable + operations on it change frequently
52
What is the main difference between Decorator and Proxy design pattern?
Decorator enhances the interface by adding new features and behavior. Proxy provides the same interface as the real object and controls access to it. Decorator follows recursive composition adding features in layers. Proxy can add lazy loading and performance improvements. Decorator is for building varieties of objects. Proxy is for access control
53
MEMORY BOOSTER: Decorator vs Proxy
Decorator = enhanced interface + adds features + recursive wrapping + building variety. Proxy = same interface + controls access + lazy loading + access restriction. Think: Decorator adds new capabilities. Proxy is a gatekeeper. IO streams = Decorator. Spring AOP proxies = Proxy pattern
54
When will you use Adapter design pattern in Java?
Use Adapter when you have two classes with incompatible interfaces that need to work together. Create an Adapter class that translates one interface to another. Commonly used with third-party libraries to isolate external code changes to just the Adapter class
55
What are the examples of Adapter design pattern in JDK?
java.util.Arrays.asList() adapts Array to List. java.util.Collections.list() adapts Collection to List behavior. java.io.InputStreamReader(InputStream) adapts a Stream to Reader. java.io.OutputStreamWriter(OutputStream) adapts OutputStream to Writer. javax.xml.bind.annotation.adapters.XmlAdapter.marshal()
56
What is the main difference between Adapter and Proxy design pattern?
Adapter provides a different interface - it converts one interface to another (like a socket adapter). Proxy provides the same interface but adds protection or indirection. Adapter = change interface. Proxy = same interface with a gatekeeper
57
MEMORY BOOSTER: Adapter pattern
Adapter = convert one interface to another = makes incompatible interfaces work together. Classic: InputStreamReader adapts InputStream (bytes) to Reader (chars). Like a power plug adapter. vs Proxy: same interface + access control. vs Decorator: same interface + adds features. Adapter CHANGES the interface
58
What are the scenarios to use Setter vs Constructor injection in Dependency Injection?
Constructor injection = mandatory dependencies = object is always valid after construction. Setter injection = optional dependencies = provides flexibility after construction. Best practice: use constructor for required dependencies and setter for optional ones
59
MEMORY BOOSTER: Setter vs Constructor injection
Constructor injection = mandatory + guaranteed initialization + immutable field possible. Setter injection = optional + flexible + can inject after construction. Spring supports both. Constructor injection is preferred for testability and ensuring all required deps are provided at creation time
60
What is the Open/Closed design principle?
Software entities (classes - modules - functions) should be open for extension but closed for modification. Add new functionality by writing new code not by changing existing tested code. Originated by Bertrand Meyer. Used in State and Strategy patterns where Context is closed but new strategies can be added
61
MEMORY BOOSTER: Open/Closed principle
Open = can extend (add new behavior). Closed = cannot modify existing code. Add features by extending not by changing. Example: add new sort strategy by writing a new Comparator class - not by modifying Collections.sort(). Strategy and State patterns are built on this principle. O in SOLID
62
What is SOLID design principle?
SOLID = S: Single Responsibility (one class = one job). O: Open/Closed (open for extension - closed for modification). L: Liskov Substitution (subclasses must be substitutable for parent). I: Interface Segregation (many specific interfaces better than one generic). D: Dependency Inversion (depend on abstractions not concrete implementations)
63
What is Single Responsibility Principle?
A class should have only one reason to change - meaning it should have only one responsibility. A class handling both business logic and database access violates SRP. Split it into separate classes each with a single clear purpose
64
What is Liskov Substitution Principle?
Objects in a program should be replaceable by instances of their subclasses without altering the correctness of the program. If class B extends class A then wherever A is used B must work correctly without breaking the program
65
What is Interface Segregation Principle?
Multiple client-specific interfaces are better than one general-purpose interface. Clients should not be forced to depend on methods they do not use. Split fat interfaces into smaller focused ones
66
What is Dependency Inversion Principle?
High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details - details should depend on abstractions. This is the foundation of Dependency Injection in Spring
67
MEMORY BOOSTER: SOLID principles
S = Single Responsibility (one class one job). O = Open/Closed (extend not modify). L = Liskov Substitution (subclasses must substitute parent safely). I = Interface Segregation (small focused interfaces). D = Dependency Inversion (depend on abstractions). Remember: each letter = one OOP design rule
68
What is the difference between Builder and Factory design pattern?
Factory creates broader subtypes of an object and the caller gets a complete object (Tea or Coffee). Builder creates complex objects step-by-step with fine-grained control over composition (Cappuccino with Vanilla Cream and Sugar vs Latte with Splenda and milk). Builder supports many more variants with more complex composition
69
MEMORY BOOSTER: Builder vs Factory
Factory = select WHAT to create (one of several known subtypes) + client gets complete object. Builder = specify HOW to construct (step-by-step assembly) + many fine-grained variants. Factory: createDrink() -> Tea or Coffee. Builder: addMilk().addSugar().addFlavor() -> exact custom coffee. Builder is more detailed + complex composition
70
What are the different categories of Design Patterns in Object Oriented Design?
Three categories: Creational (Builder - Factory Method - Abstract Factory - Object Pool - Singleton - Prototype). Structural (Adapter - Bridge - Facade - Decorator - Composite - Flyweight - Proxy). Behavioral (Command - Iterator - Chain of Responsibility - Observer - State - Strategy - Mediator - Interpreter)
71
MEMORY BOOSTER: Design pattern categories
3 categories: Creational = HOW objects are created (Singleton - Factory - Builder - Prototype). Structural = HOW objects are composed (Adapter - Decorator - Proxy - Composite - Bridge - Facade). Behavioral = HOW objects interact (Strategy - Observer - Command - State - Template - Iterator - Chain). Remember: Create + Structure + Behave
72
What design pattern is suitable to access elements of a Collection?
Iterator design pattern is used to access individual elements of a collection sequentially without exposing its underlying representation. Java has many Iterator implementations in the Collections package including Spliterator and ListIterator
73
MEMORY BOOSTER: Iterator pattern
Iterator = traverse collection without knowing its internals. Java: Iterable + Iterator + for-each loop = Iterator pattern. Spliterator for parallel iteration. ListIterator for bidirectional traversal. Pattern separates traversal algorithm from the collection. Collection provides the iterator - client uses it
74
How can we implement Producer Consumer design pattern in Java?
Use BlockingQueue in Java to implement Producer Consumer design pattern. Producer puts objects into the BlockingQueue. Consumer takes objects from the BlockingQueue. BlockingQueue handles thread synchronization automatically blocking producers when full and consumers when empty
75
MEMORY BOOSTER: Producer Consumer pattern
Producer Consumer = decouple producers from consumers via a buffer (BlockingQueue). Producer: queue.put(item) - blocks if queue is full. Consumer: queue.take() - blocks if queue is empty. BlockingQueue is thread-safe and handles synchronization automatically. ArrayBlockingQueue (bounded) or LinkedBlockingQueue (optional bound)
76
What design pattern is suitable to add new features to an existing object?
Decorator design pattern adds new features to an existing object while keeping the same interface. All decorated versions implement the same interface. The structure of the object remains the same
77
Which design pattern can be used to decouple abstraction from implementation?
Bridge design pattern decouples abstraction from implementation. Abstraction and implementation can vary independently. Example: Shape hierarchy (Square - Circle) crossed with Color hierarchy (Red - Black - Green) uses Bridge to avoid an explosion of subclasses like RedSquare - BlackSquare - GreenCircle etc.
78
MEMORY BOOSTER: Bridge pattern
Bridge = separate abstraction from implementation into two hierarchies that can vary independently. Without Bridge: Shape x Color = N*M classes (RedSquare - BlackCircle etc.). With Bridge: N shape classes + M color classes with composition. Often implemented using Adapter internally
79
Which design pattern is predominantly used in Android applications?
Android applications predominantly use Model View Presenter (MVP) pattern. Model = business logic and rules. View = UI components and events. Presenter = bridge between Model and View - queries model and updates view. Presenter keeps the View lightweight by only passing what the View needs
80
MEMORY BOOSTER: MVP in Android
MVP: Model (data + business logic) + View (UI components + events) + Presenter (bridge - queries model - updates view). Difference from MVC: Presenter does not directly depend on View - it communicates through an interface. View is passive. Presenter is testable without UI. Android + MVP = clean separation of concerns
81
How can we prevent users from creating more than one Singleton instance by using clone()?
Do not implement the Cloneable interface in your Singleton class. If you must implement Cloneable then override clone() and throw CloneNotSupportedException. This prevents anyone from using clone() to bypass the private constructor
82
MEMORY BOOSTER: Protect Singleton from clone()
Threats to Singleton: 1) clone() - fix: do not implement Cloneable or override clone() to throw exception. 2) Reflection - fix: throw exception in constructor if instance exists. 3) Serialization - fix: implement readResolve() to return existing instance. Enum Singleton is protected from all three automatically
83
What is the use of Interceptor design pattern?
Interceptor pattern is used to intercept requests before they reach the target resource. Primary use is in security - authentication and authorization. In Java it is used in javax.servlet.Filter. Spring framework uses it in HandlerInterceptor and MVC interceptors
84
MEMORY BOOSTER: Interceptor pattern
Interceptor = cross-cutting concern applied to requests before/after processing. Uses: authentication + authorization + logging + performance monitoring. Java: Servlet Filter = Interceptor. Spring: HandlerInterceptor. AOP = aspect-based interceptors. Intercept -> check/modify -> allow or reject -> continue chain
85
What are the Architectural patterns that you have used?
MVC (Model View Controller - used by Spring) + Publish-Subscribe (messaging - topics + subscribers) + Service Locator (JNDI - central registry of services) + n-Tier (presentation + application + data layers) + DAO (Data Access Object - decouple business logic from database) + IoC (Inversion of Control - core of Spring DI)
86
What is the n-Tier architectural pattern?
n-Tier divides architecture into multiple layers: Presentation layer (UI) + Application layer (business logic) + Data Access layer (database). Each layer has a specific responsibility and communicates only with adjacent layers. Also called multi-layer architecture
87
MEMORY BOOSTER: Architectural patterns
Big 6: MVC (Spring web) + Publish-Subscribe (messaging/Kafka) + Service Locator (JNDI) + n-Tier (3-layer: UI/Business/Data) + DAO (database abstraction layer) + IoC (Spring DI foundation). MVC is most common for web. DAO protects business logic from database changes. IoC makes components loosely coupled
88
What are the popular uses of Facade design pattern?
Provide simple methods for common complex tasks. Make a software library more readable and usable. Reduce external dependencies on inner implementation. Wrap poorly designed APIs with one well-designed API. Simplify access to a complex subsystem by providing a single entry point
89
MEMORY BOOSTER: Facade pattern
Facade = simplified interface to a complex subsystem. Hides complexity behind a single class. Client uses Facade instead of interacting with multiple complex classes. Classic: a single RestaurantFacade.orderMeal() hides ordering + cooking + payment subsystems. Facade reduces coupling between client and complex internal system
90
What is Memento design pattern?
Memento pattern implements rollback/undo by capturing an object's state externally. Three participants: Originator (object with state) + Caretaker (changes state but wants rollback ability) + Memento (the captured state snapshot). Caretaker gets Memento before changes and returns it to Originator to restore. Classic use: form reset - text editor undo
91
MEMORY BOOSTER: Memento pattern
Memento = snapshot of object state = undo/rollback capability. Three roles: Originator (has state) + Caretaker (changes state + holds memento) + Memento (state snapshot). Classic examples: Ctrl+Z undo in text editor + form reset + database transaction rollback. Caretaker asks for memento before change - returns it to rollback
92
What is an AntiPattern?
An AntiPattern is a common practice used to deal with a recurring problem that has more bad consequences than good ones. Found in organizations - architecture or software engineering. Examples: Gold Plating (over-engineering) - Spaghetti Code (complex unreadable code) - Coding By Exception (handling corner cases with patches) - Copy Paste Programming
93
MEMORY BOOSTER: AntiPatterns
AntiPattern = common bad practice. 4 software AntiPatterns: Gold Plating (over-engineering beyond requirements) + Spaghetti Code (complex unmaintainable code) + Coding By Exception (patching corner cases instead of proper design) + Copy Paste Programming (duplicating code instead of abstracting). AntiPatterns hurt maintainability and quality
94
What is a Data Access Object (DAO) design pattern?
DAO is a data persistence pattern that uses encapsulation to decouple business logic from the database. The DAO interface hides the underlying database implementation. Business logic only talks to the DAO interface so changing the database does not affect business logic. Can use in-memory H2 with DAO for unit testing
95
MEMORY BOOSTER: DAO pattern
DAO = Data Access Object = database abstraction layer. Business logic -> DAO interface -> database implementation. Swap database (Oracle to MySQL) = only change DAO implementation. Business logic unchanged. Spring + DAO + JPA is very common. Unit test with H2 in-memory database behind the same DAO interface