What are static factory methods?

前端 未结 14 753
粉色の甜心
粉色の甜心 2020-11-22 06:08

What\'s a \"static factory\" method?

14条回答
  •  礼貌的吻别
    2020-11-22 06:41

    A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.

    For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.

    If you want to implement database pooling, then that would also be done without affecting the rest of the application.

    It protects the rest of the application from changes that you may make to the factory, which is the purpose.

    The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.

提交回复
热议问题