Can an object remove itself? How?

前端 未结 5 869
我在风中等你
我在风中等你 2021-01-17 15:31

I\'m trying to write a simple ball game, and there\'s several turns (ie., ball lives). The ball \"dies\" when it passes the bottom border of the screen. What I have so far w

5条回答
  •  梦毁少年i
    2021-01-17 16:04

    There is presumably some object (e.g. the Screen, or the ViewRenderer in Johan's example) that holds a reference to the Ball, and removing this reference has to be done by the Screen ("object murder"). "Object suicide" amounts to Ball passing a message to the Screen asking to be "murdered".

    Since it is the Ball that knows when it has passed the boundary, it makes sense to me (without knowing the details of your design) for the removal to be initiated by the Ball. Then the Screen can find out about this change by one of several means:

    • The Screen can poll the Ball.
    • The Ball can hold a direct backward reference to the Screen, which creates an unfortunate circular dependency.
    • The Ball can hold a reference to the screen via a BallObserver interface. This is an application of the observer pattern.

    The first is simplest, and this makes it a good choice if it fits naturally into your mechanism for painting the screen. The third is more flexible in principle, but you might not need this flexibility in practice. The middle option might be OK in a simple program, but you should probably consider it as a step on the way to the third.

    And if you don't have a Screen (or ViewRenderer, or whatever) object and really mean "a separate method call in the main program" then you should probably reconsider your design.

提交回复
热议问题