Singletons and Static Fields in RAP

The classical singleton pattern suggests that a class has only one instance and keeps the reference to this instance in a static field. In RAP, this pattern is dangerous, because static values are kept in the class, which is shared among different user sessions and different applications. As an example, if a copy of the user's shopping cart is kept as a singleton, this would work on the desktop, but in RAP, all users would share the same shopping cart instance.

Instead of using singletons and static fields, all data must be kept in the correct scope in RAP. RAP provides a helper class SingletonUtil that can create session-unique instances of a given class, so called session singletons. In the context of one UI session SingletonUtil.getSessionInstance( Class ) will always return the same object, but for different user sessions the returned instances will be different. The following code snippet illustrates this pattern:

public class MySessionSingleton {
  private MySessionSingleton() {
    // prevent instantiation from outside
  }

  public static MySessionSingleton getInstance() {
    return SingletonUtil.getSessionInstance( MySessionSingleton.class );
  }

  // other methods ...
}

Note that SingletonUtil can only be used in the context of a UI session.

Another way to replace static fields is to use one of RAP's data stores.