dimanche 16 septembre 2018

How to increase a new type and don't need to modify factory class?

when i'm using factory pattern, i got a question : when i have a new type ,i need to modify my factory class. such as that:

Animal.java:

public interface Animal {
    void eat();
}

Dog.java:

public class Dog implements Animal {
    ...
    @Override
    public void eat(){
        System.out.println("eat bones");
    }
}

Cat.java

public class Cat implements Animal {
    ...
    @Override
    public void eat(){
        System.out.println("eat fish");
    }
}

Now I have an Animal interface and two Animal classes, then i have my factory here:

public class AnimalFactory {
    public static final int Dog = 1;
    public static final int Cat = 2;

    public static Animal getAnimal(int type) {
        switch(type) {
           case Dog: return new Dog();
           case Cat: return new Cat();
           default: return null;
        }
    }
}

It's very simple, but if i have a new type Mouse ,I have to modify my factory to add a case statement like case Mouse: return new Mouse .

So, it's there a way to in increase new type and don't need to modify my factory class?

Aucun commentaire:

Enregistrer un commentaire