【发布时间】:2018-03-27 07:30:18
【问题描述】:
我想用 Java 编写一个带有自定义事件的简单事件处理解决方案。到目前为止,我只找到了使用 ActionListeners 的基于 GUI 的示例。我已经包含了一个我用 C# 编写的代码。
我想在 Java 中创建类似的东西:
using System;
using System.Threading;
namespace EventHandlingPractice
{
class Program
{
static void Main(string[] args)
{
MusicServer mServer = new MusicServer();
Sub subber = new Sub();
mServer.SongPlayed += subber.SubHandlerMethod;
mServer.PlaySong();
Console.ReadKey();
}
}
// this class will notify any subscribers if the song was played
public class MusicServer
{
public event EventHandler SongPlayed;
public void PlaySong()
{
Console.WriteLine("The song is playing");
Thread.Sleep(5000);
OnSongPlayed();
}
protected virtual void OnSongPlayed()
{
if (SongPlayed != null)
SongPlayed(this, EventArgs.Empty);
}
}
// this class is class is the subscriber
public class Sub
{
public void SubHandlerMethod(object sender, EventArgs e)
{
Console.WriteLine("Notification from: " + sender.ToString() + " the song was played");
}
}
}
【问题讨论】:
-
您可以遵循观察者模式,即 ActionListeners 的实现。
标签: java c# events eventhandler