考虑以下java代码
public class PlayerView implements IPlayerListener
{
public Player player;
public PlayerView()
{
player = new Player();
player.listener = this;
}
public void onPlayerEvent()
{
}
}
public class Player
{
public IPlayerListener listener;
public void foo()
{
//do something then
if(this.listener != null)
{
this.listener.onPlayerEvent();
}
}
}
public interface IPlayerListener
{
public void onPlayerEvent();
}
这里我有一个 PlayerView 和 Player。Player 需要向 PlayerView 报告事件,所以我创建了一个名为 IPlayerListener 的接口,Player 可能有一个 PlayerListener 对象的引用来报告事件。
(我知道在 java 中这不是创建事件的最佳方式,但我真的不需要“许多侦听器”来使用默认的“addEventListener”模式)
问题一:当 PlayerView 对象设置为 null 时,PlayerView 和 Player 对象都会被 GC 收集吗?
如果是,则继续执行以下代码
public class PlayerView implements IPlayerListener, IPlaylistListener
{
public Player player;
public PlayerView()
{
player = new Player();
player.listener = this;
player.playlist = new Playlist();
player.playlist.listener = this;
}
public void onPlayerEvent()
{
}
public void onPlaylistEvent()
{
}
}
public class Player
{
public Playlist playlist;
public IPlayerListener listener;
public void foo()
{
//do something then
if(this.listener != null)
{
this.listener.onPlayerEvent();
}
}
}
public class Playlist
{
public IPlaylistListener listener;
public void bar()
{
//do something then
if(this.listener != null)
{
this.listener.onPlaylistEvent();
}
}
}
public interface IPlayerListener
{
public void onPlayerEvent();
}
public interface IPlaylistListener
{
public void onPlaylistEvent();
}
在这里,我添加了第三个类,播放列表类,播放器也有一个播放列表对象的引用。播放列表也应该有一个监听器/观察器。在这种情况下,PlayerView 也是播放列表侦听器。
问题2:当PlayerView对象设置为null时,这些对象会被GC回收吗?
如果答案 #2 为否,请继续
public class PlayerView implements IPlayerListener, IPlaylistListener
{
public Player player;
public PlayerView()
{
player = new Player();
player.listener = this;
player.playlist = new Playlist();
player.playlist.parentPlayer = player;
}
public void onPlayerEvent()
{
}
public void onPlaylistEvent()
{
}
}
public class Player
{
public Playlist playlist;
public IPlayerListener listener;
public void foo()
{
//do something then
if(this.listener != null)
{
this.listener.onPlayerEvent();
}
}
}
public class Playlist
{
public Player parentPlayer;
public void bar()
{
//do something then
if(this.parentPlayer != null)
{
if(this.parentPlayer.listener != null)
{
if(this.parentPlayer.listener instanceof IPlaylistListener)
{
((IPlaylistListener) this.parentPlayer.listener).onPlaylistEvent();
}
}
}
}
}
public interface IPlayerListener
{
public void onPlayerEvent();
}
public interface IPlaylistListener
{
public void onPlaylistEvent();
}
这里我将 playlistListener 引用切换为对父 Player 的引用,而不是直接调用 playlistListener,而是检查 playerListener 是否也是一个 PlaylistListener(或者两个接口可以合并为一个)
问题 #3:前面的代码会解决问题并收集所有对象吗?
或者我应该更好地使用第二个代码块并在 PlayerView 对象中找到正确的时间(就像在将 PlayerView 对象从其父视图中删除之前)并至少调用“player.playlist.listener = null;”。