dimanche 19 novembre 2017

Can you spot a design pattern?

Saw the code in a training task, which got me thinking if there's it's a known pattern or anti-pattern or something else and if there are any downsides of composing instances this way. The idea in a nutshell:


Class hierarchy:

class Animal {
    String animalField;
}

class Pet extends Animal {
    String petField;
}

class Dog extends Pet {
    String dogField;
}

Something that creates animals.

class AnimalCreator {

    FieldGenerator fieldGenerator;

    public Animal create() {
        Animal animal = new Animal();
        animal.animalField = fieldGenerator.getAnimalField();
        return animal;
    }
}

class PetCreator extends AnimalCreator {

    public Pet create() {
        Animal animal = super.create();
        Pet pet = new Pet(animal); // copy constructor
        pet.petField = fieldGenerator.getPetField();
        return pet;
    }
}

class DogCreator extends PetCreator {

    public Dog create() {
        Pet pet = super.create();
        Dog dog = new Dog(pet); // copy constructor
        dog.dogField = fieldGenerator.getDogField();
    }
}

The idea is that if we want to add a new type we can reuse the code for generating existing fields. The FieldGenerator could be anything, might even ask you to type in fields in the console.

Aucun commentaire:

Enregistrer un commentaire