Software Design Patterns in Java
Glossary
122 terms from Software Design Patterns in Java, in plain words, each with the chapter that teaches it.
#
- @Autowired
- A Spring annotation telling the framework to find the needed object and pass it to the constructor. It is dependency injection done by the framework.
- @BeforeEach
- A JUnit annotation marking a method that the framework runs before every test. It is used to build a fresh repo for each test.
A
- Abstract class
- A class marked `abstract` that exists only to be inherited from. It can contain abstract methods with no body, and each child must write them. `new Report()` won't compile because `Report` is abstract.
- Abstract factory
- An interface with several make methods that builds a whole family of related parts. One example is a carrier plus a label printer for the same shipping company.
- Adapter
- A small class that holds an outside library object and offers the interface your code expects, translating each call. `UpsCarrier` turns UPS's cents-based `UpsApi` into dollar quotes.
- Annotation
- A label written `@Name` above a class or method that tools and frameworks read. JUnit's `@Test` and Spring's `@GetMapping` are examples.
- Anti-pattern
- A common answer to a design problem that looks reasonable but causes more trouble than it solves. Naming them, such as god object, lets a team talk about them quickly.
- ArrayDeque
- A Java collection that works well as a stack: `push` adds on top and `pop` removes the top. The cart's undo history uses it.
- AutoCloseable
- A Java interface for objects that have a `close()` method. try-with-resources calls it automatically when its block ends.
B
- Behavioral pattern
- A pattern about how objects share work and make decisions. Strategy and Observer are examples.
- BigDecimal
- A Java class for exact decimal numbers, often used for money instead of `double` because `double` can introduce tiny rounding errors. Kettle & Crane's examples use `double` dollars for simplicity, which doesn't change how any pattern works.
- Builder
- A pattern where a helper object collects an object's parts one call at a time, then checks them and makes the finished object in `build()`. `OrderBuilder` refuses to build an order with no items.
C
- Cache
- Saved answers kept so the real work isn't repeated. `CachedCarrier` remembers a quote per item count so UPS is asked only once.
- Chain of responsibility
- A pattern where a request passes along a line of handlers, and each one deals with it (here, rejects it) or passes it on. Checkout checks such as `hasItems` and `knownCarrier` run this way.
- Characterization test
- A test that records what existing code does today, right or wrong, so a redesign can't change that behavior by accident. For example, tests that pin an old order module's totals of 467.5, 42.6 and 31.25 prove a rewrite still gives the same answers.
- Class explosion
- Needing a new class for every mix of choices, so the number of classes multiplies. `GiftWrappedWholesaleProduct` is the example.
- Clock (injected clock)
- A `Supplier<Instant>` passed into code that needs the time. A test passes a fixed time and `main` passes the real `Instant::now`.
- Cohesion
- How well the things inside one piece of code belong together. A method that only works out shipping has high cohesion.
- Command
- A pattern that turns an action into an object with `run` and `undo`. Stored commands let you build an Undo button, a history or a queue.
- Comparator
- A Java object or lambda that says how to order two items. It is the varying rule you hand to `sort`, which makes it a strategy.
- Composite
- A pattern where a single item and a group answer the same method, and the group asks each part and adds up the answers. A `Bundle` and a `Single` both have `price()`.
- Composition
- Building an object from smaller part objects it holds and delegates to ("has-a"). A `Product` has a pricing part and a wrapping part.
- Composition root
- The one place in a program, usually `main`, that builds the real parts and passes them to the code that needs them. Keeping all this wiring in one spot lets the rest of the code receive its dependencies and stay easy to test.
- computeIfAbsent
- A `Map` method that runs a lambda to create and store a value only when the key is missing. The event bus uses it to start a new empty listener list.
- Constructor injection
- Passing an object its dependencies through its constructor, to keep for its whole life. `OrderLog` receives its repo, clock and notifier this way.
- Consumer
- A Java functional interface for a function that takes a value and returns nothing, called with `accept`. Observer listeners are `Consumer<Order>`.
- Copy constructor
- A constructor that builds a new object by copying another one, including any mutable list inside. It does the prototype pattern's job for classes that aren't records.
- Copy-paste programming
- Repeating the same code in many places, so a fix must be made in each one and one is always missed. The fix is one shared function.
- Coupling
- How much one piece of code depends on another's details. If shipping code reaches inside discount code, changing one may break the other, so you want loose coupling.
- Creational pattern
- A pattern about how objects get made. It puts the decision of which class and which settings in one place.
D
- Decorator
- A wrapper that implements the same interface as the object it wraps, does a little extra work and passes the call on. `LoggedCarrier` logs each quote.
- Delegation
- Handing a job to another object you hold instead of doing it yourself. `Product.total` asks its pricing and wrapping parts.
- Dependency
- Anything a piece of code needs to do its job, such as a database, a notifier or the clock.
- Dependency injection
- Giving code its dependencies instead of letting it create or find them. A test can then pass in fakes, so it needs no disk or real clock.
- Dependency inversion principle (DIP)
- The SOLID rule that high-level code and low-level details should both depend on an interface, with the detail passed in. `confirmOrder` depends on `Notifier`, not on printing.
- Design pattern
- A named, reusable solution shape for a common design problem. It is not a library or copyable code.
- DI container
- A library that builds objects and their dependencies from a set of rules. Spring is the best-known Java one.
- DoubleUnaryOperator
- A Java functional interface for a function from one `double` to another, called with `applyAsDouble`. Each discount strategy is one.
- Duck typing
- Using any object that has the right methods, whatever its class. Java checks this with interfaces instead.
E
- Easy to change
- The goal of design: each business change touches one small, obvious place and nothing else breaks.
- Eclipse Temurin
- A free build of the Java Development Kit (JDK), the tools needed to compile and run Java. It is available for JDK 21, a long-term support release.
- enum
- A Java type with a fixed set of constants. A single-constant enum is the simplest safe singleton.
- Event bus
- The subject in an observer setup: an object where listeners register with `on` and which calls them all with `emit` when an event happens. The code that emits an event doesn't need to know which listeners are registered.
F
- Facade
- One simple method or class in front of several parts, so callers make one call and only the facade knows the steps. `checkout` and `OrderService` are facades.
- Factory method
- A pattern where a parent class has an abstract method that makes a part, and each subclass overrides it to choose which object to make. `SaverShipment` returns a `UspsCarrier`.
- Fake
- A simple working stand-in for a real part, such as `MemoryRepo` or a notifier that keeps messages in a list.
- Filter (servlet filter)
- A handler every web request passes through first, which may log it, check a login or stop it. Filters form a chain.
- Fixture
- Setup code that gives each test fresh parts so tests can't affect one another. For example, a `service()` helper can build a new `OrderService` with an empty repository for every test.
- Fragile base class
- A parent class that its children depend on so closely that changing it quietly breaks them. Adding sales tax to `Product.total` would wrongly tax wholesale children.
- Framework
- Code that runs your program and calls your code at the right moments, like JUnit or Spring. A library is the opposite: your code calls it.
- Function (java.util.function.Function)
- A Java functional interface for a function that takes one value and returns another, called with `apply`. It is the template method's hook in `makeReport`.
- Functional interface
- An interface with just one method, which a lambda or method reference can fill. A one-method `Pricing` part can be a plain function.
G
- Gang of Four
- The nickname of the four authors of the 1994 book *Design Patterns*, which named 23 patterns.
- Global mutable state
- Static data that any code can change, such as the old `orders` list or a changeable singleton. Tests then affect one another and results depend on test order.
- God object
- One class that does far too much, such as a `Shop` class with 40 methods. Split it by reason to change.
- Golden hammer
- Using one favorite tool, such as a factory or class hierarchy, for every problem.
H
- Handler
- One link in a chain of responsibility. It deals with a request or passes it on.
- Has-a / is-a
- Composition says a product has a pricing rule; inheritance says a wholesale product is a product. Choose inheritance only when the child truly is a kind of the parent.
- Hook
- The step a template method leaves for the caller or a subclass to supply, such as the row-format function in `makeReport`.
I
- Immutable
- An object whose fields can't change after it is made. Records are immutable, so to "change" one you build a new record, as in `withQty`.
- Inheritance
- A way for a child class to reuse its parent's code with `extends`. It suits true, shallow "is a" cases but deep trees cause class explosion.
- Instant
- A Java class for a moment in time. `Instant.now()` is the real current time, and `Instant.parse` makes a fixed one for tests.
- Interface
- The set of methods an object promises to have, whatever its class. Java writes it with `interface`, and each class says `implements`.
- Interface segregation principle (ISP)
- The SOLID rule that code shouldn't depend on methods it doesn't use, so keep interfaces small. `Quoter` and `Tracker` are separate.
- Inversion of control
- A framework calling your code instead of your code calling it, summed up as "don't call us, we'll call you". JUnit finds and runs your tests.
- Iterator
- An object that steps through a collection one item at a time without showing how it's stored. Every for-each loop uses one.
J
- javac
- The Java compiler command, which turns `.java` source files into runnable class files. Running `javac *.java` compiles all the files in a folder together, so a command like `java Main` can then run the program.
- JSON
- A plain-text format for structured data. The old code writes orders to `orders.json`, building the text by hand.
- JUnit
- A Java testing framework that finds methods marked `@Test`, runs them and checks the results. Tests can also use a tiny hand-written `check` helper to print PASS or FAIL without it.
- JVM
- The program that runs Java code. It creates an enum constant exactly once, which makes enum singletons safe.
K
- KISS
- "Keep it simple": of two working designs, choose the one that's easier to read.
L
- Lambda
- A short unnamed function written inline, such as `subtotal -> subtotal * 0.9`. Lambdas often replace small strategy classes, since they can be passed around as values.
- Library
- A set of tools your code calls when it wants to, like `sort` or `Files.write`.
- Liskov substitution principle (LSP)
- The SOLID rule that a child class must work anywhere its parent works. `LockedCard` breaks it by throwing in `topUp`.
- Listener
- A lambda or object that is called when an event it subscribed to is emitted, such as `sendEmail` on `order_placed`.
M
- Magic number
- A number in code with no name saying what it means, like `75` and `0.85` in the old `placeOrder`. A named constant fixes it.
- Maven
- A Java build tool that downloads libraries and runs tasks through hundreds of plugins. It is typically needed to run real JUnit tests.
- Method chaining
- Calling methods one after another, each returning `this`, as in `new OrderBuilder().forCustomer(ana).add(...).build()`.
- Method reference
- A way to use an existing method or constructor as a value, written like `Discounts::wholesaleTiers` or `UpsCarrier::new`.
- Middleware
- Code every web request passes through as a chain of handlers, for example logging or login checks, each able to stop the request.
- Mock
- A test stand-in that also records how it was called so the test can check it. Libraries such as Mockito make them.
- Mockito
- A Java library for creating mocks, which are test stand-ins that record how they were called so a test can check it. Hand-written fakes are a simpler alternative for small programs.
O
- Observer
- A pattern where the place something happens (the subject) keeps a list of listeners and calls each one, without knowing what they do. New reactions need no change to the emitting code.
- Open/closed principle (OCP)
- The SOLID rule that code should be open for extension but closed for modification. A new `DiscountRule` class is added without editing old ones.
- Over-engineering
- Building more structure than the problem needs, like an interface, class, factory and registry for one discount.
- Overload
- Writing several methods with the same name but different parameters, such as `salesTax(amount)` and `salesTax(amount, rate)`.
- Override
- Writing a child class's own version of a method it inherits, marked `@Override`. `LockedCard` and `GiftWrappedProduct` override `topUp` and `total`.
P
- Plugin
- Code a framework finds and runs to add a feature, with no change to the framework itself. It is the open/closed principle at the scale of a whole tool.
- Premature abstraction
- Adding an interface, base class or factory before there are two or three real cases. It guesses what will vary, and a wrong guess is hard to undo.
- Prototype
- A pattern that makes new objects by copying a ready-made one and changing a little. For records, a `withQty` method returns a new record with one field changed.
- Proxy
- A same-interface wrapper that controls access to the real object. It might create it lazily, check permissions or cache answers.
- Publish/subscribe
- Another name for the observer idea: the subject publishes events and listeners subscribe to them.
R
- Record
- A short Java class that holds data with unchangeable fields, like `Customer` and `Item`. To change one you make a new record.
- Reflection
- Code that inspects classes while the program runs. `MiniRunner` uses it to find methods whose names start with `test` and call them.
- Registry
- A table from names to classes or functions that is looked up when needed, like the `CARRIERS` map or Spring's route table.
- Repository
- An object that stores and finds things for the rest of the code, so nothing else knows how they're stored. `MemoryRepo` keeps orders in a list.
- Rule of three
- Write the code the first time, notice the repeat the second time, and extract the shared part the third time, when you know what really varies.
S
- Sealed interface
- A Java interface that lists exactly which types may implement it with `permits`. `Priced` permits only `Single` and `Bundle`.
- Service locator
- A global registry that code reaches into for its dependencies. It hides the dependencies and makes tests change the global, so injection is preferred.
- Simple factory
- One method or class that knows every class and turns a name into the right object, such as `createCarrier("ups")`. A new carrier is one class and one map entry.
- Single responsibility principle (SRP)
- The SOLID rule that a piece of code should have one reason to change. `priceItems` and `applyDiscount` were split from `placeOrder`.
- Singleton
- A class that allows only one instance and hands everyone that same instance. A single-constant enum is Java's simplest safe version.
- SOLID
- Five design principles named by their first letters: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
- Spaghetti code
- Code so tangled with ifs, globals and jumps that you can't follow a single path through it.
- Spring
- A widely used Java framework and DI container for web apps. It builds objects, passes them in and routes web requests to annotated methods.
- State machine
- Something that is always in exactly one of a fixed set of states, with rules for moving between them. An order moves placed, paid, shipped, delivered, and `moveTo` refuses illegal moves.
- Static field
- A `static` field belongs to the class and is shared by every instance. The old shared `orders` list was one.
- Strategy
- One interchangeable way of doing a job: all strategies share a shape, so the code using one doesn't care which it gets. In Java it's usually a lambda or method reference.
- Stream
- A Java way to process a collection step by step with methods like `map`, `filter` and `sum`. For example, a stream can add up item prices or list order ids.
- Structural pattern
- A pattern about how objects fit together, by connecting pieces not made for each other or wrapping one object in another.
- Stub
- A test stand-in that just returns fixed answers, such as a clock that always says 4:00 p.m.
- Subject
- The object whose events listeners subscribe to. It keeps the list of listeners and calls them.
- Supplier
- A Java functional interface for a function that takes nothing and returns a value, called with `get()`. A map of suppliers holds a recipe for each carrier, and `Supplier<Instant>` is a clock.
T
- Template method
- A pattern that fixes a job's steps in one place and leaves one step, the hook, for the caller to supply as a lambda or in a subclass. Try-with-resources is an example in Java.
- Test double
- Any stand-in used in a test in place of a real part. Fakes, stubs and mocks are the three common kinds.
- Thread-safe
- Safe to use when several threads run at once. In `Settings`, `volatile` makes a change visible to every thread, and the JVM creates an enum constant once.
- Transition
- One allowed move from one state to another, such as paid to shipped. A map of transitions lists where each state may go.
- Tree
- A structure where items contain smaller items, like bundles inside bundles. A composite forms one.
- Try-with-resources
- A Java `try (...)` form that automatically calls `close()` on `AutoCloseable` objects when the block ends. It always opens and closes, while your block varies.
U
- Undo stack
- A list of done commands with the newest on top. Undo pops the last one and reverses it.
W
- Wrapper
- An object that holds another and stands in front of it. Adapters, decorators and proxies are all wrappers.
Y
- YAGNI
- "You aren't gonna need it": don't build for a future need until it's a real need. Most guessed needs never arrive, or arrive in a different shape.