双重间谍和Java借口

public interface BritishSpy {
  public String speak(); //英国间谍讲英语
}
public interface GermanSpy {
  public String sprechen(); //德国间谍讲德语
}
public class DoubleAgent implements BritishSpy, GermanSpy {
  public String speak() { return "Hello"; }
  public String sprechen() { return "Gutentag"; }
}
public class Agency {
  public static void toMI5(BritishSpy spy) {
    //军情5处当然只能说英语,做英国间谍
    spy.speak();
    //spy.sprechen();不可见
  }
  public static void inGermany(GermanSpy spy) {
    //spy.speak();不可见
    spy.sprechen();
  }
  public static void main(String[] args) {
    DoubleAgent da = new DoubleAgent();
    EnglishSpy es = (EnglishSpy) da;
    GermanSpy gs = (GermanSpy) da;
    toMI5(da); //MI5也不知道他是一个双重间谍,只知道他是BritishSpy
    toMI5(es); //更安全
    //toMI5(gs); 不可能
    inGermany(da); //在德国还是安全的,德国人不知道他的双重间谍身份,只知道他是GermanSpy
    inGermany(gs);
    //inGermany(es); 不可能
  }
}
Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: