简体   繁体   中英

Is it OK to use covariance of types with abstract factory pattern

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:

  • If you deal with a factory by programming to its interface, the implementation is perfectly hidden from you
  • If, on the other hand, you deal with the factory directly, you can avoid casts.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM