| <?xml version="1.0" encoding="UTF-8" ?> |
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
| "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| <html xmlns="http://www.w3.org/1999/xhtml"> |
| <head> |
| <meta name="copyright" content="Copyright (c) 2012, 2019 EclipseSource. This page is made available under license. For full details see the LEGAL in the documentation book that contains this page."/> |
| <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> |
| <title>Singletons and Static Fields in RAP</title> |
| <link rel="stylesheet" href="../../../PRODUCT_PLUGIN/book.css" type="text/css"/> |
| </head> |
| <body> |
| |
| <h1>Singletons and Static Fields in RAP</h1> |
| |
| <p> |
| 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, <strong>this pattern is dangerous</strong>, because static values are kept in the |
| <i>class</i>, 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. |
| </p> |
| <p> |
| Instead of using singletons and static fields, all data must be kept in the correct scope in RAP. |
| RAP provides a helper class |
| <em><a href="../reference/api/org/eclipse/rap/rwt/SingletonUtil.html">SingletonUtil</a></em> |
| that can create session-unique instances of a given class, so called <em>session singletons</em>. |
| In the context of one UI session |
| <em><a href="../reference/api/org/eclipse/rap/rwt/SingletonUtil.html#getSessionInstance-java.lang.Class-">SingletonUtil.getSessionInstance( Class )</a></em> |
| will always return the same object, |
| but for different user sessions the returned instances will be different. |
| The following code snippet illustrates this pattern: |
| </p> |
| <pre class="lang-java"> |
| public class MySessionSingleton { |
| private MySessionSingleton() { |
| // prevent instantiation from outside |
| } |
| |
| public static MySessionSingleton getInstance() { |
| return SingletonUtil.getSessionInstance( MySessionSingleton.class ); |
| } |
| |
| // other methods ... |
| } |
| </pre> |
| <p> |
| <strong>Note</strong> that <em>SingletonUtil</em> can only be used in the context of a |
| <a href="threads.html">UI session</a>. |
| </p> |
| <p> |
| Another way to replace static fields is to use one of RAP's |
| <a href="data-stores.html">data stores</a>. |
| </p> |
| |
| |
| </body> |
| </html> |