简体   繁体   English

可以使用抽象工厂模式的类型协方差

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

I'm learning about design patterns from GOF book. 我正在学习GOF书中的设计模式。

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: 这是展示Java中协变覆盖的强大功能的完美案例,因为它可以让您拥有两全其美的优势:

  • 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. 另一方面,如果你直接与工厂打交道,你可以避免演员表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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