When to use Factory method pattern?

后端 未结 10 1473
南旧
南旧 2020-12-12 14:56

When to use Factory method pattern?

Please provide me some specific idea when to use it in project? and how it is a better way over new keyword?

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 16:01

    I have two cases where I tend to use it:

    1. The object needs to be initialized in some specific manner
    2. When I want to construct a specific type based on an abstract type (an abstract class or an interface).

    Examples:

    1. First case could be that you want to have a factory creating SqlCommand objects, where you automatically attach a valid SqlConnection before returning the command object.

    2. Second case is if you have an interface defined and determine at execution time which exact implementation of the interface to use (for instance by specifying it in a configuration file).

提交回复
热议问题