一个物体可以自行移除吗?怎么样? [英] Can an object remove itself? How?

查看:82
本文介绍了一个物体可以自行移除吗?怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的球类游戏,并且有几个回合(即,球的生命)。当球通过屏幕的底部边界时,球死亡。到目前为止我的工作,但似乎不是正确的做事方式:

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 works, but doesn't seem to be the proper way to do things:

if (ball.getY() > bottomOfScreen) {
  ball.die();
  remove(ball);
}

die()方法基本上会慢慢淡化球的颜色(dark_gray - >暂停(50) - > light_gray - > pause(50)),但实际上并没有做任何有用的事情。

The die() method basically fades the ball's colour slowly (dark_gray -> pause(50) -> light_gray -> pause(50)), but doesn't actually do anything useful.

显然,remove()摆脱了球从屏幕上,这就是我想要的。对于我来说这个remove()是Ball的die()方法的一部分是有意义的,而不是它是主程序中的单独方法调用 - 但我不知道该怎么做呢?

The remove(), obviously, gets rid of the ball from the screen, which is what I want. It makes sense to me for this remove() to be a part of Ball's die() method, as opposed to it being a separate method call in the main program -- but I'm not sure how to go about this?

对象可以自行删除吗?并且,如果可以的话,对象自杀比对象谋杀更好,从哲学/方法论的角度来看?

Can an object delete itself? And, if it can, is object suicide better than object murder, from a philosophical/methodological point of view?

谢谢!

推荐答案

对象可以自行删除,因为它对视图渲染机制有某种引用。您的示例没有提供足够的信息,因此我将举例说明一种方法:

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.

在这个例子中,谋杀可能更好,因为这样 Ball object 需要知道它在哪个上下文中使用。

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.

这篇关于一个物体可以自行移除吗?怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆