Sobes.tech
Junior — Middle

Millist disainimustritsa kasutaksite objekti käitumise kohandamiseks sõltuvalt päevaajast?

sobes.tech AI

Vastus AI-lt

To adapt the behavior of an object depending on the time of day, the "Strategy" design pattern is very suitable.

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 you to easily change the behavior of the object without modifying its code.