Java Design Patterns Interview Questions Practice Test MCQs Core Java Design Patterns Interview java Java MCQ by devs5003 - April 22, 2025April 28, 20250 Last Updated on April 28th, 2025 Practice tests are essential to mastering any technology. They help us review topics thoroughly and understand the concepts clearly. In this article, weโll focus on a Java Design Patterns Interview Questions Practice Test MCQs, including different question types like: Concept-based (testing our theory knowledge), Code-based (checking our coding skills), and Scenario-based (applying knowledge to real-world problems). Each question comes with detailed explanations for both correct and incorrect answers, so we will learn not just whatโs right, but also why the other options are wrong. Sometimes, even incorrect answers teach us something useful! Let’s go through Java Design Patterns Interview Questions Practice Test MCQs. Table of Contents Toggle Java Design Patterns Interview Questions Practice Test MCQsMore Questions? Java Design Patterns Interview Questions Practice Test MCQs Q#1. (Scenario-Based Question, Single-Select) You have different types of notification systems (Email, SMS, Push Notifications) in an application. The goal is to create a unified interface for sending messages without exposing the complexity of each notification system. Which pattern fits best? A) Facade Pattern B) Proxy Pattern C) Bridge Pattern D) Decorator Pattern Answer: A) Facade Pattern Explanation: (A) Facade Pattern: Correct. Facade provides a simplified interface to multiple subsystems, like the different notification systems here. (B) Proxy Pattern: Incorrect. Proxy provides a surrogate or placeholder for another object, not a simplified interface. (C) Bridge Pattern: Incorrect. Bridge is useful for separating an abstraction from its implementation, not for simplifying interfaces. (D) Decorator Pattern: Incorrect. Decorator adds functionality to objects without modifying their structure but does not simplify interfaces. Q#2. (Concept-Based Question, Single-Select) Which of the following pattern allows an object to alter its behavior when its internal state changes? A) Observer Pattern B) State Pattern C) Strategy Pattern D) Command Pattern Answer: B) State Pattern Explanation: (A)ย Observer Pattern: Incorrect. Observer notifies dependent objects about changes but doesnโt handle state-based behavior changes. (B)ย State Pattern: Correct. State allows an object to change behavior when its state changes, ideal for scenarios with different states. (C) Strategy Pattern: Incorrect. Strategy enables interchangeable algorithms, not behavior change due to state. (D) Command Pattern: Incorrect. Command encapsulates requests but doesnโt change object behavior based on state. Q#3. (Code-Based Question, Single-Select) Consider the below code snippet.ย public sealed interface Document permits PDFDocument, WordDocument { void open(); } public record PDFDocument implements Document { @Override public void open() { System.out.println("Opening PDF"); } } public record WordDocument implements Document { @Override public void open() { System.out.println("Opening Word"); } } public class DocumentFactory { public Document createDocument(String type) { switch (type) { case "PDF" -> new PDFDocument(); case "Word" -> new WordDocument(); default -> throw new IllegalArgumentException("Invalid type:" +type); } } } Which design pattern does this code demonstrate? Options: A) Factory Method Pattern B) Abstract Factory Pattern C) Builder Pattern D) Prototype Pattern Answer: A) Factory Method Pattern Explanation: A) Factory Method Pattern: Correct. The Factory Method Pattern is the correct choice here because the code defines a dedicated method (createDocument) to handle object creation, shielding clients from direct instantiation logic. B) Abstract Factory Pattern: Incorrect. The Abstract Factory Pattern is incorrect because it is designed to create families of related or dependent objects (e.g., a suite of UI components like buttons, menus, and dialogs for a specific operating system). Here, the factory only generates individualย Documentย objects without any interrelated products. An Abstract Factory would necessitate multiple creation methods (e.g.,ย createDocument,ย createParser,ย createRenderer) working together, which is absent in this implementation. C) Builder Pattern: Incorrect. The Builder Pattern does not apply because it focuses on constructing complex objects through a step-by-step process, often involving many optional parameters or nested configurations. The given code creates simpleย Document objects in a single step. D) State: Incorrect. The Prototype Pattern is irrelevant here because it relies on cloning existing instances to avoid expensive creation operations. The provided factory always creates new objects from scratch using theย new keyword, with no use of cloning. Q#4. (Scenario-Based Question, Single-Select) An application has a document conversion feature with the following requirements: Converts Document Formats: It can convert documents between different formats (e.g., DOCX to PDF, PDF to HTML). Adapts to New Formats Without Code Change: The system needs to support new formats without altering existing conversion logic. Maintains Consistent Conversion Interface: All conversions should follow a standard interface, so users have a consistent experience across formats. Which design pattern would best address this system? Options: A) Adapter Pattern B) Factory Method Pattern C) Strategy Pattern D) Bridge Pattern Answer: A) Adapter Pattern Explanation: A) Adapter Pattern: Correct. The Adapter pattern enables the conversion system to handle multiple formats by providing a unified interface to interact with various formats. When new formats are introduced, adapters for these formats can be added without altering existing code, fulfilling the requirement. B) Factory Method Pattern: Incorrect. While the Factory Method can create objects based on input, it doesnโt adapt or convert interfaces, making it unsuitable for format conversion here. C) Strategy Pattern: Incorrect. The Strategy pattern would allow different algorithms to be used interchangeably but wouldnโt help adapt incompatible document formats to a standard interface. D) Bridge Pattern: Incorrect. The Bridge pattern is useful for separating an abstraction from its implementation but is unnecessary here, where adapting incompatible interfaces is the main goal. The Adapter pattern ensures that all document formats are presented through a consistent interface, making it the ideal choice here. Q#5. (Scenario-Based Question, Multi-Select) A company needs a payment processing system that: Supports Multiple Gateways: Allows integration with various payment providers (e.g., PayPal, Stripe, Square). Provides Unified Payment Interface: Offers a standardized interface so that the main application doesnโt need to know the specifics of each payment provider. Allows Adding New Gateways Easily: New payment gateways should be added without modifying the existing code. Which design pattern/(s) would be most suitable for this system? Options (Multi-Select): A) Adapter Pattern B) Facade Pattern C) Strategy Pattern D) Template Method Pattern Answer: A) Adapter Pattern and C) Strategy Pattern Explanation: A) Adapter Pattern: Correct. The Adapter pattern can be used to unify different payment provider interfaces, making them conform to a common interface for ease of integration with the application. C) Strategy Pattern: Correct. Each payment provider can be implemented as a separate strategy, allowing the application to choose the provider dynamically at runtime based on user selection or configuration. B) Facade Pattern: Incorrect. The Facade pattern would simplify complex subsystems, but it doesnโt aid in providing interchangeable providers or adapting interfaces. D) Template Method Pattern: Incorrect. The Template Method pattern would structure a series of steps but isnโt as relevant for this use case, where different providers follow varied workflows. Here, the Adapter and Strategy patterns together allow seamless integration with multiple payment providers, ensuring a standardized interface and dynamic selection capability. Q#6. (Scenario-Based Question, Single-Select) In a graphics editor, you have different shapes (like circles, squares, etc.) and wish to apply different effects (such as color or shadow) on top of these shapes dynamically. Which design pattern is best suited here? A) Decorator Pattern B) Composite Pattern C) Flyweight Pattern D) Prototype Pattern Answer: A) Decorator Pattern Explanation: (A) Decorator Pattern: Correct. Decorator is used to add responsibilities or effects dynamically without altering the core shape class. (B) Composite Pattern: Incorrect. Composite is used to create tree-like structures, not add features to individual components. (C) Flyweight Pattern: Incorrect. Flyweight minimizes memory usage but doesnโt help with adding effects dynamically. (D) Prototype Pattern: Incorrect. Prototype is used for cloning objects, not dynamically adding responsibilities. Q#7. (Concept-Based Question, Single-Select) What technique should be used in a Singleton class to prevent multiple instances from being created when the object is serialized and then deserialized? A) Implement a private constructor B) Mark the instance variable as volatile C) Implement the readResolve method D) Use double-checked locking Answer: C) Implement the readResolve method Explanation: A) Private constructor: Incorrect. While it restricts instantiation from outside the class, it doesnโt prevent multiple instances created through deserialization. B) Marking instance as volatile: Incorrect. This helps with visibility in a multithreaded environment but does not address serialization issues. C) readResolve method: Correct. Implementing readResolve ensures that upon deserialization, the existing instance is returned, maintaining the Singleton guarantee. D) Double-checked locking: Incorrect. Double-checked locking is a thread-safety mechanism for lazy initialization but does not prevent Singleton violations due to deserialization. Q#8. (Scenario-Based Question, Single-Select) A document editor requires implementing an undo feature where each action can be undone sequentially. Which pattern would effectively manage this requirement? A) Command Pattern B) Memento Pattern C) Strategy Pattern D) Chain of Responsibility Pattern Answer: B) Memento Pattern Explanation: (A) Command Pattern: Incorrect. Command is useful for encapsulating requests, but it does not inherently support state restoration. (B) Memento Pattern: Correct. Memento captures an object’s state, enabling the undo functionality by restoring previous states. (C) Strategy Pattern: Incorrect. Strategy is for interchangeable algorithms, not for restoring object states. (D) Chain of Responsibility Pattern: Incorrect. This is used for passing requests along a chain, not for maintaining object history. Q#9. (Code-Based Question, Single-Select) Analyze the following Java code snippet: public abstract class Beverage { public final void makeBeverage() { boilWater(); addMainIngredient(); addCondiments(); pourInCup(); } protected abstract void addMainIngredient(); protected abstract void addCondiments(); private void boilWater() { System.out.println("Boiling water"); } private void pourInCup() { System.out.println("Pouring in cup"); } } Which design pattern does this code illustrate? Options: A) Template Method B) Observer C) Builder D) Facade Answer: A) Template Method Explanation: This code illustrates the Template Method pattern, where the makeBeverage method defines a series of steps, with specific methods left abstract for subclasses to implement. This ensures a predefined structure while allowing flexibility in specific steps. Observer, Builder, and Facade patterns donโt apply here, as they serve distinct purposes. Q#10. (Scenario-Based Question, Single-Select) In a drawing application, you can group shapes into complex drawings and apply actions to both individual shapes and groups uniformly. Which pattern would allow you to achieve this? A) Flyweight Pattern B) Composite Pattern C) Decorator Pattern D) Chain of Responsibility Pattern Answer: B) Composite Pattern Explanation: (A) Flyweight Pattern: Incorrect. Flyweight minimizes memory usage for many similar objects, not grouping and treating them uniformly. (B) Composite Pattern: Correct. Composite allows grouping shapes and treating both individual and complex structures as a single entity. (C) Decorator Pattern: Incorrect. Decorator dynamically adds behavior, but it doesnโt manage groups of objects. (D) Chain of Responsibility Pattern: Incorrect. Chain of Responsibility is for passing requests along a chain rather than grouping objects. Q#11. (Scenario-Based Question, Single-Select) An e-commerce website has different types of users (e.g., guest, registered, admin). Each type has varied access permissions. Which pattern can dynamically adjust the access level at runtime? A) Strategy Pattern B) State Pattern C) Observer Pattern D) Chain of Responsibility Pattern Answer: B) State Pattern Explanation: (A) Strategy Pattern: Incorrect. Strategy is for interchangeable algorithms rather than state-dependent behavior. (B) State Pattern: Correct. State pattern allows dynamic behavior change based on user type, offering a different experience for each user role. (C) Observer Pattern: Incorrect. Observer is for notifying dependent objects of changes but doesnโt change access levels. (D) Chain of Responsibility Pattern: Incorrect. Chain of Responsibility is for passing requests along a chain, not handling states. Q#12. (Scenario-Based Question, Single-Select) In a banking app, you need to provide different account creation options (e.g., savings, checking) with shared account features but varying properties. Which pattern should you apply to ensure that different account types can be created with minimal code duplication? A) Prototype Pattern B) Factory Method Pattern C) Singleton Pattern D) Abstract Factory Pattern Answer: B) Factory Method Pattern Explanation: (A) Prototype Pattern: Incorrect. Prototype is for cloning objects rather than handling different account types. (B) Factory Method Pattern: Correct. Factory Method allows subclasses to create specific account types, minimizing code duplication. (C) Singleton Pattern: Incorrect. Singleton ensures only one instance, which doesnโt solve account type variation. (D) Abstract Factory Pattern: Incorrect here, as itโs ideal for families of related products, which isnโt necessary for simple account creation. Q#13. (Scenario-Based Question, Single-Select) An application needs to load images only when they are about to be viewed by the user, to save memory. Which pattern is best for this situation? A) Singleton Pattern B) Proxy Pattern C) Adapter Pattern D) Flyweight Pattern Answer: B) Proxy Pattern Explanation: (A) Singleton Pattern: Incorrect. Singleton controls instance count but doesnโt delay image loading. (B) Proxy Pattern: Correct. Proxy controls access and can defer image loading until necessary. (C) Adapter Pattern: Incorrect. Adapter changes interface compatibility but doesnโt defer object creation. (D) Flyweight Pattern: Incorrect. Flyweight reduces memory usage by sharing, not deferring creation. Q#14. (Scenario-Based Question, Single-Select) A logging library allows users to enable logging levels (error, debug, info) without altering existing code. Which design pattern would best support this flexibility? A) Command Pattern B) Observer Pattern C) Chain of Responsibility Pattern D) Flyweight Pattern Answer: C) Chain of Responsibility Pattern Explanation: (A) Command Pattern: Incorrect. Command encapsulates a request but isnโt ideal for sequential logging levels. (B) Observer Pattern: Incorrect. Observer notifies subscribers but doesnโt chain logging responsibilities. (C) Chain of Responsibility Pattern: Correct. Chain of Responsibility can pass requests through multiple handlers (logging levels) until they are processed. (D) Flyweight Pattern: Incorrect. Flyweight reduces memory use, not request handling across chains. Q#15. (Scenario-Based Question, Single-Select) You need to create multiple themes for a user interface, each with different font styles and color schemes, while ensuring flexibility for future themes. Which pattern best fits this use case? A) Factory Pattern B) Singleton Pattern C) Abstract Factory Pattern D) Prototype Pattern Answer: C) Abstract Factory Pattern Explanation: (A) Factory Pattern: Incorrect. Factory creates objects based on input, not a suite of related products. (B) Singleton Pattern: Incorrect. Singleton ensures one instance, irrelevant for multiple theme options. (C) Abstract Factory Pattern: Correct. Abstract Factory creates families of related objects like font styles and color schemes. (D) Prototype Pattern: Incorrect. Prototype clones existing objects, not related products. Q#16. (Scenario-Based Question, Single-Select) You are creating a system where multiple components need to access a shared object, such as a configuration manager, without creating multiple instances. Which design pattern would you use? A) Singleton Pattern B) Observer Pattern C) Adapter Pattern D) Composite Pattern Answer: A) Singleton Pattern Explanation: (A) Singleton Pattern: Correct. Singleton ensures only one instance of a class, perfect for shared objects like a configuration manager. (B) Observer Pattern: Incorrect. Observer is for notifying changes rather than managing a single instance. (C) Adapter Pattern: Incorrect. Adapter enables compatibility with different interfaces but doesnโt restrict instance count. (D) Composite Pattern: Incorrect. Composite treats grouped objects uniformly, not limiting instances. Q#17. (Scenario-Based Question, Single-Select) You need to create a flexible notification system in which users can subscribe to receive updates on certain events. Which design pattern is best suited to implementing this notification feature? A) Observer Pattern B) Singleton Pattern C) Command Pattern D) Composite Pattern Answer: A) Observer Pattern Explanation: (A) Observer Pattern: Correct. Observer allows subscribing to updates, making it ideal for notifications. (B) Singleton Pattern: Incorrect. Singleton ensures only one instance; it doesnโt manage subscriptions. (C) Command Pattern: Incorrect. Command encapsulates requests but isnโt suitable for handling notifications. (D) Composite Pattern: Incorrect. Composite is for hierarchical structures, not event subscriptions. Q#18. (Code-Based Question, Single-Select) Observe below code snippet: public abstract class Shape { protected Color color; public Shape(Color color) { this.color = color; } abstract void draw(); } public class Circle extends Shape { public Circle(Color color) { super(color); } @Override public void draw() { System.out.print("Drawing Circle in "); color.applyColor(); } } public interface Color { void applyColor(); } public class RedColor implements Color { public void applyColor() { System.out.println("Red color"); } } Which design pattern does this code demonstrate? A) Adapter B) Bridge C) Composite D) Flyweight Answer: B) Bridge Explanation: A) Adapter: Incorrect. The Adapter pattern is used to make incompatible interfaces work together. Here, Color and Shape are already compatible, so Adapter is not applicable. B) Bridge: Correct. The Bridge pattern decouples an abstraction (in this case, Shape) from its implementation (in this case, Color) so that they can vary independently. By using a Color interface that is passed to the Shape constructor, we can create different shape and color combinations without changing their classes. C) Composite: Incorrect. Composite pattern is used to treat a group of objects the same way as individual objects, which isnโt demonstrated here. D) Flyweight: Incorrect. Flyweight is used for sharing common states to save memory. Thereโs no evidence of shared state optimization here. Q#19. (Scenario-Based Question, Single-Select) In an e-commerce application, a user should be able to build an order with various configurations (e.g., items, shipping method, discounts). Each order configuration has specific requirements. Which pattern best allows for this flexibility? A) Builder Pattern B) Prototype Pattern C) Composite Pattern D) Chain of Responsibility Pattern Answer: A) Builder Pattern Explanation: (A) Builder Pattern: Correct. Builder simplifies constructing complex objects with varied configurations. (B) Prototype Pattern: Incorrect. Prototype clones objects but doesnโt build configurations. (C) Composite Pattern: Incorrect. Composite structures parts, not configurations. (D) Chain of Responsibility Pattern: Incorrect. Chain doesnโt help with building configurations. Q#20. (Scenario-Based Question, Single-Select) You are developing a mobile app where a user can apply various themes, such as “dark mode” or “light mode,” without affecting the underlying structure of the app. Which design pattern should you consider? A) Bridge Pattern B) Factory Pattern C) State Pattern D) Singleton Pattern Answer: A) Bridge Pattern Explanation: (A) Bridge Pattern: Correct. Bridge separates theme interface and implementation, allowing themes to vary independently. (B) Factory Pattern: Incorrect. Factory creates instances but doesnโt manage theme and structure separation. (C) State Pattern: Incorrect. State is more suited to managing transitions, not structural independence. (D) Singleton Pattern: Incorrect. Singleton enforces one instance, unrelated to theme flexibility. Q#21. (Scenario-Based Question, Single-Select) A restaurant management app wants to allow users to place orders in a specific sequence (appetizer, main course, dessert). Each order step should execute independently but in a specified sequence. Which pattern best fits? A) Command Pattern B) Chain of Responsibility Pattern C) Decorator Pattern D) Proxy Pattern Answer: A) Command Pattern Explanation: (A) Command Pattern: Correct. Command allows encapsulation and ordering of specific actions. (B) Chain of Responsibility Pattern: Incorrect. Chain passes requests without defining execution order. (C) Decorator Pattern: Incorrect. Decorator adds behavior, irrelevant for command sequencing. (D) Proxy Pattern: Incorrect. Proxy controls access, not action sequence. Q#22. (Scenario-Based Question, Single-Select) In a logging system, log messages are handled by different handlers based on severity levels (INFO, WARNING, ERROR). A new log message with an “ERROR” level is added. Which of the following statements are correct about using the Chain of Responsibility pattern for this scenario? The “INFO” handler should forward the message to the next handler if it canโt process it. Each handler should stop the chain once it receives the log message. The “ERROR” handler, being the last in the chain, should process any unhandled requests. Options: A) Statements 1 & 2 are correct B) Statements 1 & 3 are correct C) Statements 2 & 3 are correct D) All statements are correct Answer: B Explanation: Statement 1 is correct as the “INFO” handler should forward unhandled requests to the next handler. Statement 2 is incorrect because handlers should pass unhandled messages along the chain rather than stopping it immediately. Statement 3 is correct as the “ERROR” handler should handle any unprocessed messages, acting as the last in the chain. Q#23. (Concept-Based Question, Single-Select) Which statements best describe the responsibilities of handlers in a Chain of Responsibility? Each handler can decide whether to handle or pass a request. Each handler must keep track of the previous handler in the chain. Each handler has logic to process specific requests. Options: A) Statements 1 & 2 are correct B) Statements 1 & 3 are correct C) Statements 2 & 3 are correct D) All statements are correct Answer: B Explanation: Statement 1 is correct as handlers can process or pass requests. Statement 3 is correct as each handler handles specific request types. Statement 2 is incorrect since handlers only know about the next handler, not previous ones. Q#24. (Concept-Based Question, Single-Select) Which design principle is most prominently applied in the Chain of Responsibility pattern? A) Dependency Inversion B) Open/Closed Principle C) Liskov Substitution D) Law of Demeter Answer: B Explanation: B is correct as the Open/Closed Principle allows adding new handlers without altering existing code. A, C, and D are incorrect as theyโre less central to CORโs design. Q#25. (Concept-Based Question, Single-Select) Which of the following best describes the Observer Pattern? A) A pattern used to create an interface for creating families of related objects B) A pattern where objects are arranged in a chain to handle requests sequentially C) A pattern where objects notify other objects when a change occurs in their state D) A pattern that provides a way to access elements of an aggregate object without exposing its representation Answer: C Explanation: C is correct as the Observer Pattern facilitates notification of observers when the subjectโs state changes. B, A, and D are incorrect as they describe the Chain of Responsibility, Abstract Factory, and Iterator patterns, respectively. Q#26. (Code-Based Question, Single-Select) Consider the below code snippet.ย public interface Operation{ int execute(int a, int b); } public class AddOperation implements Operation{ public int execute(int a, int b) { return a + b; } } public class SubtractOperation implements Operation{ public int execute(int a, int b) { return a - b; } } public class Calculator { private Operation operation; public Calculator(Operation operation) { this.operation= operation; } public int calculate(int a, int b) { return operation.execute(a, b); } } Which design pattern does this code demonstrate? Options: A) Chain of Responsibility B) Template Method C) Strategy D) State Answer: C) Strategy Explanation: A)ย Chain of Responsibility: Incorrect. Chain of Responsibility passes requests down a chain, unrelated to this codeโs dynamic operation selection. B) Template Method: Incorrect. Template Method defines a skeleton algorithm in a superclass with customizable steps, not interchangeable strategies. C)ย Strategy: Correct. The Strategy pattern defines a family of algorithms (addition and subtraction here) that can be swapped at runtime. Calculator uses Strategy to perform a calculation with a specific operation. D) State: Incorrect. State pattern is for managing state-dependent behavior, not interchangeable algorithms. More Questions? If you want to practice on more similar type of questions covering all the topics in Java Design Patterns, kindly visit any of the below channels: Udemy course: Java Design Patterns Practice Test & Interview Questions. You will have a life time access to these practice tests. These set of practice tests are extension to aforementioned sample questions. These are new set of practice tests having more than 500 questions created recently. When you get the access of the practice tests, you are advised to go through the explanation of each question thoroughly. It will help you clearing your concept on a particular topic. Amazon eBook: Utilize the free access to kindle unlimited reading. For amazon.in users: Master Java Design Patterns with 500+ Solved MCQs & 1000+ Concepts Explanations For amazon.com users:ย Master Java Design Patterns with 500+ Solved MCQs & 1000+ Concepts Explanations Here, you can also utilize the free access to kindle unlimited reading. Additionally, check for the availability of other formats of the book in your respective region. Related
Practice tests are essential to mastering any technology. They help us review topics thoroughly and understand the concepts clearly. In this article, weโll focus on a Java Design Patterns Interview Questions Practice Test MCQs, including different question types like: Concept-based (testing our theory knowledge), Code-based (checking our coding skills), and Scenario-based (applying knowledge to real-world problems). Each question comes with detailed explanations for both correct and incorrect answers, so we will learn not just whatโs right, but also why the other options are wrong. Sometimes, even incorrect answers teach us something useful! Let’s go through Java Design Patterns Interview Questions Practice Test MCQs. Table of Contents Toggle Java Design Patterns Interview Questions Practice Test MCQsMore Questions? Java Design Patterns Interview Questions Practice Test MCQs Q#1. (Scenario-Based Question, Single-Select) You have different types of notification systems (Email, SMS, Push Notifications) in an application. The goal is to create a unified interface for sending messages without exposing the complexity of each notification system. Which pattern fits best? A) Facade Pattern B) Proxy Pattern C) Bridge Pattern D) Decorator Pattern Answer: A) Facade Pattern Explanation: (A) Facade Pattern: Correct. Facade provides a simplified interface to multiple subsystems, like the different notification systems here. (B) Proxy Pattern: Incorrect. Proxy provides a surrogate or placeholder for another object, not a simplified interface. (C) Bridge Pattern: Incorrect. Bridge is useful for separating an abstraction from its implementation, not for simplifying interfaces. (D) Decorator Pattern: Incorrect. Decorator adds functionality to objects without modifying their structure but does not simplify interfaces. Q#2. (Concept-Based Question, Single-Select) Which of the following pattern allows an object to alter its behavior when its internal state changes? A) Observer Pattern B) State Pattern C) Strategy Pattern D) Command Pattern Answer: B) State Pattern Explanation: (A)ย Observer Pattern: Incorrect. Observer notifies dependent objects about changes but doesnโt handle state-based behavior changes. (B)ย State Pattern: Correct. State allows an object to change behavior when its state changes, ideal for scenarios with different states. (C) Strategy Pattern: Incorrect. Strategy enables interchangeable algorithms, not behavior change due to state. (D) Command Pattern: Incorrect. Command encapsulates requests but doesnโt change object behavior based on state. Q#3. (Code-Based Question, Single-Select) Consider the below code snippet.ย public sealed interface Document permits PDFDocument, WordDocument { void open(); } public record PDFDocument implements Document { @Override public void open() { System.out.println("Opening PDF"); } } public record WordDocument implements Document { @Override public void open() { System.out.println("Opening Word"); } } public class DocumentFactory { public Document createDocument(String type) { switch (type) { case "PDF" -> new PDFDocument(); case "Word" -> new WordDocument(); default -> throw new IllegalArgumentException("Invalid type:" +type); } } } Which design pattern does this code demonstrate? Options: A) Factory Method Pattern B) Abstract Factory Pattern C) Builder Pattern D) Prototype Pattern Answer: A) Factory Method Pattern Explanation: A) Factory Method Pattern: Correct. The Factory Method Pattern is the correct choice here because the code defines a dedicated method (createDocument) to handle object creation, shielding clients from direct instantiation logic. B) Abstract Factory Pattern: Incorrect. The Abstract Factory Pattern is incorrect because it is designed to create families of related or dependent objects (e.g., a suite of UI components like buttons, menus, and dialogs for a specific operating system). Here, the factory only generates individualย Documentย objects without any interrelated products. An Abstract Factory would necessitate multiple creation methods (e.g.,ย createDocument,ย createParser,ย createRenderer) working together, which is absent in this implementation. C) Builder Pattern: Incorrect. The Builder Pattern does not apply because it focuses on constructing complex objects through a step-by-step process, often involving many optional parameters or nested configurations. The given code creates simpleย Document objects in a single step. D) State: Incorrect. The Prototype Pattern is irrelevant here because it relies on cloning existing instances to avoid expensive creation operations. The provided factory always creates new objects from scratch using theย new keyword, with no use of cloning. Q#4. (Scenario-Based Question, Single-Select) An application has a document conversion feature with the following requirements: Converts Document Formats: It can convert documents between different formats (e.g., DOCX to PDF, PDF to HTML). Adapts to New Formats Without Code Change: The system needs to support new formats without altering existing conversion logic. Maintains Consistent Conversion Interface: All conversions should follow a standard interface, so users have a consistent experience across formats. Which design pattern would best address this system? Options: A) Adapter Pattern B) Factory Method Pattern C) Strategy Pattern D) Bridge Pattern Answer: A) Adapter Pattern Explanation: A) Adapter Pattern: Correct. The Adapter pattern enables the conversion system to handle multiple formats by providing a unified interface to interact with various formats. When new formats are introduced, adapters for these formats can be added without altering existing code, fulfilling the requirement. B) Factory Method Pattern: Incorrect. While the Factory Method can create objects based on input, it doesnโt adapt or convert interfaces, making it unsuitable for format conversion here. C) Strategy Pattern: Incorrect. The Strategy pattern would allow different algorithms to be used interchangeably but wouldnโt help adapt incompatible document formats to a standard interface. D) Bridge Pattern: Incorrect. The Bridge pattern is useful for separating an abstraction from its implementation but is unnecessary here, where adapting incompatible interfaces is the main goal. The Adapter pattern ensures that all document formats are presented through a consistent interface, making it the ideal choice here. Q#5. (Scenario-Based Question, Multi-Select) A company needs a payment processing system that: Supports Multiple Gateways: Allows integration with various payment providers (e.g., PayPal, Stripe, Square). Provides Unified Payment Interface: Offers a standardized interface so that the main application doesnโt need to know the specifics of each payment provider. Allows Adding New Gateways Easily: New payment gateways should be added without modifying the existing code. Which design pattern/(s) would be most suitable for this system? Options (Multi-Select): A) Adapter Pattern B) Facade Pattern C) Strategy Pattern D) Template Method Pattern Answer: A) Adapter Pattern and C) Strategy Pattern Explanation: A) Adapter Pattern: Correct. The Adapter pattern can be used to unify different payment provider interfaces, making them conform to a common interface for ease of integration with the application. C) Strategy Pattern: Correct. Each payment provider can be implemented as a separate strategy, allowing the application to choose the provider dynamically at runtime based on user selection or configuration. B) Facade Pattern: Incorrect. The Facade pattern would simplify complex subsystems, but it doesnโt aid in providing interchangeable providers or adapting interfaces. D) Template Method Pattern: Incorrect. The Template Method pattern would structure a series of steps but isnโt as relevant for this use case, where different providers follow varied workflows. Here, the Adapter and Strategy patterns together allow seamless integration with multiple payment providers, ensuring a standardized interface and dynamic selection capability. Q#6. (Scenario-Based Question, Single-Select) In a graphics editor, you have different shapes (like circles, squares, etc.) and wish to apply different effects (such as color or shadow) on top of these shapes dynamically. Which design pattern is best suited here? A) Decorator Pattern B) Composite Pattern C) Flyweight Pattern D) Prototype Pattern Answer: A) Decorator Pattern Explanation: (A) Decorator Pattern: Correct. Decorator is used to add responsibilities or effects dynamically without altering the core shape class. (B) Composite Pattern: Incorrect. Composite is used to create tree-like structures, not add features to individual components. (C) Flyweight Pattern: Incorrect. Flyweight minimizes memory usage but doesnโt help with adding effects dynamically. (D) Prototype Pattern: Incorrect. Prototype is used for cloning objects, not dynamically adding responsibilities. Q#7. (Concept-Based Question, Single-Select) What technique should be used in a Singleton class to prevent multiple instances from being created when the object is serialized and then deserialized? A) Implement a private constructor B) Mark the instance variable as volatile C) Implement the readResolve method D) Use double-checked locking Answer: C) Implement the readResolve method Explanation: A) Private constructor: Incorrect. While it restricts instantiation from outside the class, it doesnโt prevent multiple instances created through deserialization. B) Marking instance as volatile: Incorrect. This helps with visibility in a multithreaded environment but does not address serialization issues. C) readResolve method: Correct. Implementing readResolve ensures that upon deserialization, the existing instance is returned, maintaining the Singleton guarantee. D) Double-checked locking: Incorrect. Double-checked locking is a thread-safety mechanism for lazy initialization but does not prevent Singleton violations due to deserialization. Q#8. (Scenario-Based Question, Single-Select) A document editor requires implementing an undo feature where each action can be undone sequentially. Which pattern would effectively manage this requirement? A) Command Pattern B) Memento Pattern C) Strategy Pattern D) Chain of Responsibility Pattern Answer: B) Memento Pattern Explanation: (A) Command Pattern: Incorrect. Command is useful for encapsulating requests, but it does not inherently support state restoration. (B) Memento Pattern: Correct. Memento captures an object’s state, enabling the undo functionality by restoring previous states. (C) Strategy Pattern: Incorrect. Strategy is for interchangeable algorithms, not for restoring object states. (D) Chain of Responsibility Pattern: Incorrect. This is used for passing requests along a chain, not for maintaining object history.
Q#9. (Code-Based Question, Single-Select) Analyze the following Java code snippet: public abstract class Beverage { public final void makeBeverage() { boilWater(); addMainIngredient(); addCondiments(); pourInCup(); } protected abstract void addMainIngredient(); protected abstract void addCondiments(); private void boilWater() { System.out.println("Boiling water"); } private void pourInCup() { System.out.println("Pouring in cup"); } } Which design pattern does this code illustrate? Options: A) Template Method B) Observer C) Builder D) Facade Answer: A) Template Method Explanation: This code illustrates the Template Method pattern, where the makeBeverage method defines a series of steps, with specific methods left abstract for subclasses to implement. This ensures a predefined structure while allowing flexibility in specific steps. Observer, Builder, and Facade patterns donโt apply here, as they serve distinct purposes. Q#10. (Scenario-Based Question, Single-Select) In a drawing application, you can group shapes into complex drawings and apply actions to both individual shapes and groups uniformly. Which pattern would allow you to achieve this? A) Flyweight Pattern B) Composite Pattern C) Decorator Pattern D) Chain of Responsibility Pattern Answer: B) Composite Pattern Explanation: (A) Flyweight Pattern: Incorrect. Flyweight minimizes memory usage for many similar objects, not grouping and treating them uniformly. (B) Composite Pattern: Correct. Composite allows grouping shapes and treating both individual and complex structures as a single entity. (C) Decorator Pattern: Incorrect. Decorator dynamically adds behavior, but it doesnโt manage groups of objects. (D) Chain of Responsibility Pattern: Incorrect. Chain of Responsibility is for passing requests along a chain rather than grouping objects. Q#11. (Scenario-Based Question, Single-Select) An e-commerce website has different types of users (e.g., guest, registered, admin). Each type has varied access permissions. Which pattern can dynamically adjust the access level at runtime? A) Strategy Pattern B) State Pattern C) Observer Pattern D) Chain of Responsibility Pattern Answer: B) State Pattern Explanation: (A) Strategy Pattern: Incorrect. Strategy is for interchangeable algorithms rather than state-dependent behavior. (B) State Pattern: Correct. State pattern allows dynamic behavior change based on user type, offering a different experience for each user role. (C) Observer Pattern: Incorrect. Observer is for notifying dependent objects of changes but doesnโt change access levels. (D) Chain of Responsibility Pattern: Incorrect. Chain of Responsibility is for passing requests along a chain, not handling states.
Q#12. (Scenario-Based Question, Single-Select) In a banking app, you need to provide different account creation options (e.g., savings, checking) with shared account features but varying properties. Which pattern should you apply to ensure that different account types can be created with minimal code duplication? A) Prototype Pattern B) Factory Method Pattern C) Singleton Pattern D) Abstract Factory Pattern Answer: B) Factory Method Pattern Explanation: (A) Prototype Pattern: Incorrect. Prototype is for cloning objects rather than handling different account types. (B) Factory Method Pattern: Correct. Factory Method allows subclasses to create specific account types, minimizing code duplication. (C) Singleton Pattern: Incorrect. Singleton ensures only one instance, which doesnโt solve account type variation. (D) Abstract Factory Pattern: Incorrect here, as itโs ideal for families of related products, which isnโt necessary for simple account creation. Q#13. (Scenario-Based Question, Single-Select) An application needs to load images only when they are about to be viewed by the user, to save memory. Which pattern is best for this situation? A) Singleton Pattern B) Proxy Pattern C) Adapter Pattern D) Flyweight Pattern Answer: B) Proxy Pattern Explanation: (A) Singleton Pattern: Incorrect. Singleton controls instance count but doesnโt delay image loading. (B) Proxy Pattern: Correct. Proxy controls access and can defer image loading until necessary. (C) Adapter Pattern: Incorrect. Adapter changes interface compatibility but doesnโt defer object creation. (D) Flyweight Pattern: Incorrect. Flyweight reduces memory usage by sharing, not deferring creation. Q#14. (Scenario-Based Question, Single-Select) A logging library allows users to enable logging levels (error, debug, info) without altering existing code. Which design pattern would best support this flexibility? A) Command Pattern B) Observer Pattern C) Chain of Responsibility Pattern D) Flyweight Pattern Answer: C) Chain of Responsibility Pattern Explanation: (A) Command Pattern: Incorrect. Command encapsulates a request but isnโt ideal for sequential logging levels. (B) Observer Pattern: Incorrect. Observer notifies subscribers but doesnโt chain logging responsibilities. (C) Chain of Responsibility Pattern: Correct. Chain of Responsibility can pass requests through multiple handlers (logging levels) until they are processed. (D) Flyweight Pattern: Incorrect. Flyweight reduces memory use, not request handling across chains. Q#15. (Scenario-Based Question, Single-Select) You need to create multiple themes for a user interface, each with different font styles and color schemes, while ensuring flexibility for future themes. Which pattern best fits this use case? A) Factory Pattern B) Singleton Pattern C) Abstract Factory Pattern D) Prototype Pattern Answer: C) Abstract Factory Pattern Explanation: (A) Factory Pattern: Incorrect. Factory creates objects based on input, not a suite of related products. (B) Singleton Pattern: Incorrect. Singleton ensures one instance, irrelevant for multiple theme options. (C) Abstract Factory Pattern: Correct. Abstract Factory creates families of related objects like font styles and color schemes. (D) Prototype Pattern: Incorrect. Prototype clones existing objects, not related products. Q#16. (Scenario-Based Question, Single-Select) You are creating a system where multiple components need to access a shared object, such as a configuration manager, without creating multiple instances. Which design pattern would you use? A) Singleton Pattern B) Observer Pattern C) Adapter Pattern D) Composite Pattern Answer: A) Singleton Pattern Explanation: (A) Singleton Pattern: Correct. Singleton ensures only one instance of a class, perfect for shared objects like a configuration manager. (B) Observer Pattern: Incorrect. Observer is for notifying changes rather than managing a single instance. (C) Adapter Pattern: Incorrect. Adapter enables compatibility with different interfaces but doesnโt restrict instance count. (D) Composite Pattern: Incorrect. Composite treats grouped objects uniformly, not limiting instances.
Q#17. (Scenario-Based Question, Single-Select) You need to create a flexible notification system in which users can subscribe to receive updates on certain events. Which design pattern is best suited to implementing this notification feature? A) Observer Pattern B) Singleton Pattern C) Command Pattern D) Composite Pattern Answer: A) Observer Pattern Explanation: (A) Observer Pattern: Correct. Observer allows subscribing to updates, making it ideal for notifications. (B) Singleton Pattern: Incorrect. Singleton ensures only one instance; it doesnโt manage subscriptions. (C) Command Pattern: Incorrect. Command encapsulates requests but isnโt suitable for handling notifications. (D) Composite Pattern: Incorrect. Composite is for hierarchical structures, not event subscriptions. Q#18. (Code-Based Question, Single-Select) Observe below code snippet: public abstract class Shape { protected Color color; public Shape(Color color) { this.color = color; } abstract void draw(); } public class Circle extends Shape { public Circle(Color color) { super(color); } @Override public void draw() { System.out.print("Drawing Circle in "); color.applyColor(); } } public interface Color { void applyColor(); } public class RedColor implements Color { public void applyColor() { System.out.println("Red color"); } }
Which design pattern does this code demonstrate? A) Adapter B) Bridge C) Composite D) Flyweight Answer: B) Bridge Explanation: A) Adapter: Incorrect. The Adapter pattern is used to make incompatible interfaces work together. Here, Color and Shape are already compatible, so Adapter is not applicable. B) Bridge: Correct. The Bridge pattern decouples an abstraction (in this case, Shape) from its implementation (in this case, Color) so that they can vary independently. By using a Color interface that is passed to the Shape constructor, we can create different shape and color combinations without changing their classes. C) Composite: Incorrect. Composite pattern is used to treat a group of objects the same way as individual objects, which isnโt demonstrated here. D) Flyweight: Incorrect. Flyweight is used for sharing common states to save memory. Thereโs no evidence of shared state optimization here. Q#19. (Scenario-Based Question, Single-Select) In an e-commerce application, a user should be able to build an order with various configurations (e.g., items, shipping method, discounts). Each order configuration has specific requirements. Which pattern best allows for this flexibility? A) Builder Pattern B) Prototype Pattern C) Composite Pattern D) Chain of Responsibility Pattern Answer: A) Builder Pattern Explanation: (A) Builder Pattern: Correct. Builder simplifies constructing complex objects with varied configurations. (B) Prototype Pattern: Incorrect. Prototype clones objects but doesnโt build configurations. (C) Composite Pattern: Incorrect. Composite structures parts, not configurations. (D) Chain of Responsibility Pattern: Incorrect. Chain doesnโt help with building configurations. Q#20. (Scenario-Based Question, Single-Select)
You are developing a mobile app where a user can apply various themes, such as “dark mode” or “light mode,” without affecting the underlying structure of the app. Which design pattern should you consider? A) Bridge Pattern B) Factory Pattern C) State Pattern D) Singleton Pattern Answer: A) Bridge Pattern Explanation: (A) Bridge Pattern: Correct. Bridge separates theme interface and implementation, allowing themes to vary independently. (B) Factory Pattern: Incorrect. Factory creates instances but doesnโt manage theme and structure separation. (C) State Pattern: Incorrect. State is more suited to managing transitions, not structural independence. (D) Singleton Pattern: Incorrect. Singleton enforces one instance, unrelated to theme flexibility. Q#21. (Scenario-Based Question, Single-Select) A restaurant management app wants to allow users to place orders in a specific sequence (appetizer, main course, dessert). Each order step should execute independently but in a specified sequence. Which pattern best fits? A) Command Pattern B) Chain of Responsibility Pattern C) Decorator Pattern D) Proxy Pattern Answer: A) Command Pattern Explanation: (A) Command Pattern: Correct. Command allows encapsulation and ordering of specific actions. (B) Chain of Responsibility Pattern: Incorrect. Chain passes requests without defining execution order. (C) Decorator Pattern: Incorrect. Decorator adds behavior, irrelevant for command sequencing. (D) Proxy Pattern: Incorrect. Proxy controls access, not action sequence. Q#22. (Scenario-Based Question, Single-Select) In a logging system, log messages are handled by different handlers based on severity levels (INFO, WARNING, ERROR). A new log message with an “ERROR” level is added. Which of the following statements are correct about using the Chain of Responsibility pattern for this scenario? The “INFO” handler should forward the message to the next handler if it canโt process it. Each handler should stop the chain once it receives the log message. The “ERROR” handler, being the last in the chain, should process any unhandled requests. Options: A) Statements 1 & 2 are correct B) Statements 1 & 3 are correct C) Statements 2 & 3 are correct D) All statements are correct Answer: B Explanation: Statement 1 is correct as the “INFO” handler should forward unhandled requests to the next handler. Statement 2 is incorrect because handlers should pass unhandled messages along the chain rather than stopping it immediately. Statement 3 is correct as the “ERROR” handler should handle any unprocessed messages, acting as the last in the chain. Q#23. (Concept-Based Question, Single-Select) Which statements best describe the responsibilities of handlers in a Chain of Responsibility? Each handler can decide whether to handle or pass a request. Each handler must keep track of the previous handler in the chain. Each handler has logic to process specific requests. Options: A) Statements 1 & 2 are correct B) Statements 1 & 3 are correct C) Statements 2 & 3 are correct D) All statements are correct Answer: B Explanation: Statement 1 is correct as handlers can process or pass requests. Statement 3 is correct as each handler handles specific request types. Statement 2 is incorrect since handlers only know about the next handler, not previous ones. Q#24. (Concept-Based Question, Single-Select) Which design principle is most prominently applied in the Chain of Responsibility pattern? A) Dependency Inversion B) Open/Closed Principle C) Liskov Substitution D) Law of Demeter Answer: B Explanation: B is correct as the Open/Closed Principle allows adding new handlers without altering existing code. A, C, and D are incorrect as theyโre less central to CORโs design. Q#25. (Concept-Based Question, Single-Select) Which of the following best describes the Observer Pattern? A) A pattern used to create an interface for creating families of related objects B) A pattern where objects are arranged in a chain to handle requests sequentially C) A pattern where objects notify other objects when a change occurs in their state D) A pattern that provides a way to access elements of an aggregate object without exposing its representation Answer: C Explanation: C is correct as the Observer Pattern facilitates notification of observers when the subjectโs state changes. B, A, and D are incorrect as they describe the Chain of Responsibility, Abstract Factory, and Iterator patterns, respectively. Q#26. (Code-Based Question, Single-Select) Consider the below code snippet.ย public interface Operation{ int execute(int a, int b); } public class AddOperation implements Operation{ public int execute(int a, int b) { return a + b; } } public class SubtractOperation implements Operation{ public int execute(int a, int b) { return a - b; } } public class Calculator { private Operation operation; public Calculator(Operation operation) { this.operation= operation; } public int calculate(int a, int b) { return operation.execute(a, b); } } Which design pattern does this code demonstrate? Options: A) Chain of Responsibility B) Template Method C) Strategy D) State Answer: C) Strategy Explanation: A)ย Chain of Responsibility: Incorrect. Chain of Responsibility passes requests down a chain, unrelated to this codeโs dynamic operation selection. B) Template Method: Incorrect. Template Method defines a skeleton algorithm in a superclass with customizable steps, not interchangeable strategies. C)ย Strategy: Correct. The Strategy pattern defines a family of algorithms (addition and subtraction here) that can be swapped at runtime. Calculator uses Strategy to perform a calculation with a specific operation. D) State: Incorrect. State pattern is for managing state-dependent behavior, not interchangeable algorithms. More Questions? If you want to practice on more similar type of questions covering all the topics in Java Design Patterns, kindly visit any of the below channels: Udemy course: Java Design Patterns Practice Test & Interview Questions. You will have a life time access to these practice tests. These set of practice tests are extension to aforementioned sample questions. These are new set of practice tests having more than 500 questions created recently. When you get the access of the practice tests, you are advised to go through the explanation of each question thoroughly. It will help you clearing your concept on a particular topic. Amazon eBook: Utilize the free access to kindle unlimited reading. For amazon.in users: Master Java Design Patterns with 500+ Solved MCQs & 1000+ Concepts Explanations For amazon.com users:ย Master Java Design Patterns with 500+ Solved MCQs & 1000+ Concepts Explanations Here, you can also utilize the free access to kindle unlimited reading. Additionally, check for the availability of other formats of the book in your respective region.