Код: Выделить всё
public interface Animal {
void speak();
}
public class Dog implements Animal{
void speak (){
System.out.println("This is dog.")
}
}
public class Cat implements Animal{
void speak (){
System.out.println("This is cat.")
}
}
@Module
public class Module{
@Provides
@Named("Dog")
static Animal providesDog() {
return new Dog();
}
@Provides
@Named("Cat")
static Animal providesCat() {
return new Cat();
}
}
public class AnimalOrchestrator {
@Inject
Animal animal;
public void speak(String type) {
if(type.equals("dog")
(Dog) animal.speak();
else
(Cat) animal.speak();
}
}
Ниже приведены некоторые другие способы использования которым достигается такая функциональность.
Код: Выделить всё
public class AnimalOrchestrator {
@Inject
Dog dog;
@Inject
Cat cat;
public void speak(String type) {
if(type.equals("dog")
dog.speak();
else
cat.speak();
}
}
Другой способ следующий:
Код: Выделить всё
public class AnimalOrchestrator {
Animal animal;
public void speak(String type) {
if(type.equals("dog"){
animal = new Dog();
animal.speak();
} else {
animal = new Cat();
animal.speak();
}
}
}
Это первое решение даже возможно? Если да, то какой из них лучше?
Подробнее здесь: https://stackoverflow.com/questions/785 ... dependency