How does a factory know which type of object to create?

前端 未结 5 1711
旧时难觅i
旧时难觅i 2021-02-05 12:04

I believe the factory method design pattern is appropriate for what I\'m trying to do, but I\'m not sure how much responsibility (knowledge of subclasses it creates) to give it.

5条回答
  •  礼貌的吻别
    2021-02-05 12:28

    Factory should have some idea about choosing the actual object to create. For example, WebRequest.Create method in .NET, should be able to choose between the different protocol clients by checking the protocol part of the Uri. It doesn't need to parse the whole thing. Just the part required to distinguish which class is going to be responsible for it (in your example, it'll probably be just the file header).

    Regarding your question about breaking encapsulation, not really... Most of the time, the factory is hardcoded and already knows about different types of classes and their features. It already depends on the functionality offered by a known set of classes, so you are not adding much to it. You can also encapsulate the detection part of the factory in another helper class that can be used both by the factory and the subclasses (in the sprit of DRY principle).

提交回复
热议问题