假设 Igor 已在 ServantLoader 中注册,可以很方便地将 can() 调用改得更实用,并重用前面的 Servant 代码,如清单 9 所示:
清单 9. Igor 做了什么
import java.io.*;
import java.util.*;
public class Servant
{
public static void main(String[] args)
throws IOException
{
ServiceLoader<IPersonalServant> servantLoader =
ServiceLoader.load(IPersonalServant.class);
IPersonalServant i = null;
for (IPersonalServant ii : servantLoader)
if (ii.can("fetch body parts"))
i = ii;
if (i == null)
throw new IllegalArgumentException("No suitable servant found");
for (String arg : args)
{
i.process(new File(arg));
}
}
}
import java.util.*;
public class Servant
{
public static void main(String[] args)
throws IOException
{
ServiceLoader<IPersonalServant> servantLoader =
ServiceLoader.load(IPersonalServant.class);
IPersonalServant i = null;
for (IPersonalServant ii : servantLoader)
if (ii.can("fetch body parts"))
i = ii;
if (i == null)
throw new IllegalArgumentException("No suitable servant found");
for (String arg : args)
{
i.process(new File(arg));
}
}
}
真正 DSL 实现显然不会仅仅打印到标准输出流。我把追踪哪些部分、跟随哪些部分的细节留待给您(当然,还有忠诚的 Igor)。
4. Timer
java.util.Timer 和 TimerTask 类提供了方便、相对简单的方法可在定期或一次性延迟的基础上执行任务: