Hi All,
Have spent the last hour looking for a singleton class in prototype,
with not a large amount of luck.
Found a reasonable attempt by Jim Higgson at
http://jimhigson.blogspot.com/2009/01/prototype-singleton-classes.html
but didn't like the fact that if you called new again it threw an
exception. To my mind, calling new should simply return the instance. I
realise that this goes against the normal singleton design pattern which
should be used with getInstance() rather than new, but as we can't make
'new' private as we would in other languages I felt that 'new' was the
logical function to make sure it got the singleton instance (i.e. it is
more likely to be used by others to create an object in Javascript and
with no compile to warn you until runtime, it should 'just work').
To make it work like that I have used the following code. Comments on
anything that you don't like, or that might cause an issue would be
appreciated.
var STUser = Class.create(
{
initialize: function() {
if (!STUser._instance) {
this.getInstance(); // Actual instance contructor, sets up
variables etc.
}
return this;
},
getInstance: function() {
this._timePeriod = 120;
},
getTimePeriod: function() {
return STUser._instance._timePeriod;
},
setTimePeriod: function(timePeriod) {
STUser._instance._timePeriod = timePeriod;
}
});
STUser._instance = new STUser();
Tested with the following code...
var user = new STUser();
alert(User 1 Time = + user.getTimePeriod());
user.setTimePeriod(100);
alert(User 1 Time = + user.getTimePeriod());
var user2 = new STUser();
alert(User 2 Time = + user2.getTimePeriod());
Which worked as advertised,
Appreciate any feedback, and wonder if I missed something out of
prototype as was surprised there wasn't (or I couldn't find) a singleton
pattern.
--
daff
SOFTWARE ENGINEER
andrew 'daff' niles | spider tracks ltd | 117a the square
po box 5203 | palmerston north 4441 | new zealand
P: +64 6 353 3395 | M: +64 21 515 548
E: d...@spidertracks.co.nz mailto:d...@spidertracks.co.nz
W: www.spidertracks.com http://www.spidertracks.com
--
You received this message because you are subscribed to the Google Groups Prototype
script.aculo.us group.
To post to this group, send email to prototype-scriptacul...@googlegroups.com.
To unsubscribe from this group, send email to
prototype-scriptaculous+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/prototype-scriptaculous?hl=en.