Reputation: 32321
I have a classes and interface as shown
package com;
public interface Animal {
public void makeSound();
}
Dog.java
package com;
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Ruf Ruf");
}
}
Cat.java
package com;
public class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow Meow");
}
}
Tester.java
public class Tester {
public static void main(String args[]) {
Tester tester = new Tester();
Dog dog = new Dog();
Cat cat = new Cat();
tester.show(dog);
}
public void show(Animal animal) {
animal.makeSound();
}
}
Why do one need a Factory Pattern as i could accomplish the task using polymorphism?
I was following this tutorial tutorialspoint.com/design_pattern/factory_pattern.htm so in this case what is the use of ShapeFactory class here ??
Upvotes: 0
Views: 78
Reputation: 109567
IF you take a look at implementing-factory-design-pattern-in-java you'll see a factory based on an enumeration.
so here one could use an Animal factory, have an
enum AnimalFamily { CAT, DOG }
and use that to create animals.
I doubt the factory pattern makes sense here.
However discovery of capabilities (lookup) is similar to the factory pattern. And concerns this case.
Usage:
Optional<MakingSound> soundCapability = animal.lookup(MakingSound.class);
if (soundCapability.isPresent()) {
makingSound.makeSound();
}
interface Animal {
<T> Optional<T> lookup(Class<T> klazz);
}
interface MakingSound {
void makeSound();
}
// Base class
class AbstractAnimal implements Animal {
protected Map<Class<?>, Object> capabilities;
@Override
public <T> Optional<T> lookup(Class<T> klazz) {
Object capability = capabilities.get(klazz);
T c = klazz.cast(capability);
return Optional.ofNullabel(c);
}
}
class Dog extends Abstract Animal {
Dog() {
capabilities.put(MakingSound.class, new MakingSound() {
@Override
public void makeSound() {
System.out.println("Ruf Ruf");
}
});
// Java 8 style
capabilities.put(MakingSound.class,
() -> System.out.println("Ruf Ruf"));
}
}
This allows fish without making sounds, adding dynamic capabilties like flying. And so on. Whether this is done as factory or as above, using a prefilled map, ...
(I have use java 8's Optional here as it fits.)
Upvotes: 1
Reputation: 36304
Factory Pattern is used to create Objects i/e, it is a Creational Pattern.
In your example if you had a class AnimalFactory
, which produced your cats and dogs, then it would be a factory pattern.
What you are really doing in your posted code is creating the Dog
and Cat
objects yourself and calling an overridden method (which is dynamically dispatched based on the object type). In factory pattern you depend on another entity to generate your objects for you
Upvotes: 3