验证面试测试示例代码对应的设计模式是否准确
Design Pattern Check for Your Code Snippets
Let's break down each example to clarify which design patterns are at play.
Example 1: Builder or Strategy? Neither—it's the Decorator Pattern!
Your code snippet:
FileStream* files = new FileStream("my_file.zip"); BufferedStream* bufferds = new BufferedStream(files); ZipStream* zips = new ZipStream(bufferds);
This is a textbook Decorator pattern, not Builder or Strategy. Here's the breakdown:
- Builder focuses on constructing complex objects step-by-step (like assembling a custom car with optional features). That's not what's happening here—we're not building a single object through sequential steps, but wrapping existing ones.
- Strategy is about swapping interchangeable algorithms (e.g., choosing between bubble sort and quicksort). This code isn't replacing behavior; it's adding functionality on top of existing objects.
- Decorator dynamically extends an object's responsibilities by wrapping it. Each stream (BufferedStream, ZipStream) takes an existing stream as input and enhances its capabilities (buffering, compression) without modifying the original stream's code. That's exactly what this implementation does.
Example 2: Is this the Strategy Pattern? Yes (with a dash of Adapter)
Looking at your code structure:
struct Writer { virtual void write(string str) = 0; virtual void newline() = 0; virtual ~Writer() {} }; struct UnixWriter : Writer { /* ... implements newline with lf() ... */ }; struct WindowsWriter : Writer { /* ... implements newline with crlf() ... */ }; int main() { Writer* writer = (g_IsUnix) ? (Writer*) new UnixWriter(new UnixText()) : (Writer*) new WindowsWriter(new WindowsText()); writer->write("Hello"); writer->newline(); writer->write("World"); }
Yes, this absolutely uses the Strategy pattern. Here's why:
- You have a common interface (
Writer) that defines the operations the client cares about. - Two concrete implementations (
UnixWriter,WindowsWriter) handle thenewlinebehavior differently, adapting to Unix vs. Windows line-ending standards. - At runtime, you select which strategy to use based on
g_IsUnix, then interact with the interface without worrying about the concrete type. This dynamic, interchangeable behavior is the core of the Strategy pattern.
A quick side note: The UnixWriter and WindowsWriter also act as Adapters—they convert the interface of UnixText/WindowsText (which use lf()/crlf() instead of newline()) to match the Writer interface. But the primary pattern driving the dynamic selection and interchangeable behavior here is Strategy.
内容的提问来源于stack exchange,提问作者Aminos
相关产品推荐
相关产品推荐

