Can an object remove itself? How?

前端 未结 5 867
我在风中等你
我在风中等你 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条回答
  •  臣服心动
    2021-01-17 16:02

    The object can remove itself given it has some sort of reference to the view rendering mechanism. Your sample doesn't give enough information so I'll exemplify one way to do it:

    public class Ball {
        private ViewRenderer view;
    
        public void remove() {
           view.remove(this);
        }
    }
    

    Neither suicide nor murder is better or worse. It depends on your design and requirements.

    In this sample though, murder might be preferable since this way the Ball object doesn't need to know in which context it's being used.

提交回复
热议问题