AJAX In Action [50]
Singleton pattern
In some situations, it is important to ensure that there is only one point of contact with a particular resource. Again, this is best explained by working with a specific example, so let’s look at one now.
A simple trading example
Let’s say that our Ajax application manipulates stock market data, allowing us to trade on the real markets, perform what-if calculations, and run simulation games over a network against other users. We define three modes for our application, named after traffic lights. In real-time mode (green mode), we can buy and sell stocks on live markets, when they are open, and perform what-if calculations against stored datasets. When the markets are closed, we revert to analysisonly mode (red mode) and can still perform the what-if analyses, but we can’t buy or sell. In simulation mode (amber mode), we can perform all the actions available to green mode, but we do so against a dummy dataset rather than interacting with real stock markets.
Our client code represents these permutations as a JavaScript object, as defined here:
var MODE_RED=1;
var MODE_AMBER=2;
var MODE_GREEN=2;
function TradingMode(){
this.mode=MODE_RED;
}
We can query and set the mode represented in this object and will do so in our code in many places. We could provide getMode() and setMode() functions that would check conditions such as whether or not the real markets were open, but for now let’s keep it simple.
Let’s say that two of the options open to the user are to buy and sell stocks and to calculate potential gains and losses from a transaction before undertaking it. The buy and sell actions will point to different web services depending on the mode of operation—internal ones in amber mode, our broker’s server in green mode—and will be switched off in red mode. Similarly, the analyses will be based on retrieving data feeds on current and recent prices—simulated in amber mode and live market data in green mode. To know which feeds to point to, both will refer to a TradingMode object as defined here (figure 3.4).
Licensed to jonathan zheng 88 CHAPTER 3 Introducing order to Ajax Simulation Simulation server server Client Client buyOrSell() buyOrSell() analyzeData() Live trading analyzeData() Live trading server server Mode =AMBER Mode = GREEN Simulation Client server buyOrSell() Mode = AMBER Live trading analyzeData() server Mode = GREEN Figure 3.4 In our example Ajax trading application, both buy/sell and analysis functions determine whether to use real or simulated data based on a TradingMode object’s status, talking to the simulation server if it is in amber mode and to the live trading server in green mode. If more than one TradingMode object is present in the system, the system can end up in an inconsistent state. It is imperative that both activities point to the same TradingMode object. If our user is buying and selling in a simulated market but basing her decisions on analysis of live market data, she will probably lose the game. If she’s buying and selling real stocks based on analysis of a simulation, she’s apt to lose her job! An object of which there is only one instance is sometimes described as a sin- gleton. We’ll look at how singletons are handled in an object-oriented language first and then work out a strategy for using them in JavaScript. Singletons in Java Singletons are typically implemented in Java-like languages by hiding the object constructor and providing a getter method, as illustrated in listing 3.3. Listing 3.3 Singleton TradingMode object in Java public class TradingMode{ private static TradingMode instance=null; public int mode; Licensed to jonathan zheng Some small refactoring case studies 89 private TradingMode(){ mode=MODE_RED; } public static TradingMode getInstance(){ if (instance==null){ instance=new TradingMode(); } return instance; } public void setMode(int mode){ ... } } The Java-based solution makes use of the private and public access modifiers to