Design patterns: creational, structural and behavioral – Server Side interview prep

261 interview-style multiple-choice questions on Design patterns: creational, structural and behavioral, organized by topic: concepts, scenarios, code to read and tradeoffs, each with a short explanation. Learn the 140 key terms with the flashcards first, then test yourself.

Take the practice test · Flashcards · All study tools

What it covers

  1. 14.1 Creational patterns
  2. 14.2 Adapter, Facade, Proxy and Decorator
  3. 14.3 Composite, Bridge, Flyweight and other structures
  4. 14.4 Strategy, Template Method, State and Command
  5. 14.5 Observer, Mediator, Iterator and other behaviors
  6. 14.6 Enterprise application patterns
  7. 14.7 Functional and framework idioms
  8. 14.8 Anti-patterns and pattern misuse
  9. 14.9 Choosing and comparing patterns

Key terms

14.1 Creational patterns

Factory Method
Defers which class to create to a method or subclass
Singleton
Ensures one instance with global access
Builder
Step-by-step construction of complex objects
Abstract Factory
Creates families of related objects
Simple factory
One method choosing a class
Telescoping constructor
Many overloads
Director
Runs builder steps in order
Enum singleton
JVM-guaranteed single instance
Prototype registry
Clone preconfigured objects by key
Multiton
One instance per key
Registry factory
Map of keys to creators
Step builder
Typed required steps
Static factory names
of, from, valueOf

14.2 Adapter, Facade, Proxy and Decorator

Adapter
Converts one interface to another
Decorator
Adds behavior by wrapping
Facade
Simple front for a complex subsystem
Proxy
Stand-in controlling access to an object
Object adapter
Holds and delegates to adaptee
Class adapter
Inherits from adaptee
Remote proxy
Local stand-in for a remote object
Virtual proxy
Delays expensive creation
Protection proxy
Checks access first
Smart reference
Bookkeeping on access
ORM proxy
Generated lazy-loading subclass
JavaScript Proxy
Traps on object operations
Decorator order
Wrapping order changes results
Stream decorators
Buffered, decoding wrappers
Base decorator
Forwards everything by default
Facade drift
Grows into a god object

14.3 Composite, Bridge, Flyweight and other structures

Transparency vs safety
Child methods on all nodes or not
Composite rule
And/Or rules nesting
Cycle in composite
Infinite recursion
Bridge example
Remote × device
JDBC
API with vendor drivers
Pimpl
Pointer to hidden implementation
Intrinsic state
Shared inside flyweight
Extrinsic state
Supplied per use
Integer cache
Shared small boxed values
String interning
One instance per value
Flyweight factory
Returns cached instances
Extension Object
Add interfaces later
Leaf/composite
Worker vs container
AWT peers
Platform implementations

14.4 Strategy, Template Method, State and Command

Strategy
Interchangeable algorithms behind one interface
Observer
Subscribers notified of changes
Command
Request wrapped as an object
State
Behavior that changes with internal state
Strategy selection
Client or config picks
Stateless strategy
Shared single instance
Hook method
Optional overridable step
Final template method
Fixed step order
HttpServlet.service
Calls doGet/doPost
State successor
State picks next state
Transition table
States and events as data
State persistence
Store an identifier
Undoable command
Execute and Undo
Macro command
Commands run as one
Command roles
Client, invoker, receiver
Command log
Replay after crash

14.5 Observer, Mediator, Iterator and other behaviors

Push vs pull observer
Data in notice vs read later
Observer error isolation
One failure shouldn't stop others
Reactive stream
Observer plus completion and operators
Dialog mediator
Coordinates widgets
External vs internal iterator
Caller drives vs collection drives
Caretaker
Stores mementos unopened
Snapshot vs inverse
Memento vs Command undo
Default handler
End of the chain
accept/visit
Double dispatch
AST visitor
Operations over syntax trees
Interpreter
Grammar rules as classes
Parser generator
Builds parsers from grammars

14.6 Enterprise application patterns

Repository
Collection-like abstraction over data access
Unit of Work
Commits a set of changes together
Anemic domain model
Data-only classes with logic elsewhere
Null Object
Do-nothing object replacing null
PoEAA
Fowler's enterprise patterns
Active Record
Row object with its own persistence
Data Mapper
Separate mapper layer
Transaction Script
Procedure per operation
Table Module
Logic per table
Service Layer
Application operations boundary
Table/Row Data Gateway
SQL per table or row
Gateway
Wrapper for external systems
Query Object
Criteria as an object
Specification
Business rule object
Special Case
Subclass instead of null
Money allocation
Split without losing cents
Ghost
Partly loaded object
Front Controller
One entry handler
Identity Field
Object stores its row key
Separated Interface
Interface apart from implementation
Serialized LOB
Object graph in one column
Embedded Value
Value object in owner's table
Association table
Many-to-many join table

14.7 Functional and framework idioms

Patterns as functions
Strategy, Command as lambdas
Norvig on patterns
16 of 23 simpler in dynamic languages
Execute around
Acquire, lend, release
Pipes and filters
Chained processing steps
Railway-oriented programming
Results skip steps on failure
Fluent interface
Chainable calls
JdbcTemplate
Callback-based template
by lazy
Delegated lazy property
Newtype
Distinct wrapper type
Typestate
State encoded in types
Type-safe builder
Lambda-with-receiver DSL
singledispatch
Type-based generic function
Type erasure
Uniform type over many callables
Policy-based design
Strategies as template parameters
Stackable traits
Layered mixins
JDK vs CGLIB proxy
Interface vs subclass
ServiceLoader
Interface implementation discovery
IObservable
Push-based observer contract
Lens
Nested immutable updates

14.8 Anti-patterns and pattern misuse

Golden hammer
One tool for every problem
Poltergeist
Stateless go-between class
Lava flow
Hardened dead code
Boat anchor
Unused component kept around
Cargo cult programming
Copying form without understanding
Lapsed listener
Leaked observer
Unhandled chain request
Falls off the end
Call super
Overrides must call parent
Constant interface
Interface holding constants
Inner-platform effect
Reimplementing the platform
Soft coding
Logic moved into config
Magic pushbutton
Logic in UI handlers
Reinventing the square wheel
Worse rebuild of a solved problem
Accidental complexity
Complexity from the solution

14.9 Choosing and comparing patterns

Decorator vs Proxy
Add behavior vs control access
Adapter vs Facade
Fit one interface vs simplify many
Bridge vs Adapter
Designed up front vs retrofit
State vs Strategy
Self-changing vs client-chosen
Observer vs Mediator
Broadcast vs coordinate
Composite vs Decorator
Many children vs one wrapped object
Builder vs Abstract Factory
One complex object vs families
Flyweight vs Singleton
Many keyed vs exactly one
Facade vs Mediator
One-way vs two-way
Repository vs DAO
Domain collection vs table access
Refactoring to Patterns
Let patterns emerge
Pattern language
Alexander's idea behind GoF
GoF categories
Creational, structural, behavioral

Sample practice questions

  1. What problem does the Factory Method pattern solve?

    1. Converting one class's interface into another one clients expect
    2. Making sure a class can only ever have a single shared instance
    3. Deferring which concrete class to create, so callers see only an interface
    4. Creating new objects by cloning an existing prototype instance

    Answer: C. Deferring which concrete class to create, so callers see only an interface Callers ask for an `INotifier` without knowing whether it's email or SMS.

  2. What does the Adapter pattern do?

    1. Puts a simple interface in front of a complex subsystem
    2. Adds behavior to an object without changing its class
    3. Converts one interface into the one clients expect
    4. Controls access to another object as its stand-in

    Answer: C. Converts one interface into the one clients expect Wrapping a third-party SDK behind your own interface is a common use.

  3. Which pattern lets you treat single objects and groups of objects the same way, such as files and folders?

    1. Composite
    2. Builder
    3. Singleton
    4. Adapter

    Answer: A. Composite Both a file and a folder can answer `GetSize()`.

  4. What does the Strategy pattern do?

    1. Notifies a list of observers whenever an object's state changes
    2. Swaps interchangeable algorithms behind one interface at runtime
    3. Builds a complex object step by step through a fluent API
    4. Saves an object's state so that it can be restored later

    Answer: B. Swaps interchangeable algorithms behind one interface at runtime Different shipping-cost calculators are a classic example.

  5. Which pattern is ASP.NET Core middleware or a Java servlet filter chain closest to?

    1. Singleton: one shared handler serves every request
    2. Flyweight: handlers share state to save memory
    3. Chain of Responsibility: each handler acts or passes on
    4. Prototype: each request clones a template handler

    Answer: C. Chain of Responsibility: each handler acts or passes on Each component can handle the request or pass it on.

  6. What is the Unit of Work pattern?

    1. A way of measuring how productive each developer on a team is
    2. Tracking changes in an operation and committing them in one transaction
    3. Running exactly one automated test at a time to avoid interference
    4. Splitting a large job into equal parts for several workers to process

    Answer: B. Tracking changes in an operation and committing them in one transaction EF Core's `DbContext` acts as a unit of work.

  7. Which GoF patterns often shrink to plain functions in languages with first-class functions?

    1. Strategy, Command and Template Method, which become passed-in lambdas or callbacks
    2. Facade, Proxy and Adapter, which become compiler flags set at build time
    3. Composite, Flyweight and Bridge, which become global variables shared by modules
    4. Singleton, Prototype and Abstract Factory, which become database tables

    Answer: A. Strategy, Command and Template Method, which become passed-in lambdas or callbacks The idea stays; the ceremony disappears.

  8. What's a common anti-pattern when learning design patterns?

    1. Writing unit tests for the classes that implement patterns
    2. Naming classes after the design patterns that they implement
    3. Using the Strategy pattern anywhere at all in production code
    4. Using patterns where they aren't needed, adding needless indirection

    Answer: D. Using patterns where they aren't needed, adding needless indirection Patterns are solutions to recurring problems, not goals.

  9. Decorator and Proxy both wrap an object with the same interface. How do their intents differ?

    1. Decorator works only on interfaces; Proxy works only on concrete classes with no interface
    2. Decorator adds behavior; Proxy controls access to the real object, like lazy loading or permissions
    3. Decorator runs at compile time; Proxy runs only at runtime through reflection
    4. Decorator changes the interface; Proxy always removes methods from the interface

    Answer: B. Decorator adds behavior; Proxy controls access to the real object, like lazy loading or permissions The structure is nearly identical; the purpose isn't.

  10. What is the Singleton pattern, and what's a common criticism of it?

    1. A way to create many objects cheaply; it wastes memory
    2. A pattern for single-threaded code; it can't scale out
    3. A class with only one method; it's too small to be useful
    4. One global instance; it hides dependencies and hampers testing

    Answer: D. One global instance; it hides dependencies and hampers testing DI containers with a singleton lifetime give one instance without global state.

Practice all 261 questions

More Server Side