Junior — Middle
What design pattern would you apply to adapt the behavior of an object depending on the time of day?
sobes.tech AI
Answer from AI
To adapt the behavior of an object depending on the time of day, the Strategy design pattern is well suited.
The idea is that you have a common behavior interface, and specific implementations (strategies) change depending on the time of day — for example, morning, daytime, and evening strategies.
Example in Java:
interface Behavior {
void execute();
}
class MorningBehavior implements Behavior {
public void execute() {
System.out.println("Good morning!");
}
}
class EveningBehavior implements Behavior {
public void execute() {
System.out.println("Good evening!");
}
}
class Context {
private Behavior behavior;
public void setBehavior(Behavior behavior) {
this.behavior = behavior;
}
public void performBehavior() {
behavior.execute();
}
}
// Usage:
Context context = new Context();
LocalTime now = LocalTime.now();
if (now.isBefore(LocalTime.NOON)) {
context.setBehavior(new MorningBehavior());
} else {
context.setBehavior(new EveningBehavior());
}
context.performBehavior();
This approach allows easy changing of object behavior without modifying its code.