how to delete singleton object

前端 未结 3 643
不知归路
不知归路 2021-01-19 10:49

Assuming this implementation of a singleton pattern ( of course we should avoid Singleton: it is just question), I have just been thinking about static object being created.

3条回答
  •  悲&欢浪女
    2021-01-19 11:14

    The classical singleton pattern does not describe the deletion aspect.

    However, if I have to do it, I would start with a simple approach like the following (it is not fool-proof):

    1) Similar to the static method for creating/retrieving the singleton object, say createObject(), there is a static method for destructing the singleton object, say destructObject()

    2) There is a counter which counts the current number of objects in the system;

    • it starts at 0
    • on createObject() call, it increments by 1
    • on deleteObject() call, it decrements by 1.
      • If it reaches 0, then the delete is called to actually destruct the object

提交回复
热议问题