简体   繁体   English

如何在Play中实现用户特定的类型通用行为?

[英]How to realize user-specific type-generic behaviour in Play?

Say I wanted to build an application as follows: A user can log in and create some observing mechanisms, that eg lookup a twitter hashtag or check some stocks every hour. 假设我要按以下方式构建应用程序:用户可以登录并创建一些观察机制,例如,每小时查找一个Twitter主题标签或检查一些股票。

  1. You have to have a User object that eg saves email and password for the user to log in. 您必须具有一个User对象,例如,保存电子邮件和密码以供用户登录。
  2. You have to have some Java Code that eg establishes a HttpURLConnection, for both stocks and twitter 您必须具有一些Java代码,例如为股票和Twitter建立一个HttpURLConnection。
  3. You have to save user-specific settings for those services: eg userA wants #hashtag1 but user2 wants #anotherTag 您必须为这些服务保存用户特定的设置:例如,userA需要#hashtag1但user2需要#anotherTag

For scientific purpose I don't want to have every possible combination of those observers (twitter, stocks, ...) but rather have an abstract class "Observer" that both "TwitterObserver" and "StocksObserver" extend or something. 出于科学目的,我不想让这些观察者(推特,股票等等)拥有所有可能的组合,而是拥有一个抽象类“ Observer”,它既可以扩展“ TwitterObserver”又可以扩展“ StocksObserver”。

The problem I'm facing is this: 我面临的问题是:

I am not able to eg select all observers (no matter of type), iterate over them, check if modified and react on user-specific behaviour. 我无法例如选择所有观察者(无论类型如何),对其进行迭代,检查是否已修改并对用户特定的行为做出反应。 To put it another way: I cannot have a generic "Observer"-Class in combination with classes holding user-specific settings for this observer. 换句话说:我不能将通用的“观察者”类与包含用于该观察者的用户特定设置的类结合使用。

Is there any design pattern or best-practice to model this behavior? 是否有任何设计模式或最佳实践来对此行为建模? I can't believe it's all that hard. 我简直不敢那么难。

I'm thankful for every hint! 我很感谢每一个提示! Thank you guys 感谢大伙们

In your GenericObserver class create an application job to collect the specific types: 在您的GenericObserver类中,创建一个应用程序作业以收集特定的类型:

public class Observer {
  // common properties and methods

  public static List<Observer> observers = new ArrayList<Observer>();

  public static void respondUserBehavior() {
    for (Observer observer: observers) {
      // call each observer to respond to user behavior
    }
  }

  @OnApplicationStart
  public static class ObserverCollector extends Job<?> {
    @Override public void doJob() {
      observers.addAll(play.Play.classLoader.getAssignableClasses(Observer.class));
      // or you might want to loop through the list and filter out the abstract classes
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM