0% found this document useful (0 votes)
2 views7 pages

Design Patterns Learning Tests

Uploaded by

Andrew Carson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Design Patterns Learning Tests

Uploaded by

Andrew Carson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Design Patterns Learning Tests

Creational Patterns

1. Singleton Pattern
Test 1 - Conceptual Understanding: You're building a logging system for an application. Multiple parts
of your code need to write to the same log file. Why would you use the Singleton pattern here, and what
problems could arise if you created multiple logger instances?

Test 2 - Implementation Challenge: Write pseudocode for a thread-safe Singleton class called
DatabaseConnection . It should have a method getInstance() that always returns the same instance,
and a method query(sql) that executes database queries.

2. Factory Method Pattern


Test 1 - Pattern Recognition: A payment processing system needs to handle different payment types
(CreditCard, PayPal, BankTransfer). Each payment type has different validation rules and processing steps.
How would the Factory Method pattern solve this, and what would be the key components?

Test 2 - Code Analysis:

pseudocode

class ShapeFactory {
createShape(type) {
if (type == "circle") return new Circle()
if (type == "square") return new Square()
if (type == "triangle") return new Triangle()
}
}

Is this a proper Factory Method implementation? If not, what's wrong and how would you improve it?

3. Abstract Factory Pattern


Test 1 - Scenario Application: A GUI application needs to support different operating systems
(Windows, Mac, Linux). Each OS has its own Button, Menu, and Dialog components that look and behave
differently. Explain how Abstract Factory would structure this solution.

Test 2 - Design Challenge: Design an Abstract Factory for a furniture store that sells Modern and
Victorian style furniture. Each style has Chairs, Tables, and Sofas. What classes would you create and how
would they relate to each other?

4. Builder Pattern
Test 1 - Problem Identification: You need to create a House object that can have different numbers of
rooms, floors, garages, pools, and gardens. Some houses are simple (just rooms), others are complex.
Why is Builder better than a constructor with many parameters?

Test 2 - Implementation Design: Create a Builder pattern structure for building SQL queries. The builder
should handle SELECT, FROM, WHERE, ORDER BY, and LIMIT clauses. Show the main classes and their key
methods.

5. Prototype Pattern
Test 1 - Use Case Analysis: A graphics editor allows users to copy and paste complex shapes that
contain colors, gradients, shadows, and transformations. Creating these from scratch is expensive. How
does Prototype pattern help, and what interface would the shapes need?

Test 2 - Implementation Problem: What's the difference between shallow copy and deep copy in the
Prototype pattern? Give an example where shallow copy would cause bugs and explain how to fix it.

Structural Patterns

6. Adapter Pattern
Test 1 - Real-World Application: Your new system needs to integrate with a legacy XML-based API, but
your application works with JSON. The legacy API has methods like getCustomerXML(id) and
updateCustomerXML(xmlData) . Design an Adapter solution.

Test 2 - Code Completion:


pseudocode

class OldPrinter {
printOldFormat(text) { /* prints in old format */ }
}

class NewPrinter {
printNewFormat(data) { /* prints in new format */ }
}

// Complete the Adapter class


class PrinterAdapter {
// Your code here
}

7. Bridge Pattern
Test 1 - Pattern Distinction: Explain the difference between Bridge and Adapter patterns using a remote
control example. When would you use Bridge instead of Adapter?

Test 2 - Design Exercise: You're building a notification system that can send messages via Email, SMS, or
Push notifications. The messages can be formatted as Plain text, HTML, or JSON. Design a Bridge pattern
solution showing the abstraction and implementation hierarchies.

8. Composite Pattern
Test 1 - Structure Recognition: A file system has Files (leaf nodes) and Directories (composite nodes).
Both can be copied, moved, and deleted. Directories can contain other files and directories. Map this to
the Composite pattern components (Component, Leaf, Composite).

Test 2 - Implementation Challenge: Design a Composite pattern for a drawing application where you
have basic shapes (Circle, Rectangle) and groups of shapes. All should support draw() , move(x, y) , and
calculateArea() operations.

9. Decorator Pattern
Test 1 - Scenario Analysis: A coffee shop sells basic coffee for $2. Customers can add milk (+$0.5), sugar
(+$0.2), whipped cream (+$0.7), or extra shot (+$1.5). Orders can have multiple add-ons. Why is
Decorator better than creating separate classes for every combination?
Test 2 - Code Structure: Design the Decorator pattern for text formatting where you have basic text and
can add Bold, Italic, Underline, and Color decorators. Show the key classes and their relationships.

10. Facade Pattern


Test 1 - Complexity Hiding: A home automation system controls lights, thermostat, security system, and
entertainment center. Each has complex APIs with many methods. Design a Facade that provides simple
methods like leaveHome() , arriveHome() , and movieTime() .

Test 2 - Pattern Benefits: What are the main advantages of using Facade pattern? Give an example
where Facade might make the system harder to maintain and how to avoid that problem.

11. Flyweight Pattern


Test 1 - Memory Optimization: A word processor displays thousands of characters. Each character has
font, size, color, and position. Which properties should be intrinsic (shared) and which should be extrinsic
(context-specific) in a Flyweight implementation?

Test 2 - Implementation Decision: You're building a game with thousands of trees in a forest. Each tree
has species, texture, position, and health. Design a Flyweight solution and calculate the memory savings
compared to creating individual tree objects.

12. Proxy Pattern


Test 1 - Pattern Variants: Name and explain three different types of Proxy patterns. Give a real-world
example for each type.

Test 2 - Security Proxy: Design a Proxy for accessing sensitive user data. The real object has methods
getPersonalInfo() , getCreditCardInfo() , and getPublicProfile() . The proxy should check user
permissions before allowing access. Show the structure.

Behavioral Patterns

13. Chain of Responsibility Pattern


Test 1 - Request Handling: An expense approval system needs different approval levels: Manager
($0-$1000), Director ($1000-$5000), VP ($5000-$10000), CEO ($10000+). Design a Chain of Responsibility
solution showing how requests flow through the chain.

Test 2 - Implementation Analysis: What happens if no handler in the chain can process a request?
Provide two different strategies for handling this situation and explain when to use each.
14. Command Pattern
Test 1 - Undo Functionality: A text editor needs to support undo/redo for operations like typing,
deleting, cutting, and pasting. Explain how the Command pattern enables this and what information each
command needs to store.

Test 2 - Macro Commands: Design a Command pattern for a smart home system with commands like
TurnOnLights , SetTemperature , LockDoors . Then show how to create a macro command called
GoodNightMode that executes multiple commands.

15. Interpreter Pattern


Test 1 - Language Design: Create a simple expression language that can evaluate mathematical
expressions like "5 + 3 * 2". Define the grammar and show what interpreter classes you'd need.

Test 2 - Pattern Limitations: When should you NOT use the Interpreter pattern? What are better
alternatives for complex language parsing, and why?

16. Iterator Pattern


Test 1 - Custom Collection: You have a binary tree structure and need to traverse it in different ways (in-
order, pre-order, post-order). Design Iterator pattern solution that allows clients to iterate without
knowing the tree structure.

Test 2 - Iterator Interface: Design a generic Iterator interface that works with different collection types.
What methods should it have, and how would you handle edge cases like modifying the collection during
iteration?

17. Mediator Pattern


Test 1 - Communication Complexity: An online auction system has Bidders, Auctioneer, and Auction
items. Bidders place bids, auctioneers announce winners, and items track highest bids. Without Mediator,
how many communication paths exist between 5 bidders, 2 auctioneers, and 10 items? How does
Mediator simplify this?

Test 2 - Chat Room Design: Design a Mediator pattern for a chat room where users can send messages,
join/leave rooms, and send private messages. Show the mediator interface and how users interact
through it.

18. Memento Pattern


Test 1 - State Management: A chess game needs to support undo moves and save/load game states.
What information should be stored in the Memento, and what should remain private to the chess game?
Consider the principle of encapsulation.

Test 2 - Implementation Challenge: Design a Memento pattern for a drawing application where users
can undo drawing operations. Handle the case where storing full state snapshots would use too much
memory.

19. Observer Pattern


Test 1 - Notification System: A stock trading system needs to notify different components when stock
prices change: Portfolio display, Alert system, Trading bot, and Analytics engine. Each needs different
information about the price change. Design an Observer solution.

Test 2 - Observer Management: What problems can occur if observers are not properly managed? How
do you handle the case where an observer throws an exception during notification?

20. State Pattern


Test 1 - State Machine: A TCP connection has states: Closed, Listen, Established, and CloseWait. Different
events (open, close, acknowledge) cause state transitions and different behaviors. Map this to the State
pattern structure.

Test 2 - Context Switching: Design a State pattern for a music player with states: Stopped, Playing,
Paused. Show how the same operations (play, pause, stop) behave differently in each state.

21. Strategy Pattern


Test 1 - Algorithm Selection: A navigation app can calculate routes using different strategies: Fastest
route, Shortest distance, Avoid tolls, Scenic route. The user can switch strategies at runtime. Design a
Strategy pattern solution.

Test 2 - Strategy vs State: Explain the key differences between Strategy and State patterns. Both involve
changing behavior, so when would you choose one over the other?

22. Template Method Pattern


Test 1 - Algorithm Framework: Design a Template Method for data processing that follows these steps:
Read data, Validate data, Process data, Save results. Some steps are common, others vary by data type
(CSV, JSON, XML).
Test 2 - Hook Methods: What are hook methods in Template Method pattern? Show how to design a
template for generating reports where some sections are optional based on user preferences.

23. Visitor Pattern


Test 1 - Operation Addition: A document structure has Paragraphs, Images, and Tables. You need to add
new operations: Export to PDF, Count words, Find and replace text. Why is Visitor better than adding
these methods to each element class?

Test 2 - Double Dispatch: Explain the concept of double dispatch in the Visitor pattern. Show with
pseudocode how the visitor method gets selected based on both the visitor type and the element type.

Answer Guidelines
For Instructors/Self-Assessment:

Each test is designed to evaluate:

Conceptual Understanding: Does the student grasp when and why to use the pattern?
Practical Application: Can they design or implement the pattern correctly?

Problem Recognition: Can they identify which pattern solves a given problem?

Critical Thinking: Do they understand the trade-offs and limitations?

Difficulty Levels:

Beginner: Pattern recognition and basic concepts


Intermediate: Design and implementation challenges

Advanced: Comparing patterns and understanding trade-offs

These tests can be used for:

Individual study and self-assessment

Programming interviews

Computer science coursework

Professional development training

You might also like