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

前端 未结 5 1715
旧时难觅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:39

    Both are valid choices depending on context.

    IF you're architecting for extensibility - say a plugin model for different ImageReaders - then your Factory class cannot know about all possible ImageReaders. In that case, you go the ImageReader.CanRead(ImageStream) route - asking each implementer until you find one that can read it.

    Beware, that sometimes ordering does matter here. You may have a GenericImageReader that can handle JPGs, but a Jpeg2000ImageReader that is better at it. Walking the ImageReader implementers will stop at whichever is first. You may want to look at sorting the list of possible ImageReaders if that's a problem.

    Otherwise, if the list of ImageReaders is finite and under your control, then you can go the more traditional Factory approach. In that case, the Factory decides what to create. It's already coupled to the concrete implementations of ImageReader by the ctor, so adding rules for each ImageReader doesn't increase coupling. If the logic to pick a ImageReader is mainly in the ImageReader itself, then to avoid duplication of code, you can still go the ImageReader.CanRead(ImageStream) route - but it could just be hardcoded which types you walk.

提交回复
热议问题