Q1. Ina chat application, youwant users to receive updates about messages in a chat room only when they’re subscribed to that room. The system should also manage the communication between different chat rooms. Which combination of patterns is suitable?
- Observer Pattern
- Adapter Pattern
- Chain of Responsibility Pattern
- Mediator Pattern
Answer: A) Observer Pattern and D) Mediator Pattern
Explanation:-
- Observer Pattern: Correct. The Observer pattern suits the need for notifying subscribers of updates in a chat room.
- Adapter Pattern: Incorrect. Given scenario doesn’t satisfy the features of Adapter pattern.
- Chain of Responsibility Pattern: Incorrect. Given scenario doesn’t satisfy the features of the Chain of Responsibility pattern.
- Mediator Pattern: Correct. Mediator pattern facilitates coordinated communication among different chat rooms.
- Question 2. There are four statements about the participants involved in the context of Adapter Pattern.
1. Target: The domain-specific class that the client uses.
2. Adapter: A class that implements the Target interface and adapts the Adaptee to it.
3. Adaptee: An existing class with an incompatible interface that needs adapting.
4. Client: The class that interacts with the Target class.
Which of the following option is correct?
A) Statements 1 & 2 are correct
B) Statements 1 & 3 are correct
C) Statements 2 & 3 are correct
D) All statements are correct
Answer: C
Explanation:
Statement 2 (Correct): Adapter is a class that implements the Target interface and adapts the Adaptee to it.
Statement 3 (Correct): Adaptee is an existing class with an incompatible interface that needs adapting.
Statement 1 (Incorrect): Target is the domain-specific interface that the client uses. It’s not a class, but interface.
Statement 4 (Incorrect): Client is the class that interacts with the Target interface, but not the Target class.
Q3. Consider the following code snippet.What design pattern does this code demonstrate?
public class CPU {
public void start() {
System.out.println("CPU started.");
}
}
public class Memory {
public void load() {
System.out.println("Memory loaded.");
}
}
public class HardDrive {
public void read() {
System.out.println("Hard drive reading.");
}
}
public class Computer {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
public void startComputer() {
cpu.start();
memory.load();
hardDrive.read();
}
}
A) Prototype
B) Builder
C) Mediator
D) Facade
Answer: D) Façade
• D) Facade: Correct. The Facade pattern simplifies a complex system by providing a unified interface. Here, ComputerFacade starts the system with simplified calls to CPU, Memory, and HardDrive.
A) Prototype: Incorrect. Prototype clones existing objects, unrelated to simplifying complex systems as in Facade.
B) Builder: Incorrect. Builder constructs complex objects step-by-step, which isn’t represented here.
C) Mediator: Incorrect. Mediator centralizes interactions between objects, unlike the unifying interface shown here.
Q4. An e-commerce platform wants to implement a product recommendation system that:
- Provides Real-Time Recommendations: As users browse, the system recommends similar items based on categories like “frequently bought together,” “similar items,” and “recently viewed.”
- Allows Custom Recommendation Algorithms: Developers can plug in various recommendation algorithms without altering the main recommendation flow, such as collaborative filtering, content-based filtering, and user-based filtering.
- Logs Recommendation Events: The system logs user interactions with recommended items (e.g., clicks, add-to-cart actions) to analyze engagement data, and it should be extensible to add more logging features without modifying existing code.
Which design pattern(s) would be most appropriate to implement this recommendation system?
- Strategy Pattern
- Decorator Pattern
- Chain of ResponsibilityPattern
- Observer Pattern
Answer: A) Strategy Pattern and B) Decorator Pattern
Explanation:–
- Strategy Pattern: Correct. The Strategy pattern is perfect for situations where multiple algorithms can be used interchangeably. Here, different recommendation algorithms (like collaborative, content-based, and user-based filtering) can be designed as separate strategies, allowing developers to change them without modifying the main recommendation engine. This keeps the recommendation flow flexible and adaptable.
- Decorator Pattern: Correct. The Decorator pattern allows for dynamically adding behaviours to objects, such as logging additional data or adding new features without altering existing code. In this case, as new logging requirements are introduced, the Decorator pattern provides a structured way to extend logging features for recommendation events without modifying the core recommendation classes, enhancing maintainability.
- Chain of Responsibility Pattern: Incorrect. Although the Chain of Responsibility pattern allows handling requests across multiple handlers, it isn’t ideal for scenarios that require dynamic selection of algorithms or the addition of logging functionalities. This pattern wouldn’t meet the system’s goals as effectively as the Strategy and Decorator patterns.
- Observer Pattern: Incorrect. The Observer pattern is used to notify multiple objects about changes in another object’s state, but it doesn’t suit the need to select recommendation algorithms or enhance logging capabilities for this recommendation system.
This scenario illustrates how the Strategy pattern offers flexible algorithm selection while the Decorator pattern allows seamless addition of features, meeting both the recommendation and logging needs of the system.
Q5. Analyse the following code snippet.
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Which of the followingapproach is being used to ensure a thread-safe Singleton implementation?
(Code-based, Single-select)
- Eager Initialization
- Synchronized Method
- Double-Checked Locking
- Holder Class (Bill Pugh Method)
Answer: C) Double-Checked Locking Explanation:
- Eager Initialization: Eager initialization creates the Singleton instance as soon as the class is loaded, without any lazy loading.
- Synchronized Method: A synchronized method locks the entire method, whereas in this code only a block within getInstance is synchronized.
- Double-Checked Locking: The code checks twice if instance is null, synchronizing only the first time a thread tries to initialize it.
- Holder Class (Bill Pugh Method): This approach uses a static inner class for lazy initialization, not double-checked locking.
Q6. In which of the following situations is the Builder pattern particularly useful?
(Concept-based, Multi-select)
- A) When the object construction process involves multiple steps
- B) When there are several optional parameters in an object
- C) When the object type varies based on the input provided
- D) When a single constructor with multiple parameters would be confusing
Answer: A) When the object construction process involves multiple steps; B) When there are several optional parameters in an object; D) When a single constructor with multiple parameters would be confusing
Explanation:
- A) Multiple construction steps: Correct. The Builder pattern is ideal for scenarios
with multiple construction steps.
- B) Optional parameters: The Builder pattern allows for optional parameters without numerous constructors.
- C) Varying object types: This is better suited for Factory Method, not Builder.
- D) Complex constructor parameters: Builder pattern helps avoid large, confusing constructors.
Q#7. Analyze the following Singleton implementation. Which aspect of it ensures thread safety in a multithreaded environment?
(Code-based, Single-select)
public class Singleton {
privatestatic volatileSingletoninstance;
privateSingleton() {}
publicstatic SingletongetInstance () {
if(instance == null){
synchronized (Singleton.class) {
if(instance ==null){
instance =newSingleton ();
}
}
}
returninstance;
}
}
- A)The synchronized block
- B)The volatile keyword
- C)The private constructor
- D)Both synchronized block and volatile keyword
Answer: D) Both synchronized block and volatile keyword
Explanation:
- A) synchronized block: Partially correct. While synchronized blocks control access to initialization, they work with the volatile keyword to ensure full thread safety.
- B) volatile keyword: Partially correct. volatile ensures visibility of changes across threads but cannot by itself prevent multiple threads from entering the block initially.
- C) Private constructor: The private constructor only prevents external instantiation, not multithreaded issues.
- D) Both synchronized block and volatile keyword: Together, synchronized and volatile ensure thread-safe Singleton instantiation in a double-checked locking approach.
Q#8. Which of the followingadditions would you make to the following HouseBuilder class to ensureitfollows the Builder pattern correctly?
(Code-based,Single-select)
public class HouseBuilder{
private int rooms;
private boolean hasGarage;
private boolean hasSwimmingPool;
public HouseBuilder setRooms(int rooms) {
this.rooms = rooms;
return this;
}
public HouseBuilder setGarage(boolean hasGarage) {
this.hasGarage = hasGarage;
return this;
}
public HouseBuilder setSwimmingPool(boolean hasSwimmingPool) {
this.hasSwimmingPool = hasSwimmingPool;
return this;
}
}
- A) Add a House class to be built and a build() method that returns a House object
- B) Add a HouseBuilderInterface to define the build methods
- C) Create a Director class to initialize House Builder
- D) Replace method chaining with a constructor
Answer: A) Add a House class to be built and a build() method that returns a House object
Explanation:
- A) House class with build(): Correct. A build() method is essential to the Builder pattern, returning the final object.
- B) HouseBuilderInterface: An interface isn’t strictly required for this implementation.
- C) Director class: Incorrect. While useful, a Director class is optional. • D) Constructor without chaining: Incorrect. Removing chaining would go against the Builder’s design.
Q#9. You are building a report generation tool with various formats like PDF, CSV, and XML. Each format has specific formatting rules, but all follow a general generation process. Which design pattern should you use?
(Scenario-based, Single-select)
- A) Template MethodPattern
- B) Observer Pattern
- C) Builder Pattern
- D) Singleton Pattern
Answer: A) Template Method Pattern Explanation:
- (A) Template Method Pattern: Correct. Template Method allows general process control with format-specific steps.
- (B) Observer Pattern: Incorrect. Observer monitors changes, not suitable for process definition.
- (C) Builder Pattern: Incorrect. Builder constructs complex objects but doesn’t define process templates.
- (D) Singleton Pattern: Incorrect. Singleton controls instances, irrelevant to templated steps.
Q#10. Which of the following are correctly matched with their respective Design Pattern categories?
(Concept-based, Multi-select)
- A) Structural pattern: Flyweight, Adapter, Proxy
- B) Creational pattern: Factory Method, Builder, Memento
- C) Behavioral pattern: Observer, Chain of Responsibility, Command
- D) Behavioral pattern: Template Method, Iterator, Decorator
Answer: A) and C) Explanation:
- (A) Flyweight, Adapter, Proxy: Correct. These are all Structural Patterns
- (C) Observer, Chain of Responsibility, Command: Correct. These are Behavioral Patterns.
- (B) Factory Method, Builder, Memento: Incorrect. Memento is a Behavioral Pattern, while the others are Creational Patterns.
- (D) Template Method, Iterator, Decorator: Incorrect. Decorator is a Structural Pattern, not Behavioral.

