I'm learning about design patterns from GOF book.
There is one thing about Abstract Factory pattern implementation that makes me mingle. I'll start with code:
Abstract Factory:
public interface AnimalsFactory {
Animal getWaterAnimal();
Animal getLandAnimal();
Animal getFlyingAnimal();
}
Concrete Factory:
public class SafariAnimalsFactory implements AnimalsFactory {
@Override
public Hippo getWaterAnimal() {
return new Hippo();
}
@Override
public Giraffe getLandAnimal() {
return new Giraffe();
}
@Override
public Vulture getFlyingAnimal() {
return new Vulture();
}
}
I used covariance of types so factory methods return concrete products instead of abstract products (Animal).
I like it but doesn't this violate rule of thumb about products being encapsulated from the client? Or maybe I'm overthinking this.
Using covariance in this situation is great. This is a perfect case for demonstrating the power of covariant overrides in Java, because it lets you have the best of both worlds:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.