vendredi 18 février 2022

How can I structure my classes which usually need to be called together?

I have some related classes that implement the same method

class Dog {
    public void speak() { System.out.println("Bark") }
}
class Cat {
    public void speak() { System.out.println("Meow") }
}

90% of the time, users would want both the dog and the cat to speak. They don't want to know the details. When we add a new animal, they'll want it to speak too. The idea is to avoid:

// All animals need to be explicitly told to speak every time
new Dog().speak();
new Cat().speak();

// But we just added Birds, and the users need to remember to add this call everywhere
new Bird.speak();

I could do something like

class Animals {
    public void speak() {
        new Dog().speak();
        new Cat().speak();
        new Bird().speak();
    }
}

So that users can just call new Animals().speak() every time.

However, 10% of the time, it does need to be configurable. What I want is a way for users to do something like this

// Used most of the time
Animals.withAllAnimals().speak();

// Sometimes they don't want cats, and they want the dogs to woof instead
Animals.exclude(Cat)
  .configure(Dog.sound, "Woof")
  .speak();

How can I structure my classes to accomplish this?

Aucun commentaire:

Enregistrer un commentaire