94 Design Patterns Interview Questions and Answers (2026)

Blog / 94 Design Patterns Interview Questions and Answers (2026)
Design Patterns

Design Patterns interviews aren't about memorizing definitions anymore. As codebases grow and hiring bars climb, interviewers expect you to know when a Singleton saves you, when a pattern becomes over-engineering, and why one choice beats another. Walk in shaky here and it shows fast—vague answers signal you've read about patterns but never wrestled with them.

This post gives you 94 questions with concise, interview-ready answers and code where it actually helps. It's organized Junior to Senior, so you build from pattern fundamentals up through Creational, Structural, and Behavioral patterns, DI and IoC, and enterprise and framework-level design. Work through it and you'll speak about patterns like someone who's used them, not just studied them.

Q1.
Why do we use design patterns? Beyond just reusing code, what do they provide for a development team in terms of communication and maintenance?

Junior

Design patterns are proven solutions to recurring problems, but their biggest payoff is shared vocabulary and predictable structure: they let a team communicate intent and maintain code with less friction, not just reuse snippets.

  • Communication (a shared language):

    • Saying "use an Observer here" conveys structure, roles, and trade-offs in two words instead of a paragraph.

    • Names appear in code reviews, design docs, and diagrams, aligning the team fast.

  • Maintenance and comprehension:

    • A recognized pattern is a familiar shape: a new dev spots the intent quickly rather than reverse-engineering it.

    • Patterns localize change (e.g. adding a new Strategy without touching callers), reducing regression risk.

  • Proven design quality: They encode tested answers to coupling and change, steering teams away from known pitfalls.

  • Caveat: the value is realized only when applied to a real problem; used decoratively they add noise.

Q2.
Explain the three main categories of Gang of Four patterns (Creational, Structural, Behavioral) and what specific problem each category aims to solve.

Junior

The Gang of Four grouped 23 patterns by the kind of problem they address: how objects are created, how they're composed, and how they interact at runtime.

  • Creational (object creation):

    • Problem: decouple code from the concrete classes it instantiates, and control how/when objects are made.

    • Examples: Factory Method, Abstract Factory, Builder, Singleton, Prototype.

  • Structural (object composition):

    • Problem: assemble classes and objects into larger structures while keeping them flexible and efficient.

    • Examples: Adapter, Decorator, Facade, Composite, Proxy.

  • Behavioral (object interaction):

    • Problem: define how objects communicate and distribute responsibility, reducing tight coupling in their collaboration.

    • Examples: Strategy, Observer, Command, State, Template Method.

Q3.
What is the difference between a design pattern and a design principle like SOLID?

Junior

A principle is a general guideline about what good design looks like; a pattern is a concrete, reusable structure that helps you achieve those principles in a specific situation. Principles are the "why," patterns are a proven "how."

  • Design principle (e.g. SOLID):

    • Abstract, always-applicable advice: single responsibility, open/closed, dependency inversion.

    • Says nothing about class layout; it's a quality bar you judge designs against.

  • Design pattern:

    • A named, structured solution with defined roles for a recurring problem (e.g. Strategy).

    • Applied selectively when its problem appears, not everywhere.

  • How they relate:

    • Patterns are often concrete embodiments of principles: Strategy realizes open/closed and dependency inversion.

    • You can follow principles with no named pattern, but a good pattern rarely violates them.

Q4.
Explain the fundamental difference between a design pattern and an algorithm. Can you have one without the other?

Junior

An algorithm is a precise step-by-step recipe to compute a result; a design pattern is a way to organize classes and objects so code is flexible and maintainable. One answers "how do I compute this," the other answers "how do I structure this."

  • Algorithm:

    • Deterministic sequence of operations with a defined input and output (e.g. quicksort, Dijkstra).

    • Concerned with correctness and efficiency, not code organization.

  • Design pattern:

    • A template for relationships between components; it doesn't tell you what to compute.

    • Concerned with coupling, change, and communication.

  • Can you have one without the other? Yes, both ways:

    • An algorithm needs no pattern: a standalone sort function has no object structure.

    • A pattern needs no interesting algorithm: a Strategy can wrap trivial one-line behaviors.

    • They combine well: Strategy is often used to make interchangeable algorithms swappable at runtime.

Q5.
What is a design pattern, and what are the primary benefits of using them in a codebase?

Junior

A design pattern is a general, reusable solution to a commonly recurring problem in software design: not finished code, but a template for how to structure classes and objects. Its value is in making designs flexible, understandable, and easier to change.

  • What it is:

    • A named description of a problem, a proven solution structure, and its trade-offs (context matters).

    • Language-agnostic: you adapt it to your code, you don't copy-paste it.

  • Primary benefits:

    1. Shared vocabulary: teams discuss intent quickly ("this is a Decorator").

    2. Maintainability: patterns isolate what varies, so changes stay localized.

    3. Flexibility and extensibility: new behavior added without rewriting existing code.

    4. Proven quality: they encode battle-tested solutions and avoid known traps.

  • Trade-off to acknowledge: they add indirection, so apply them to real problems, not preemptively.

Q6.
Who were the Gang of Four, and what is the significance of the 'Design Patterns' book?

Junior

The "Gang of Four" (GoF) are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, authors of the 1994 book Design Patterns: Elements of Reusable Object-Oriented Software, which catalogued 23 recurring solutions and gave the industry a shared vocabulary.

  • Who they were: Four software researchers/engineers who collected patterns observed across many OO systems, borrowing the "pattern" idea from architect Christopher Alexander.

  • What the book did:

    • Documented 23 patterns in three families: Creational, Structural, and Behavioral.

    • Gave each a consistent template: Intent, Motivation, Structure, Consequences.

  • Why it matters:

    • Shared vocabulary: saying "use an Observer" conveys a whole design instantly.

    • Promoted principles still central today: program to an interface, favor composition over inheritance.

  • Caveat: Some patterns exist to work around limitations of older languages; modern features (first-class functions, generics) make a few less necessary.

Q7.
When would you choose a Simple Factory over the formal Factory Method pattern?

Junior

Use a Simple Factory (one method with a switch/if that returns products) when object creation is centralized and the set of types is small and stable. Reach for the formal Factory Method only when subclasses need to decide which product to create and you want to extend without modifying existing code.

  • Simple Factory:

    • A single place (often a static method) picks the concrete class based on a parameter.

    • Pros: minimal, easy to read, hides new from clients.

    • Con: adding a type means editing the factory (violates open/closed), so it suits stable type sets.

  • Factory Method:

    • Declares a creation method that subclasses override, so the choice of product varies per subclass.

    • Pros: extensible without touching existing code; fits framework hook points.

    • Con: more classes and ceremony.

  • Rule of thumb: Start with Simple Factory; graduate to Factory Method when variation-by-subclass or extensibility genuinely appears.

Q8.
Give a real-world example of the Decorator pattern in a common framework such as java.io streams or Python decorators.

Junior

The classic example is Java's java.io stream classes, where you wrap one stream in another to layer capabilities; note that Python's @decorator syntax is related in spirit but is function wrapping, not the exact GoF object structure.

  • Java I/O streams (true GoF Decorator):

    • All share the InputStream/OutputStream interface, so wrappers are interchangeable.

    • You stack behaviors: BufferedInputStream adds buffering, DataInputStream adds typed reads.

  • Python decorators (conceptually similar):

    • A decorator wraps a function to add behavior (timing, caching, auth) while preserving its call signature.

    • Same core idea: transparent, composable added behavior.

java

InputStream in = new DataInputStream( // adds typed reads new BufferedInputStream( // adds buffering new FileInputStream("data.bin"))); // core source // each wrapper is an InputStream, so they compose freely

Q9.
How does the Iterator pattern let a client traverse an aggregate without exposing its underlying representation?

Junior

The Iterator moves traversal logic into a separate object that exposes a uniform interface (hasNext()/next()), so the client walks the collection through that interface while the aggregate's internal structure (array, tree, linked list) stays hidden.

  • Encapsulation of representation:

    • The client never indexes or navigates nodes directly; it only asks the iterator for the next element.

    • The aggregate can change its internal storage without breaking clients.

  • Separation of concerns: Traversal state (current position) lives in the iterator, not the collection, so multiple independent traversals can run at once.

  • Uniformity:

    • Different aggregates can offer the same iterator interface, letting client code stay identical across collection types.

    • In many languages this is built in (Python's __iter__/__next__, Java's Iterable).

Q10.
When should you avoid using a design pattern, and can you describe a scenario where applying one led to over-engineering?

Mid

Avoid a pattern when it adds indirection without solving a real, present problem: patterns trade simplicity for flexibility, and flexibility you don't need is just cost. Apply them to relieve actual pain (change, duplication, coupling), not speculatively.

  • When to avoid them:

    • The requirement is stable and simple: a direct implementation is clearer than an abstracted one.

    • You're guessing at future needs ("we might need to swap this"): YAGNI usually wins.

    • The pattern's vocabulary hides intent from readers instead of clarifying it.

  • Over-engineering scenario:

    • A team wrapped a single, never-changing email service behind an AbstractFactory plus a Strategy interface "for future providers" that never arrived.

    • Result: five files and two interfaces to send one email, harder onboarding, no realized benefit.

  • Healthier default: Start simple, refactor to a pattern when a second real case or a concrete change forces the abstraction.

Q11.
How do you distinguish a design pattern from a language-specific idiom or a library/framework?

Mid

A pattern is an abstract, language-independent design concept you implement yourself; an idiom is a language-specific way of doing something, and a library/framework is concrete code you call or plug into. Patterns describe structure, idioms and libraries provide the mechanics.

  • Design pattern:

    • Portable across languages: the Observer idea works in Java, Python, or Go.

    • You write the implementation; the pattern only guides its shape.

  • Language idiom:

    • A conventional, low-level technique tied to one language (e.g. Python context managers with with, or list comprehensions).

    • More granular and specific than a pattern.

  • Library / framework:

    • Concrete reusable code you consume; it may implement patterns internally (e.g. an event bus using Observer).

    • Difference of control: you call a library; a framework calls you (inversion of control).

  • Overlap: languages sometimes bake a pattern in as an idiom (Python's @decorator syntax echoes, but isn't identical to, the Decorator pattern).

Q12.
How do design patterns help achieve the 'Composition over Inheritance' heuristic?

Mid

Many patterns embody "composition over inheritance" by assembling behavior from collaborating objects at runtime instead of hard-coding it into a class hierarchy. They give you the flexibility inheritance promises without its rigidity.

  • Why inheritance is limiting:

    • It fixes behavior at compile time and creates tight parent/child coupling.

    • Combining variations explodes the number of subclasses.

  • How patterns compose instead:

    • Strategy: inject an interchangeable behavior object, swap it at runtime rather than subclassing.

    • Decorator: wrap an object to add responsibilities, stacking behaviors without new subclasses.

    • Composite: build tree structures from part/whole objects treated uniformly.

  • The payoff: Behavior becomes a property of collaborators you can reconfigure, aligning with open/closed and dependency inversion.

python

# Strategy: behavior composed in, not inherited class PaymentProcessor: def __init__(self, strategy): self.strategy = strategy # a collaborating object def pay(self, amount): return self.strategy.charge(amount) # Swap behavior at runtime without subclassing PaymentProcessor PaymentProcessor(CreditCard()).pay(100) PaymentProcessor(PayPal()).pay(100)

Q13.
What general trade-offs and consequences should you weigh before introducing any design pattern into a codebase?

Mid

A pattern buys flexibility at the price of indirection and complexity, so weigh whether the change it accommodates is real and likely before adopting it.

  • Complexity vs flexibility: More classes and layers of abstraction can make simple code harder to follow; the flexibility must be needed, not hypothetical.

  • Readability and team familiarity: A named pattern aids communication only if the team recognizes it; an obscure or misapplied pattern hurts maintainability.

  • Indirection cost: Extra hops (factories, decorators, proxies) can obscure control flow and complicate debugging.

  • Over-engineering (YAGNI): Applying patterns speculatively adds cost for flexibility you may never use; prefer refactoring toward a pattern when the need appears.

  • Performance: Some patterns add object allocations or delegation overhead; usually negligible but worth noting in hot paths.

  • Testability impact: Patterns that inject dependencies help testing; those introducing global state (e.g. Singleton) hurt it.

Q14.
What is the Telescoping Constructor problem, and how does the Builder pattern solve it? Why is it preferred for objects with many optional parameters?

Mid

The Telescoping Constructor problem is the explosion of overloaded constructors (or one giant parameter list) that appears when a class has many optional fields; the Builder pattern solves it by constructing the object step by step through readable, named method calls.

  • The problem:

    • You end up with many constructor overloads for each combination of optional args, or one long signature.

    • Call sites become unreadable and error-prone: new Pizza(12, true, false, true, false) (which boolean is what?).

  • How Builder fixes it:

    • Each optional value is set by a self-explanatory method that returns the builder, enabling fluent chaining.

    • A final build() produces the object, and can validate invariants in one place.

  • Why it's preferred:

    • Readability: named calls document intent at the call site.

    • Immutability: the target can be built once and expose no setters.

    • Flexibility: skip any optional field without new overloads.

java

Pizza pizza = new Pizza.Builder() .size(12) .cheese(true) .pepperoni(true) .build(); // validates and returns an immutable Pizza

Q15.
What is the fundamental difference between the Factory Method and the Abstract Factory pattern, and when would you choose one over the other?

Mid

Factory Method creates one product through a single overridable method, while Abstract Factory creates whole families of related products through an object with multiple creation methods. In short: Factory Method is a method, Abstract Factory is an object bundling several factory methods.

  • Factory Method:

    • Subclasses override a method to decide which single concrete product to instantiate.

    • Relies on inheritance: one product type per creator.

  • Abstract Factory:

    • An interface with several creation methods that produce a coordinated family (e.g. createButton() and createCheckbox() for a UI theme).

    • Relies on composition: you pass around the factory object.

  • When to choose:

    • Use Factory Method when a class defers instantiation of one product to subclasses.

    • Use Abstract Factory when you must guarantee that multiple related products come from the same family and stay consistent.

  • Relationship: Abstract Factories are often implemented with Factory Methods internally.

Q16.
In the Prototype pattern, what is the difference between a shallow copy and a deep copy, and why is this distinction critical when cloning complex objects?

Mid

A shallow copy duplicates the object's top-level fields but shares the same referenced sub-objects, whereas a deep copy recursively clones the referenced objects too. The distinction is critical because a shallow clone can leave the copy and original secretly sharing mutable state.

  • Shallow copy:

    • Copies primitive fields by value and reference fields by reference: both objects point to the same nested instances.

    • Mutating a nested object through one clone affects the other: a hidden coupling bug.

  • Deep copy:

    • Recursively clones every referenced object so the copy is fully independent.

    • More expensive and must handle nested collections and cyclic references carefully.

  • Why it matters for Prototype:

    • The pattern's whole point is producing an independent new object by cloning; a shallow clone breaks that guarantee for mutable members.

    • Default clone mechanisms (e.g. Java's Object.clone()) are shallow, so complex prototypes must override to deep-copy mutable fields.

  • Rule of thumb: Immutable or primitive-only fields: shallow is fine. Mutable nested objects: deep copy.

Q17.
What is the difference between eager initialization and lazy initialization for a Singleton?

Mid

Eager initialization creates the Singleton instance when the class loads; lazy initialization defers creation until the first request. The choice trades startup cost and simplicity against memory/thread-safety concerns.

  • Eager initialization:

    • Instance built at class-load time (e.g. a static final field in Java), so it is inherently thread-safe with no locking.

    • Downside: the instance exists even if never used, wasting resources for a heavy object.

  • Lazy initialization:

    • Instance created only on first access, saving startup cost and memory when unused.

    • Requires care under concurrency: naive lazy code can create two instances, so you need synchronized, double-checked locking, or a holder idiom.

  • Rule of thumb: Eager when the object is cheap and always used; lazy when it is expensive or may never be needed.

java

// Eager public class Config { private static final Config INSTANCE = new Config(); private Config() {} public static Config get() { return INSTANCE; } } // Lazy (thread-safe holder idiom) public class Config { private Config() {} private static class Holder { static final Config INSTANCE = new Config(); } public static Config get() { return Holder.INSTANCE; } }

Q18.
What is the difference between a fluent Builder and a standard Builder?

Mid

They build the same way; the difference is only the API shape. A fluent Builder returns the builder itself from each setter so calls can be chained, while a standard Builder uses plain void setters called one per statement.

  • Standard Builder:

    • Setters return void; you call each on its own line, then call build().

    • More verbose but trivially simple to write.

  • Fluent Builder:

    • Each setter returns this, enabling a chain like builder.name("x").age(3).build().

    • Reads like a sentence and reduces the temporary variable noise; it is the common style in modern APIs.

  • Bottom line: Fluent is a readability refinement of the same pattern, not a different pattern.

java

// Fluent: each setter returns this User u = new User.Builder() .name("Ada") .email("ada@x.com") .build();

Q19.
When would you use an Object Pool pattern instead of simply creating and destroying objects as needed?

Mid

Use an Object Pool when object creation or destruction is expensive and objects are reused frequently: you keep a set of ready instances and hand them out and return them instead of constructing fresh ones each time.

  • Good fit when:

    • Creation is costly: DB connections, threads, sockets, large buffers.

    • Objects are acquired and released rapidly and repeatedly (high churn).

    • You want to cap resource usage: the pool bounds how many exist at once.

  • Poor fit when:

    • Objects are cheap to create: pooling adds complexity for no gain.

    • Objects hold state that must be reset carefully: stale state causes subtle bugs.

  • Cost to weigh: You must manage lifecycle: reset on return, handle exhaustion, and avoid leaks from objects never returned.

  • Canonical examples: connection pools (HikariCP) and thread pools.

Q20.
What is the difference between a Singleton and a class with only static methods, and in what scenario would you choose one over the other?

Mid

A Singleton is a single object instance you can pass around and treat polymorphically; a static-only class is just a namespace of functions with no instance. Choose a Singleton when you need object semantics (interfaces, state, injectability); choose static methods for stateless, pure utilities.

  • Singleton:

    • Is an object: it can implement interfaces, be subclassed, and be passed as a parameter.

    • Can hold and manage state, and its creation can be lazy.

    • Can be mocked/injected, so it is friendlier to testing and dependency injection.

  • Static-method class:

    • No instance, no polymorphism: calls bind at compile time to the concrete class.

    • Best for pure, stateless helpers (Math.max, string utilities).

    • Hard to mock or swap, which hurts testability if it carries dependencies.

  • Choose accordingly: Need to abstract behind an interface or hold shared state? Singleton. Just grouping pure functions? Static methods.

Q21.
What are the trade-offs of using a Builder? Does it always make the code cleaner?

Mid

A Builder shines when constructing objects with many optional or interdependent parameters, giving readable, immutable, step-by-step construction. But it adds boilerplate, so for simple objects it makes code more complex, not cleaner.

  • Benefits:

    • Avoids telescoping constructors and unreadable positional args (new X(null, 0, true, null)).

    • Enables immutability: set fields on the builder, then produce a final object with no setters.

    • Can validate invariants in build() before the object exists.

  • Costs:

    • Extra class and duplicated fields: more code to write and maintain.

    • Overhead of an intermediate object.

    • Easy to forget a required field unless you enforce it.

  • So, not always cleaner: For 1-3 required parameters a plain constructor is clearer; the Builder pays off as optional parameters multiply.

Q22.
Why is using an enum considered the best way to implement a Singleton in Java?

Mid

An enum Singleton is considered best in Java because the language guarantees a single instance, and it handles thread-safety, lazy loading of the enum class, and serialization/reflection attacks for free. It is concise and effectively unbreakable.

  • Guaranteed single instance: The JVM ensures each enum constant is instantiated exactly once, with no locking code needed.

  • Reflection-safe: Reflection cannot instantiate enums, closing a hole that breaks ordinary private-constructor Singletons.

  • Serialization-safe: Enum serialization is handled specially, so deserializing does not create a second instance (a classic bug for class-based Singletons).

  • Concise: A few lines replace double-checked locking and its subtleties.

  • Caveats: Cannot extend another class, and eager by enum semantics, so it is not ideal if you need lazy loading of a heavy resource.

java

public enum Registry { INSTANCE; public void register(String k) { /* ... */ } } // use: Registry.INSTANCE.register("x");

Q23.
What is the role of the Director in the Builder pattern?

Mid

The Director encapsulates the how and order of construction steps, while the Builder supplies the concrete implementation of each step: it defines a reusable construction sequence so the same recipe can build products from different builders.

  • Owns the construction algorithm: Calls builder steps in a fixed order (e.g. buildWalls(), buildRoof()), so clients reuse a known recipe instead of remembering step sequences.

  • Decouples the sequence from the parts: Swap in a different Builder and the same Director produces a different representation (a house vs a cabin) using identical steps.

  • Optional by design: For a single or ad-hoc build order, clients can drive the builder directly; the Director earns its place when the same sequence is reused or is complex.

  • The product is retrieved from the builder, not the Director: The Director knows steps, not the concrete product type, so it stays independent of what is being built.

Q24.
What is the concept of a 'product family' in the Abstract Factory pattern, and why does it matter?

Mid

A product family is a set of related objects designed to be used together (e.g. a Button, Checkbox, and Scrollbar all styled for one OS): Abstract Factory's job is to guarantee that a client gets a consistent set from a single family and never mixes families.

  • What defines a family: Multiple distinct product types (button, checkbox) that share a common variant/theme (Windows vs macOS).

  • One factory produces one whole family: A WinFactory makes only Windows widgets; a MacFactory only macOS ones, so parts always match.

  • Why it matters: consistency: Prevents illegal combinations (a macOS button next to a Windows scrollbar) at the type level.

  • Trade-off: Adding a new product type (a new widget) forces changes to every factory interface, so families work best when the set of product types is stable.

Q25.
How would you decide between the different creational patterns—Factory, Builder, and Prototype—for a given object-creation problem?

Mid

Pick based on what makes creation hard: use a Factory when the problem is choosing among types, a Builder when a single object has a complex step-by-step assembly, and a Prototype when creating from scratch is costly and you already have a configured instance to copy.

  • Factory (Method / Abstract Factory):

    • The client shouldn't know or choose the concrete class; you want to decide the type at runtime and return via a common interface.

    • Abstract Factory when you need a consistent family of related objects.

  • Builder: One complex object with many optional parts or a required assembly order; avoids telescoping constructors and keeps the object valid.

  • Prototype: Instantiation is expensive (heavy setup, DB load) or configurations are known at runtime; clone() an existing instance instead of rebuilding.

  • They compose: A factory can return prototypes, or use a builder internally; the patterns aren't mutually exclusive.

Q26.
How does the Prototype pattern reduce the need for subclassing compared to a factory-based approach?

Mid

Prototype creates new objects by cloning an existing configured instance rather than instantiating a class, so variation lives in object state instead of in a class hierarchy: you avoid the parallel subclass explosion a factory approach can require.

  • Factory ties variants to classes: Each new product variant often needs a new subclass plus a matching branch/creator, growing the hierarchy.

  • Prototype ties variants to instances: Configure an object once, register it as a prototype, and clone() it; new variants are just differently-configured copies, no new class needed.

  • Runtime flexibility: You can add and remove prototypes at runtime, which static class-based factories can't do.

  • Watch out for copy depth: You must decide shallow vs deep copy so clones don't share mutable references unintentionally.

Q27.
What is the difference between an object pool and a Singleton when managing shared or reusable resources?

Mid

Both manage shared resources, but a Singleton guarantees exactly one instance globally, whereas an object pool maintains a managed set of many reusable, interchangeable instances that clients borrow and return.

  • Singleton: one and only one: Enforces single instance and provides a global access point; best for genuinely single-owner state (config, a logger).

  • Object pool: many, reused: Pre-creates/caches expensive objects (DB connections, threads); clients acquire one, use it, and release it back.

  • Concurrency intent differs: A Singleton is shared simultaneously by all callers; a pooled object is typically checked out for exclusive use, then returned.

  • They can combine: The pool manager itself is often a Singleton that hands out many pooled instances.

Q28.
Can you explain the Decorator pattern and how it allows adding functionality to an object at runtime without using inheritance?

Mid

The Decorator pattern wraps an object in another object that shares its interface, adding behavior before or after delegating to the wrapped object: because you compose wrappers at runtime rather than subclassing, you can layer responsibilities in any combination.

  • Same interface, wrapping structure: Decorator implements the same type as its component and holds a reference to one, so clients can't tell a decorated object from a plain one.

  • Adds behavior by delegation: Each wrapper does its extra work then calls the inner object, so effects stack (e.g. compression + encryption on a stream).

  • Runtime composition beats inheritance: Inheritance fixes behavior at compile time and causes a class explosion for every combination; decorators mix freely at runtime.

  • Order can matter: The sequence of wrapping changes the result, and many small wrappers can make debugging harder to trace.

python

class Coffee: def cost(self): return 2.0 class MilkDecorator: def __init__(self, drink): self._drink = drink def cost(self): return self._drink.cost() + 0.5 drink = MilkDecorator(MilkDecorator(Coffee())) print(drink.cost()) # 3.0 - layered at runtime

Q29.
How does the Composite pattern allow you to treat individual objects and groups of objects uniformly through a part-whole hierarchy?

Mid

The Composite pattern gives leaf objects and container objects a common interface, so clients call the same operations on a single item or a whole tree without checking which they hold: composites just forward those calls to their children recursively.

  • One shared component interface: Both Leaf and Composite implement the same type (e.g. render(), getSize()), so clients treat them identically.

  • Composites delegate recursively: A composite implements an operation by looping over its children and calling the same operation, which naturally traverses the tree.

  • Part-whole hierarchy: Models trees like files/folders or UI groups, where a group can contain items and other groups to any depth.

  • Design tension: Child-management methods (add(), remove()) don't fit leaves; you choose between transparency (declared on the interface) and safety (declared only on composites).

Q30.
What are the different types of Proxies such as Virtual, Remote, and Protection, and what problems do they solve?

Mid

A Proxy is a surrogate that stands in for a real object; the type of proxy is named for the access concern it addresses: creating expensive objects lazily, reaching remote ones, or guarding them.

  • Virtual Proxy:

    • Defers creation of an expensive object until it's actually needed (lazy loading).

    • Example: a placeholder for a high-resolution image loaded only when rendered.

  • Remote Proxy:

    • Represents an object living in another address space or machine, hiding network communication.

    • Example: an RPC/RMI stub that marshals calls across the wire.

  • Protection Proxy:

    • Controls access based on permissions or roles before delegating.

    • Example: checking a user's rights before allowing a sensitive operation.

  • Others worth knowing: Smart Reference (adds actions like reference counting or lock management on access) and Caching Proxy (stores results of expensive calls).

Q31.
How does the Bridge pattern decouple an abstraction from its implementation, and can you give a conceptual example where both might need to vary independently?

Mid

Bridge splits one hierarchy into two: an abstraction and an implementation, connected by composition rather than inheritance, so each can be extended independently without a combinatorial explosion of subclasses.

  • The mechanism:

    • The abstraction holds a reference to an implementor interface and delegates the low-level work to it.

    • You subclass the abstraction and the implementor separately, then combine them at runtime.

  • Why it helps: Avoids classes like RemoteWithSonyTV, RemoteWithLGTV: instead you have Remote types and TV types combined freely.

  • Conceptual example: remote controls and devices:

    • Abstraction axis: BasicRemote, AdvancedRemote (varies in features).

    • Implementation axis: TV, Radio (varies in device behavior).

    • Either axis grows without touching the other.

python

class Device: # implementor def enable(self): ... def set_volume(self, v): ... class Remote: # abstraction, holds a Device def __init__(self, device): self.device = device def toggle_power(self): self.device.enable() class AdvancedRemote(Remote): # extends abstraction independently def mute(self): self.device.set_volume(0)

Q32.
How does the Flyweight pattern help reduce memory footprint in applications with a large number of objects?

Mid

Flyweight reduces memory by sharing the common, unchanging part of many objects (intrinsic state) as a single reusable instance, while the varying part (extrinsic state) is passed in or stored externally.

  • Split the state:

    • Intrinsic: shared, context-independent, stored inside the flyweight (e.g. a character's glyph shape and font).

    • Extrinsic: unique per use, supplied by the client (e.g. position on the page).

  • Share instead of duplicate:

    • A factory returns an existing flyweight for a given intrinsic key rather than creating a new object.

    • Millions of logical objects map to a handful of shared physical objects.

  • Classic examples: characters in a text editor, tiles/trees in a game map, particle systems.

  • Trade-off: saves memory but adds complexity, and flyweights must be immutable so sharing is safe.

Q33.
Both Adapter and Facade wrap existing code — what is the difference in their intent?

Mid

Both wrap existing code, but Adapter changes an interface to make incompatible things work together, while Facade simplifies a complex subsystem behind one convenient interface.

  • Adapter: convert one interface to another:

    • Intent is compatibility: the client expects interface A, but the existing class offers B.

    • Usually wraps a single class and doesn't hide complexity, just translates.

  • Facade: provide a simplified entry point:

    • Intent is convenience: hide the interactions of many subsystem classes behind one high-level API.

    • It defines a new, simpler interface rather than matching an existing expected one.

  • Rule of thumb: Adapter is retrofitting for a required interface; Facade is a friendlier front door to a messy subsystem.

Q34.
Explain the difference in intent between the Adapter, Proxy, and Decorator patterns, since they all involve wrapping an object.

Mid

All three wrap an object and often keep it hidden, but their intents are distinct: Adapter changes the interface, Proxy controls access, and Decorator adds behavior.

  • Adapter:

    • Changes the interface of the wrapped object so an incompatible client can use it.

    • Interface in differs from interface out.

  • Proxy:

    • Keeps the same interface but governs access (lazy load, security, remoting).

    • Doesn't add functionality visible to the client, just manages the real object.

  • Decorator:

    • Keeps the same interface but adds responsibilities, and can stack.

    • Enhances what the object does.

  • Quick summary: Adapter = different interface; Proxy = controlled access, same interface; Decorator = added behavior, same interface.

Q35.
What is the purpose of a Facade pattern, and how does it help in adhering to the Law of Demeter?

Mid

A Facade provides a single simplified entry point to a complex subsystem, so clients talk to one object instead of orchestrating many. This directly supports the Law of Demeter by preventing clients from reaching through chains of collaborating objects.

  • Purpose:

    • Wraps a set of subsystem classes behind a higher-level, task-oriented interface.

    • Reduces coupling: clients depend on the facade, not on subsystem internals.

    • Does not hide the subsystem: advanced clients can still use it directly.

  • How it helps the Law of Demeter ("only talk to your immediate friends"):

    • Instead of order.getCustomer().getAccount().charge(), the client calls one facade method.

    • The facade becomes the client's single "friend," and it handles the internal navigation and object chaining.

Q36.
Since a Facade simplifies an interface while an Adapter changes it, explain a scenario where you would use a Facade to wrap a complex third-party library.

Mid

You use a Facade when a third-party library requires a verbose, multi-step ritual to accomplish a common task, and you want your code to depend on one clean method instead of that whole dance. Unlike an Adapter, you are not conforming to a required interface; you are inventing a simpler one for convenience and decoupling.

  • Scenario: a video/PDF/email library:

    • To send an email the library needs you to configure a transport, build headers, encode the body, attach files, then flush.

    • A MailFacade.send(to, subject, body) hides all of that behind one call.

  • Why a facade fits here:

    • There is no pre-existing interface you must match, so it is simplification, not adaptation.

    • It isolates the third-party dependency: swapping libraries later touches only the facade.

    • It centralizes sane defaults and error handling for the common path.

Q37.
How does a Facade differ from a simple utility class, and when does a Facade become 'too big'?

Mid

A Facade differs from a utility class in that it wraps and orchestrates a specific subsystem while holding references to its objects, whereas a utility class is a bag of stateless, unrelated helper functions. A facade becomes "too big" when it stops delegating and starts owning business logic, turning into a god object.

  • Facade vs. utility class:

    • A facade has a clear subject: it fronts one cohesive subsystem and coordinates its parts.

    • A utility class (often static methods) is a grab-bag of generic helpers with no single subsystem behind it.

    • A facade delegates; a utility method usually just computes.

  • Signs a facade is too big:

    • It grows unrelated methods spanning multiple subsystems (low cohesion).

    • It contains real logic instead of delegating, becoming a god object.

    • Fix: split into several focused facades, one per subsystem or use case.

Q38.
How does the Chain of Responsibility differ from the Decorator pattern?

Mid

Both build a chain of wrapping objects, but their intent differs: Chain of Responsibility passes a request along until one handler processes it (and may stop), while Decorator has every wrapper add behavior and always forward to the next.

  • Chain of Responsibility: find a handler:

    • Each link decides whether to handle the request or pass it on.

    • Processing can stop early once a handler takes responsibility.

    • Focus is on who handles, not on accumulating behavior.

  • Decorator: augment behavior:

    • Every wrapper adds its own responsibility and typically calls the wrapped object.

    • All layers contribute; none is meant to "stop" the request.

    • Focus is on enhancing a single result, not routing.

  • Summary: CoR = at most one (or a few) handlers act; Decorator = all layers act.

Q39.
Why does the order in which decorators are wrapped around an object matter?

Mid

Order matters because decorators form a nested pipeline: each layer runs its logic around the call to the one it wraps, so the sequence determines both the ordering of side effects and how each layer transforms the data the next one sees.

  • Nested execution:

    • The outermost decorator runs first and last (before and after delegating), like layers of an onion.

    • Behavior is applied outside-in on the way in and inside-out on the way out.

  • Order changes the result when layers are not commutative:

    • Compress-then-encrypt vs. encrypt-then-compress produce very different (and differently secure) outputs.

    • A caching decorator outside a logging one logs only on cache misses; reversed, it logs every call.

  • When order is safe to ignore: Only if each decorator's effect is independent and commutative, which is rarely guaranteed.

Q40.
What is a Smart Proxy (smart reference), and what kinds of additional behavior does it add when an object is accessed?

Mid

A smart proxy (smart reference) is a proxy that stands in for a real object and executes extra bookkeeping or safety logic every time the object is accessed, on top of just forwarding the call.

  • Same interface as the real subject: Clients use it transparently; the proxy delegates to the real object after doing its own work.

  • Typical additional behaviors:

    • Reference counting: track how many clients hold the object and free it when the count drops to zero.

    • Lazy loading: load a persistent object into memory only on first access.

    • Locking / thread safety: acquire a lock so no other client can mutate the object concurrently.

    • Access checks: verify the object is still valid before dereferencing.

  • Contrast with related proxies: A virtual proxy focuses on lazy creation, a protection proxy on permissions; the smart proxy is the general "do extra work on access" variant.

Q41.
The UML diagrams for Strategy and State look almost identical — conceptually, how does the intent of the State pattern differ from the Strategy pattern?

Mid

They share the same structure (a context delegating to a swappable interface), but the intent differs: Strategy swaps interchangeable algorithms chosen by the client, while State models an object changing behavior as its internal condition changes, often transitioning itself between states.

  • Strategy: interchangeable algorithms:

    • Each strategy solves the same problem a different way (e.g. sort algorithms); they are independent and unaware of each other.

    • The client picks the strategy; it rarely changes during the object's life.

  • State: behavior tied to internal condition:

    • Concrete states represent modes of the object (e.g. Open, Closed); the same request behaves differently per state.

    • States often know about and trigger transitions to other states; changing state happens dynamically at runtime.

  • Litmus test: If the implementations are aware of and drive movement between one another, it's State; if they are independent alternatives selected externally, it's Strategy.

Q42.
How does the Command pattern facilitate undo/redo functionality, and what are the roles of the Invoker and the Receiver?

Mid

The Command pattern encapsulates a request as an object holding all the data needed to execute it, which lets you keep a history of executed commands; adding an undo() method to each command makes reversing operations straightforward.

  • How undo/redo works:

    • Each command stores the state or inverse action needed to reverse itself.

    • Executed commands are pushed onto a history stack; undo pops one and calls undo(), redo re-runs execute().

  • Invoker: Triggers commands and owns the history stack; it knows only the command interface, not what the command does (e.g. a menu button or remote).

  • Receiver: The object that performs the actual work; the command calls the receiver inside execute().

python

class InsertText: def __init__(self, doc, text): self.doc, self.text = doc, text def execute(self): self.doc.append(self.text) # calls the Receiver def undo(self): self.doc.remove_last(len(self.text)) history = [] def run(cmd): cmd.execute(); history.append(cmd) # Invoker def undo(): history.pop().undo()

Q43.
What is the Hollywood Principle, and how does the Template Method pattern embody it using hook methods?

Mid

The Hollywood Principle is "Don't call us, we'll call you": high-level framework code controls the flow and calls down into your code, rather than your code driving the framework. Template Method embodies it by defining the algorithm's skeleton in a base class and calling subclass-provided hook methods at the right points.

  • Inversion of control: The base class owns the sequence; subclasses don't invoke it, they just supply pieces the base class calls.

  • Template method + hooks:

    • The final template method fixes the steps; abstract steps must be implemented, hook methods have default (often empty) behavior subclasses may optionally override.

    • The framework decides when the hook fires; the subclass only decides what it does.

  • Why it matters: Prevents low-level modules from creating dependencies on high-level flow, keeping control centralized and the algorithm consistent.

python

class Report: def generate(self): # template method (the skeleton) self.header() self.body() # subclass must define if self.needs_footer(): # hook: default overridable self.footer() def needs_footer(self): return False # hook default

Q44.
How does the Chain of Responsibility decouple the sender of a request from its multiple potential receivers?

Mid

Chain of Responsibility decouples sender from receiver by passing the request along a chain of handler objects: the sender holds only a reference to the first handler and doesn't know or care which handler ultimately processes it.

  • The sender knows only the chain's head: It issues the request to the first handler; it has no knowledge of the set of receivers or their order.

  • Each handler decides: handle or forward:

    • A handler either processes the request or passes it to its successor via a common interface.

    • Handlers only reference the next link, not the sender, so responsibility is distributed.

  • Benefits of the decoupling:

    • You can add, remove, or reorder handlers at runtime without touching the sender.

    • Trade-off: no guarantee any handler processes the request; it may fall off the end unhandled.

Q45.
What is the Null Object pattern, and how does it help you avoid null pointer checks throughout your business logic?

Mid

The Null Object pattern replaces a null reference with a real object that implements the same interface but does nothing (or returns neutral defaults), so callers can invoke methods safely without checking for null.

  • It provides a "do nothing" implementation:

    • The null object conforms to the same interface/abstract type, so it is a drop-in substitute for a real collaborator.

    • Its methods have benign behavior: empty bodies, zero, empty collections, or identity values.

  • It moves the null check to one place:

    • Instead of scattering if (x != null) across business logic, the factory/lookup returns a null object once.

    • Callers just call methods; polymorphism handles the "absent" case.

  • When to use it:

    • A missing collaborator has a sensible "neutral" behavior (e.g. a NullLogger that discards messages).

    • Not when absence is a real error that should surface: silently doing nothing can hide bugs.

java

interface Logger { void log(String msg); } class NullLogger implements Logger { public void log(String msg) { /* do nothing */ } } // caller never needs a null check Logger logger = config.getLogger(); // returns NullLogger if none set logger.log("processing...");

Q46.
What is the role of the Invoker and the Receiver in the Command pattern?

Mid

In the Command pattern, the Invoker holds and triggers a command without knowing what it does, and the Receiver is the object that actually performs the work when the command executes.

  • Invoker:

    • Stores a command and calls command.execute() on some trigger (button press, menu click, queue).

    • Decoupled from the concrete action: it only knows the Command interface.

  • Receiver:

    • Contains the real business logic (e.g. a Light, Document, or Database).

    • The concrete command calls methods on it inside execute().

  • How they connect:

    • A ConcreteCommand holds a reference to the receiver and binds a request to it.

    • This indirection is what enables queueing, logging, and undo/redo of requests.

java

class Light { void on() { /* real work */ } } // Receiver class LightOnCommand implements Command { private Light light; LightOnCommand(Light l) { this.light = l; } public void execute() { light.on(); } // calls Receiver } class Button { // Invoker private Command command; void press() { command.execute(); } // doesn't know it's a Light }

Q47.
What is the difference between the push and pull models of data notification in the Observer pattern?

Mid

In the push model the subject sends the changed data to observers as part of the notification; in the pull model the subject just signals "something changed" and each observer queries the subject for the details it needs.

  • Push model:

    • Subject passes data in the update call, e.g. update(temperature, humidity).

    • Pros: observers get everything immediately; no back-reference to the subject needed.

    • Cons: subject must assume what observers want, sending possibly irrelevant data; couples the update signature to the state.

  • Pull model:

    • Subject calls a bare update(); observers call getters like subject.getState() to fetch what they care about.

    • Pros: flexible, each observer takes only what it needs; leaner notification interface.

    • Cons: observers must hold a reference to the subject and may make multiple calls.

  • Choosing: Push when the data set is small and uniform; pull when observers need varied or expensive subsets of state.

Q48.
How does the Strategy pattern help a class follow the Open/Closed Principle?

Mid

The Strategy pattern lets a class stay closed for modification but open for extension by delegating a varying algorithm to an interchangeable strategy object: you add new behavior by writing a new strategy class rather than editing the context.

  • The mechanism:

    • The context holds a reference to a Strategy interface and calls it, not concrete logic.

    • Each algorithm lives in its own class implementing that interface.

  • Why that satisfies Open/Closed:

    • Adding a new behavior = adding a new strategy class; the context's code is untouched.

    • Contrast with a big if/else or switch on type, which you must edit (and risk breaking) for every new case.

  • Bonus: Strategies can be swapped at runtime, and each is independently testable.

java

interface DiscountStrategy { double apply(double price); } class Cart { // closed for modification private DiscountStrategy discount; Cart(DiscountStrategy d) { this.discount = d; } double total(double price) { return discount.apply(price); } } // New behavior = new class, no edit to Cart class BlackFriday implements DiscountStrategy { public double apply(double p) { return p * 0.5; } }

Q49.
What is the Hollywood Principle ('Don't call us, we'll call you'), and which behavioral patterns embody it?

Mid

The Hollywood Principle inverts control: low-level code doesn't call the framework or high-level logic; instead the framework holds the flow and calls back into your code at the right moments. It's the essence of inversion of control and underpins hooks, callbacks, and event-driven design.

  • Core idea: Control flow lives with the framework/parent; your components register and wait to be invoked, rather than polling or driving the loop themselves.

  • Patterns that embody it:

    • Template Method: the base class defines the algorithm skeleton and calls your overridden hook steps.

    • Observer: subjects call update() on registered observers when state changes.

    • Strategy and Command: a context invokes the plugged-in object's method when appropriate.

    • Also central to dependency injection and callback-based frameworks generally.

  • Why it matters: Decouples reusable framework code from application specifics: the framework stays stable while your callbacks vary.

Q50.
When would you use a Chain of Responsibility instead of a large if-else or switch block?

Mid

Use Chain of Responsibility when a request may be handled by one of several handlers and you want to decouple the sender from the specific receiver, letting each handler decide to process or pass along. It shines when the set of handlers or their order changes at runtime, where a giant conditional would become rigid and hard to maintain.

  • Good fit when:

    • Multiple objects can handle a request and the handler isn't known until runtime.

    • You want to add, remove, or reorder handlers without touching existing code (open/closed).

    • Handling logic is naturally staged: validation, authentication, logging, then business logic.

  • Advantages over if-else/switch:

    • Each handler is a small single-responsibility class, testable in isolation.

    • The sender knows nothing about which link handles it, reducing coupling.

  • Trade-offs:

    • No guarantee a request is handled (it can fall off the end).

    • Harder to trace/debug flow than a linear conditional; overkill for a small fixed set of branches.

Q51.
What is a fail-fast iterator, and why does modifying a collection during iteration throw a ConcurrentModificationException?

Mid

A fail-fast iterator detects that its underlying collection was structurally modified after the iterator was created and immediately throws rather than risking silent, undefined behavior. In Java, iterators over collections like ArrayList or HashMap do this via a modCount check, throwing ConcurrentModificationException.

  • How it detects modification:

    • The collection keeps a modCount incremented on structural changes (add/remove).

    • The iterator snapshots it as expectedModCount; on each next() it compares, and a mismatch triggers the exception.

  • Why fail fast at all:

    • Mutating during iteration can invalidate indices/pointers, causing skipped or duplicated elements; failing loudly is safer than corrupt results.

    • It's best-effort, not a concurrency guarantee: don't rely on it for thread safety.

  • How to modify safely:

    • Use the iterator's own Iterator.remove() (it updates expectedModCount).

    • Or use fail-safe collections (CopyOnWriteArrayList, ConcurrentHashMap) that iterate over a snapshot.

java

List<String> list = new ArrayList<>(List.of("a","b","c")); for (Iterator<String> it = list.iterator(); it.hasNext();) { if (it.next().equals("b")) it.remove(); // safe } // list.remove("b") during a for-each would throw ConcurrentModificationException

Q52.
What is a macro command (composite command), and how does the Command pattern support composing multiple commands?

Mid

A macro command is a command that holds a list of other commands and executes them in sequence: because every command shares the same interface, a macro is itself just another command (a Composite of commands).

  • Uniform interface enables composition: All commands expose execute() (and often undo()), so a container of commands can be treated exactly like a single one.

  • The macro delegates:

    • Its execute() loops over its children and calls each execute().

    • Undo typically iterates in reverse order calling each child's undo().

  • This is Composite applied to Command: clients invoke one big operation without knowing it is many.

python

class MacroCommand: def __init__(self, commands): self.commands = commands def execute(self): for c in self.commands: c.execute() def undo(self): for c in reversed(self.commands): c.undo()

Q53.
What is the role of the Caretaker in the Memento pattern?

Mid

The Caretaker stores and manages mementos on behalf of the originator, but treats them as opaque: it can hold, hand back, or discard a snapshot without ever reading or modifying its contents.

  • Three roles in the pattern:

    • Originator: creates a memento capturing its state and restores from one.

    • Memento: the opaque snapshot of that state.

    • Caretaker: keeps the mementos (e.g. an undo stack) but never inspects them.

  • Why the caretaker stays blind:

    • Preserves the originator's encapsulation: internal state details never leak.

    • The caretaker only knows the "wide" interface as an opaque token; only the originator sees the "narrow" internals.

  • Typical responsibilities: Deciding when to save, ordering history, and requesting a specific memento back on undo/redo.

Q54.
How does the Chain of Responsibility handle the case where no handler processes a request, and how can you guarantee handling?

Mid

By default, if the request reaches the end of the chain unhandled, nothing happens: the request is silently dropped. To guarantee handling you add a terminal handler or enforce a contract that some handler always processes it.

  • The unhandled case is inherent:

    • Each handler either processes the request or passes it on; the last handler's "pass on" goes nowhere.

    • This loose coupling is a feature (senders don't know who handles) but a risk (silent no-op).

  • Ways to guarantee handling:

    • Add a default / catch-all handler at the tail that always handles (e.g. logs, returns a fallback, or throws).

    • Have the dispatch mechanism detect an unhandled request and raise an exception.

    • Return a boolean/result from the chain so the caller can react when nothing handled it.

  • Design choice: Silent drop is acceptable for optional processing (e.g. event filters); a guaranteed terminal handler suits required processing.

Q55.
Is Dependency Injection the same thing as Inversion of Control? Explain DI as a pattern versus IoC as a principle.

Mid

No, they are not the same: Inversion of Control is the broad principle that a component's flow or dependencies are controlled from the outside, and Dependency Injection is one specific pattern for achieving IoC by supplying a component's dependencies rather than letting it create them.

  • IoC is the principle (the "what"):

    • Control that a component would normally own is inverted to an external party.

    • DI is just one form; others include the Template Method, callbacks/events, and Service Locator.

  • DI is a pattern (the "how"):

    • Dependencies are passed in via constructor, setter, or interface injection instead of being instantiated internally.

    • Benefits: looser coupling, easier testing (inject mocks), and swappable implementations.

  • How they connect:

    • DI achieves IoC specifically for the dependency-acquisition concern.

    • A DI container / framework often automates the wiring, but DI does not require a container: manual constructor injection is still DI.

python

# Not DI: the class controls its own dependency class Service: def __init__(self): self.repo = SqlRepo() # hard-wired # DI: dependency supplied from outside (constructor injection) class Service: def __init__(self, repo): self.repo = repo # inverted control, easy to mock

Q56.
What are the different forms of dependency injection—constructor, setter, and interface/method injection—and how do they differ?

Mid

They differ in how and when the dependency is handed over: through the constructor (at creation), through a setter/property (after creation), or through an interface the client implements to be given the dependency via a callback method.

  • Constructor injection:

    • Dependencies passed as constructor arguments; object is fully valid the moment it exists.

    • Best for required, immutable dependencies (can use final/readonly). The preferred default.

  • Setter (property) injection:

    • Dependency assigned after construction via a setter or property.

    • Good for optional dependencies or reconfiguration, but leaves a window where the object is partially built (risk of null).

  • Interface / method injection:

    • The client implements an interface (e.g. IConfigurable.setService(...)) that the container/caller uses to inject the dependency.

    • Also covers passing a dependency into a single method call. Rare; used by frameworks needing a standard contract.

  • Rule of thumb: constructor for required dependencies, setter for optional ones, interface/method only when a framework demands it.

Q57.
What is the role of an IoC container, and how does it manage the lifecycle of dependencies?

Mid

An IoC (Inversion of Control) container is a framework that automates dependency injection: you register how to build each type, and it resolves the whole object graph for you, wiring dependencies and controlling how long each instance lives.

  • Core responsibilities:

    • Registration: map an abstraction to a concrete implementation or factory.

    • Resolution: build the object and recursively inject its dependencies (auto-wiring).

    • Lifetime management: decide when to create, reuse, and dispose instances.

  • Common lifetimes:

    • Transient: a new instance every time it's requested.

    • Scoped: one instance per logical scope (e.g. per web request).

    • Singleton: one shared instance for the container's lifetime.

  • Lifecycle handling:

    • The container tracks disposable objects and calls Dispose()/close hooks when the scope ends.

    • Captive dependency trap: injecting a scoped/transient into a singleton keeps it alive too long, causing bugs.

  • Benefit: composition happens in one place (the composition root), keeping classes free of wiring logic.

Q58.
What is the purpose of the Repository pattern, and how does it differ from a Data Access Object (DAO)?

Mid

The Repository pattern provides a collection-like abstraction over your domain objects, hiding how they're stored so business code works with objects, not queries. A DAO is a lower-level abstraction focused on data access to a specific table or source; a repository is more domain-oriented and often sits above DAOs.

  • Purpose of Repository:

    • Acts like an in-memory collection of aggregates: add, remove, findById.

    • Decouples domain/business logic from persistence tech, aiding testing and swappable storage.

  • How DAO differs:

    • DAO is data-centric: usually one DAO per table/entity, exposing CRUD close to the storage schema.

    • Repository is domain-centric: works with aggregates and may compose several data sources/DAOs.

  • Level of abstraction:

    • DAO thinks in rows and tables; Repository thinks in domain objects and business intent.

    • In practice the terms overlap heavily, and many teams use them interchangeably.

Q59.
What is the difference between Model-View-Controller (MVC) and Model-View-ViewModel (MVVM), and how does data binding work in MVVM?

Mid

Both separate UI from logic, but they differ in the middle layer and how the View is updated. In MVC a Controller handles input and updates the Model/View; in MVVM a ViewModel exposes bindable state and commands, and data binding keeps View and ViewModel in sync automatically, so there's little glue code.

  • MVC:

    • Controller receives user input, manipulates the Model, selects a View to render.

    • View updates are often driven explicitly by the Controller.

  • MVVM:

    • ViewModel exposes properties and commands representing View state, with no reference to the View.

    • View binds declaratively to those properties; the ViewModel is highly testable in isolation.

  • How data binding works in MVVM:

    • The View subscribes to change notifications (e.g. INotifyPropertyChanged) so UI updates when a property changes.

    • Two-way binding pushes user edits back into the ViewModel automatically, eliminating manual sync code.

Q60.
In the context of modern UI frameworks, what is the difference between the Controller in MVC and the ViewModel in MVVM?

Mid

In modern UI frameworks the key difference is coupling and direction: a Controller actively orchestrates the View and handles requests, while a ViewModel is a passive, View-agnostic state holder that the View binds to. The Controller pushes; the ViewModel is pulled from.

  • Controller (MVC):

    • Handles incoming input/requests, coordinates the Model, and chooses/updates a View.

    • Often aware of the View and imperatively drives it.

  • ViewModel (MVVM):

    • Exposes bindable state and commands; has no reference to the View at all.

    • Updated indirectly: the View binds to it, and change notifications flow back automatically.

  • Consequences:

    • ViewModels are easier to unit test because there's no View dependency to fake.

    • Controllers suit request/response and imperative UI flow; ViewModels suit reactive, binding-driven UIs.

Q61.
What are the key differences between MVP and MVC, and what role does the Presenter play?

Mid

Both split UI from logic, but MVC's view can read the model directly while MVP fully decouples them: the Presenter sits in the middle, so the view is a passive, dumb surface that only reports events and displays what it's told.

  • Flow of communication:

    • MVC: the controller updates the model, and the view observes/reads the model directly to refresh itself.

    • MVP: the view never touches the model; all data passes through the Presenter.

  • View responsibility:

    • MVC view holds some presentation logic.

    • MVP view is passive: it exposes an interface and delegates every action to the Presenter.

  • Relationship cardinality:

    • MVC: one controller can serve multiple views.

    • MVP: usually one Presenter per view (1:1).

  • Role of the Presenter:

    • It retrieves data from the model, formats it, and pushes it into the view via the view's interface.

    • Because it talks to the view through an abstraction, it is highly testable: you can mock the view and unit-test presentation logic without any UI.

Q62.
Explain how the Iterator pattern is used in modern language features like foreach loops or Java Streams, and why it is better than a standard for loop for complex data structures.

Mid

The Iterator pattern gives a uniform way to traverse a collection without exposing its internal representation, and language features like foreach and Java Streams are built directly on it: the loop just asks for the next element and doesn't care whether it's backed by an array, a tree, or a lazy pipeline.

  • How the feature maps to the pattern:

    • foreach desugars into obtaining an iterator and calling hasNext/next (Java) or MoveNext()/Current (C#).

    • Java Streams traverse via a Spliterator, an iterator variant that also supports splitting for parallelism.

  • Why it beats a manual for loop for complex structures:

    • Index-based loops only fit sequential, indexable data; a tree, graph, or hash set has no meaningful index.

    • The iterator hides traversal order and structure, so the same loop works across list, set, tree, or generated sequence.

    • It supports lazy/infinite sources: elements are produced on demand rather than requiring a known size up front.

    • Less off-by-one and bounds error surface, since you never manage indices by hand.

Q63.
How do you decide which design pattern to apply when faced with a new problem?

Senior

Start from the problem, not the pattern: identify what varies, what's rigid, and what kind of relationship or creation concern is causing pain, then match that to a pattern's intent.

  • Categorize the problem: Creational (how objects are made), Structural (how they're composed), or Behavioral (how they interact) narrows the search fast.

  • Identify what varies: The GoF principle "encapsulate what varies": isolate the changing part behind an interface and pick the pattern that abstracts that axis of change.

  • Match on intent, not structure: Many patterns share class diagrams (e.g. Strategy vs State) but differ in purpose; read the "Intent" section, not just the UML.

  • Prefer the simplest thing that works: Don't reach for a pattern speculatively; apply it when duplication, rigidity, or a real change forces it (refactor toward patterns).

  • Weigh the cost: Every pattern adds indirection; adopt it only if the flexibility earns its added complexity.

Q64.
Why is the Singleton pattern often criticized as an anti-pattern in modern development, and how does it affect unit testing and global state?

Senior

Singleton is criticized because it is essentially global state in disguise: it creates hidden dependencies, tightly couples code to a concrete instance, and makes unit tests unpredictable and hard to isolate.

  • It is global state: Any code can reach it, so mutations create action-at-a-distance bugs and unclear ownership.

  • Hidden dependencies: A class calling Singleton.getInstance() internally hides its dependency from its constructor/signature, violating explicit dependency injection.

  • Tight coupling: Code depends on a concrete class, not an interface, so you can't swap implementations.

  • Unit-testing problems:

    • Hard to mock/replace, since callers grab the instance directly.

    • State persists across tests, breaking isolation and causing order-dependent failures unless reset.

  • Better alternative: Keep a single instance if needed, but manage its lifetime with a DI container and inject it via an interface: you get one instance plus testability.

Q65.
Explain the different ways to achieve thread-safety in a Singleton. What is double-checked locking, and why do we need the volatile keyword?

Senior

Thread-safety in a Singleton means guaranteeing only one instance is created even under concurrent access. The main strategies are eager initialization, synchronized access, double-checked locking, and the recommended language-idiomatic approaches (holder idiom or enum in Java).

  • Eager initialization: Create the instance at class load (static final): inherently thread-safe, but built even if never used.

  • Synchronized accessor: Lock the whole getInstance(): correct but slow, since every call pays lock cost.

  • Double-checked locking: Check for null, synchronize only if null, then check again inside the lock: locks only during first creation, fast afterward.

  • Why volatile is needed:

    • Object construction is not atomic: the reference can be assigned before the object is fully initialized (instruction reordering).

    • Without volatile, another thread could see a non-null but half-constructed instance; volatile enforces visibility and prevents that reordering.

  • Preferred idioms:

    • Initialization-on-demand holder: lazy and thread-safe via class-loading guarantees, no explicit locking.

    • An enum singleton (Java): concise, serialization- and reflection-safe.

java

public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { // first check (no lock) synchronized (Singleton.class) { if (instance == null) { // second check (locked) instance = new Singleton(); } } } return instance; } }

Q66.
Which design patterns are commonly combined or used together, and can you give an example such as Abstract Factory using Factory Method or Prototype?

Senior

Patterns are routinely combined because each solves one concern; real designs layer them. A classic case is Abstract Factory, whose creation methods are often implemented as Factory Methods, or sometimes as Prototypes that clone pre-configured instances.

  • Abstract Factory + Factory Method: The abstract factory declares product-creation operations; concrete factories implement each as a Factory Method returning a family member.

  • Abstract Factory + Prototype: Instead of subclassing per product, the factory holds prototypes and returns clones, keeping the factory count down.

  • Composite + Iterator / Visitor: Iterator traverses a Composite tree; Visitor applies operations across its nodes without bloating the node classes.

  • Decorator + Factory / Builder: A factory or builder assembles the wrapping chain so clients don't hand-nest decorators.

  • Command + Memento + Composite: Undo systems: Command encapsulates actions, Memento captures state to restore, and a Composite (macro) command groups them.

  • Flyweight + Factory: A factory caches and shares flyweight instances rather than creating duplicates.

  • Strategy + Factory: A factory selects and returns the appropriate Strategy implementation at runtime.

Q67.
What is the difference between intrinsic and extrinsic state in the Flyweight pattern, and how does this pattern help in memory-constrained environments?

Senior

Intrinsic state is the shared, context-independent data stored inside a flyweight; extrinsic state is the context-dependent data passed in by the client at call time: separating them lets many logical objects share one physical instance, saving memory.

  • Intrinsic state (shared): Immutable and reusable across contexts (e.g. a character glyph's shape and font); stored once in the flyweight.

  • Extrinsic state (unique): Varies per use (e.g. a glyph's position on the page); supplied by the client as a parameter, never stored in the flyweight.

  • How it saves memory: Instead of millions of full objects, you keep a small pool of shared flyweights and pass the varying data in, cutting object count dramatically.

  • Trade-off: You trade memory for computation/complexity: clients must track and supply extrinsic state, and flyweights must stay immutable to be safely shared.

Q68.
How do the intents of the Decorator pattern and the Proxy pattern differ, given they look similar structurally?

Senior

Structurally both wrap an object and forward calls, but their intent differs: Decorator adds new behavior, while Proxy controls access without changing behavior.

  • Decorator: enhances responsibility:

    • Wraps to add behavior (logging, buffering, formatting) and can be stacked recursively at runtime.

    • The client knowingly composes decorators to build up features.

  • Proxy: controls access:

    • Wraps to manage the lifecycle or access of the real subject (lazy creation, permission checks, remoting).

    • The interface stays identical; the client usually doesn't know a proxy stands in for the real object.

  • Key contrast: Decorator asks "what more can this object do?"; Proxy asks "should and how should this object be reached?"

Q69.
What is the difference between a Class Adapter and an Object Adapter?

Senior

Both make an adaptee usable through a target interface, but a Class Adapter uses inheritance (multiple inheritance) while an Object Adapter uses composition, holding a reference to the adaptee.

  • Class Adapter (inheritance):

    • Inherits from both the target and the adaptee, overriding as needed.

    • Requires multiple inheritance, so limited in languages like Java (can only extend one class); commits to one concrete adaptee at compile time.

  • Object Adapter (composition):

    • Implements the target and holds an instance of the adaptee, delegating calls to it.

    • More flexible: works with any subclass of the adaptee and follows "favor composition over inheritance."

  • Practical takeaway: the Object Adapter is usually preferred, especially in single-inheritance languages, because it's more flexible and less tightly coupled.

Q70.
Both Adapter and Bridge provide indirection — what is the difference in their intent (fixing an existing interface vs. decoupling abstraction from implementation)?

Senior

Both wrap one object in another, but their intent and timing differ: Adapter reconciles an incompatible interface after the fact, while Bridge is designed up front to let an abstraction and its implementation vary independently.

  • Adapter: fix an existing mismatch:

    • Reactive/retrofitting: you have a class whose interface a client cannot use, so you wrap it to make it conform.

    • Applied after both sides already exist and were designed independently.

  • Bridge: decouple abstraction from implementation:

    • Proactive/planned: split a hierarchy into two (abstraction and implementor) so each varies without a combinatorial subclass explosion.

    • Example: Shape abstraction holding a Renderer implementor, so shapes and renderers grow separately.

  • Key contrast:

    • Adapter changes an interface to match a client; Bridge preserves interfaces but lets both dimensions evolve.

    • Adapter is a fix; Bridge is a design decision made before coding.

Q71.
In the Composite pattern, what is the trade-off between transparency and safety when placing child-management methods in the component interface?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q72.
How does the Bridge pattern differ from the Strategy pattern, given both use composition?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q73.
What is a two-way adapter, and when would you need one?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q74.
Is the Observer pattern the same as Publish-Subscribe? Explain the role of the Message Broker or Event Bus in the Pub-Sub model that isn't present in a standard GoF Observer.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q75.
What is Double Dispatch, and why is the Visitor pattern necessary to achieve it in languages that only support single dispatch?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q76.
When would you use a Mediator to coordinate complex interactions between objects instead of having them observe each other directly?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q77.
How does the Memento pattern allow capturing and restoring an object's internal state without violating encapsulation?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q78.
Can you explain the difference between an internal iterator and an external iterator?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q79.
How does the Template Method use inheritance to achieve what the Strategy pattern achieves through composition?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q80.
What is the Interpreter pattern, and what kind of problem is it designed to solve?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q81.
When would you choose the Interpreter pattern over simply writing a parser, and what are its drawbacks?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q82.
What is the difference between the Strategy pattern and the Command pattern, since both encapsulate behavior?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q83.
How does the Mediator pattern differ from the Facade pattern?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q84.
What is the lapsed listener problem, and how can the Observer pattern cause memory leaks?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q85.
What is the main drawback of the Visitor pattern when you need to add new element types to the hierarchy?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q86.
In the State pattern, who is responsible for triggering state transitions—the context or the state objects—and what are the trade-offs?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q87.
How does the Factory Method pattern relate to the Template Method pattern?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q88.
Can you compare the Dependency Injection pattern with the Service Locator pattern, and explain why Service Locator is sometimes considered an anti-pattern?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q89.
What is the Unit of Work pattern, and how does it coordinate multiple Repository operations into a single transaction?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q90.
Explain the flow of data and dependency directions in MVC, MVP, and MVVM, and which one is most suitable for data binding.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q91.
Can you identify a design pattern used in a popular framework like Spring's Bean Factory or React's Higher-Order Components and explain why it was used?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q92.
How does the middleware in frameworks like Express.js or ASP.NET Core relate to the Chain of Responsibility or Decorator patterns?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q93.
In Java or C#, how does the Streams/LINQ API utilize the Iterator or Decorator patterns?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q94.
How does a framework like Spring use the Factory and Singleton patterns under the hood to manage Beans?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.