By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,377 Members | 1,655 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,377 IT Pros & Developers. It's quick & easy.

Singleton

P: n/a
Ugo
Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

var singletonClass = (function( )
{
// Private variable
var instance = null;

// Private Constructor
function myClass( )
{
//...
}

return new function( )
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
}

return instance;
}
}
})( );
Jun 27 '08 #1
Share this Question
Share on Google+
29 Replies


P: n/a
On Wed, 7 May 2008 10:42:51 +0200, Ugo <pr*****@nospam.itwrote:
>Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

var singletonClass = (function( )
{
// Private variable
var instance = null;

// Private Constructor
function myClass( )
{
//...
}

return new function( )
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
}

return instance;
}
}
})( );
Pure qui? :-))
se ti vede ZERO...
ciao
Jun 27 '08 #2

P: n/a
Do you know a better way of this one:
Yes

change this:
* *return new function( )

to this:
return function( )

;-)
Jun 27 '08 #3

P: n/a
On May 7, 11:06*am, RoLo <roloswo...@gmail.comwrote:
Do you know a better way of this one:

Yes

change this:
** *return new function( )

to this:
* * return function( )

;-)
ok... sorry, I over read you code.. you can ignore my previous comment.
Jun 27 '08 #4

P: n/a
Ugo
>>Hi guys,
>>how do you make a singleton access class?
Do you know a better way of this one:
[cut]
Pure qui? :-))
ehh, gi :)
Mi tornato questo cruccio, e non so' fare n trovare di meglio...
per tanto o provato a vedere cosa ne pensano qui...
se ti vede ZERO...
ssshhh, zitto, non dire niente che forse non se ne accorge
:P
ciao
Bye
Jun 27 '08 #5

P: n/a
Ugo wrote:
how do you make a singleton access class?
How do you define a "singleton access class"?
Do you know a better way of this one:
The best way of doing something depends at least in part on what it is
you are trying to do.
var singletonClass = (function( )
{
// Private variable
var instance = null;
There is little point in assigning null to this variable as its default
undefined value will be just as false as the null value when you test it
with - !instance -.
// Private Constructor
function myClass( )
{
//...
}

return new function( )
I can think of no circumstances under which it makes sense to use the -
new - operator with a function expression as its operand. In this case
it would be simpler (and more efficient) to have an object literal
returned at this point. That object could easily define - constructor -
and - getInstance - properties.
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
As you are using a constructor to create this object instance it would
be possible to define the created object's - constructor property on the
prototype of the constructor. Though there may be no good reason for
using a contractor to create the object at all as you are only going to
be creating one instance of the object, and so again a literal could be
used instead.
}

return instance;
}
}
})( );
The result of those changes could look like:-

var singletonClass = (function( ){
// Private variable
var instance;
return ({
constructor:null,
getInstance:function( ){
return (
instance||
(
instance = {
constructor:null
}
)
);
}
});
})();

- though that is almost certainly less than would be needed in any real
context, but you will always suffer that if you don't define what it is
exactly that you are trying to achieve.

Richard.

Jun 27 '08 #6

P: n/a
On May 7, 1:42 am, Ugo <priv...@nospam.itwrote:
Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

var singletonClass = (function( )
{
// Private variable
var instance = null;

// Private Constructor
function myClass( )
{
//...
}

return new function( )
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
}

return instance;
}
}

})( );
This does not look like something a JavaScript programmer would write.
In JavaScript, assigning an object literal to a global variable would
likely achieve the purpose of a Singleton pattern in Java, for
example, for many situations. What is your real application?

Peter
Jun 27 '08 #7

P: n/a
Ugo
>how do you make a singleton access class?
How do you define a "singleton access class"?
i wanted a function/object which restricts the instantiation of one my
object one time and which it ables one global access
>Do you know a better way of this one:

The best way of doing something depends at least in part on what it is
you are trying to do.
A generic way to create a singleton object (and if it's possible I'd like
to adopt the GoF's "roles" - applyed to JS)
>var singletonClass = (function( )
{
// Private variable
var instance = null;

There is little point in assigning null to this variable as its default
undefined value will be just as false as the null value when you test it
with - !instance -.
IMHO, (new myClass()) can not be null|false|undefined..
so that initialization was good
> // Private Constructor
function myClass( )
{
//...
}

return new function( )

I can think of no circumstances under which it makes sense to use the -
new - operator with a function expression as its operand. In this case
it would be simpler (and more efficient) to have an object literal
returned at this point. That object could easily define - constructor -
and - getInstance - properties.
ahh, in effect :P
> {
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;

As you are using a constructor to create this object instance it would
be possible to define the created object's - constructor property on the
prototype of the constructor. Though there may be no good reason for
using a contractor to create the object at all as you are only going to
be creating one instance of the object, and so again a literal could be
used instead.
Mmm
> }

return instance;
}
}
})( );

The result of those changes could look like:-
let's look at
var singletonClass = (function( ){
// Private variable
var instance;
return ({
constructor:null,
getInstance:function( ){
return (
instance||
(
instance = {
constructor:null
}
)
);
}
});
})();
Ok, it's no much different of mine, you have converted my code with object
literal
- though that is almost certainly less than would be needed in any real
context, but you will always suffer that if you don't define what it is
exactly that you are trying to achieve.
see before

THKS
Jun 27 '08 #8

P: n/a
On May 23, 7:22 am, Ugo <priv...@nospam.itwrote:
how do you make a singleton access class?
How do you define a "singleton access class"?

i wanted a function/object which restricts the instantiation of one my
object one time and which it ables one global access
Do you know a better way of this one:
The best way of doing something depends at least in part on what it is
you are trying to do.

A generic way to create a singleton object

I doubt that is what Richard meant by "what it is you are trying to
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.

A generic way to create a singleton object with global access is to
use a object literal.

var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};

Peter
Jun 27 '08 #9

P: n/a
Ugo wrote:
IMHO, (new myClass()) can not be null|false|undefined..
Yes, it can ;-)

function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jun 27 '08 #10

P: n/a
On 23. Mj, 20:45 h., Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
Ugo wrote:
IMHO, (new myClass()) can not be null|false|undefined..

Yes, it can ;-)
You are just plain wrong.
function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());
Irrelevant code - what does it prove?
Jun 27 '08 #11

P: n/a
On May 23, 11:45 am, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
Ugo wrote:
IMHO, (new myClass()) can not be null|false|undefined..

Yes, it can ;-)

function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());
That is "null"|"false"|"undefined"

Try this

function myClass() {
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

var inst = (new myClass());
if (inst === null ||
inst === false ||
inst === undefined) {
alert('Thomas is right');
}
else {
alert('Thomas is wrong');
}

This is, of course, the expected behavior according to ECMAScript
spec. Please see section 13.2.2.

Peter

P.S. I do appreciate the humor. I was just playing Thomas.

Footnotes:
"P.S." is abbreviation for "post scriptum", a Latin expression meaning
"after writing"
Jun 27 '08 #12

P: n/a
P. Prikryl wrote:
Thomas 'PointedEars' Lahn wrote:
>Ugo wrote:
>>IMHO, (new myClass()) can not be null|false|undefined..
Yes, it can ;-)
You are just plain wrong.
Or I could have made a joke.
> function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());
Irrelevant code - what does it prove?
It has proven that Google Groups and your irony detector are borken.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #13

P: n/a
Ugo
>>The best way of doing something depends at least in part on what it is
>>you are trying to do.
A generic way to create a singleton object
I doubt that is what Richard meant by "what it is you are trying to
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.
all this things :P
A generic way to create a singleton object with global access is to
use a object literal.

var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};
But, in this way I can not to declare "private" variables/methods in an
elegant way:

I don't like it:

var singleton;

(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}

// Obj
singleton = {
hi : b,
a: a
};
})();
Jun 27 '08 #14

P: n/a
VK
On May 24, 7:58 pm, Ugo <priv...@nospam.itwrote:
>The best way of doing something depends at least in part on what it is
you are trying to do.
A generic way to create a singleton object
I doubt that is what Richard meant by "what it is you are trying to
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.

all this things :P
A generic way to create a singleton object with global access is to
use a object literal.
var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};

But, in this way I can not to declare "private" variables/methods in an
elegant way:

I don't like it:

var singleton;

(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}

// Obj
singleton = {
hi : b,
a: a
};

})();
The way I'm using most often - without any claims that it is the best
out of anything:

function MySingleton() {
if (this == self) {
window.alert('Conctructor called as a function');
return MySingleton;
}
else if (
!!($isInstantiated.flag) ||
(this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this))
) {
window.alert('Only one instance is allowed');
return mySingleton;
}
else {
// instantiate your singleton
// with methods and properties
// ...
this.toString = $toString;
$isInstantiated.flag = true;
}
function $isInstantiated() {
return arguments.callee.flag;
}
function $toString() {
return ''.concat(
'function mySingleton() {\n',
' [native code]\n',
'}'
);
}
}

The benefits as I see them:
1) It is much lesser convoluted as function expression ways.
Respectively it is easier to read, to maintain and to avoid parasite
closures.
2) It allows to distinct different "not allowed" situation so to
provide more informative errors - in a real case window.alert replaced
by throw new Error of course.
3) it prevents or at least makes much harder to use reliably runtime
cloning over source code dumping and reusing in eval or new Function.
Jun 27 '08 #15

P: n/a
On May 24, 8:58 am, Ugo <priv...@nospam.itwrote:
>The best way of doing something depends at least in part on what it is
you are trying to do.
A generic way to create a singleton object
I doubt that is what Richard meant by "what it is you are trying to
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.

all this things :P
A generic way to create a singleton object with global access is to
use a object literal.
var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};

But, in this way I can not to declare "private" variables/methods in an
elegant way:

I don't like it:

var singleton;

(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}

// Obj
singleton = {
hi : b,
a: a
};

})();
Why don't you "like it"? Because it does not involve a constructor
function? Because it is not like Java? These seem like unfortunates
reason to avoid the simplest most direct technique to achieve your
goal. What you have written above is one normal way to write a
JavaScript singleton and is far simpler than your previous code
examples.

I am not always so concerned with this sort of closure "privacy" and
would just write

var singleton = {
_a: 1,
hi: function() {alert('hi');}
};

Some folks argue against the underscore privacy convention but I think
they are fooling themselves that things can be protected in
JavaScript. Someone could come along and reassign to the singleton
variable and destroy everything anyway.

Peter
Jun 27 '08 #16

P: n/a
VK
On May 24, 8:13 pm, VK <schools_r...@yahoo.comwrote:
On May 24, 7:58 pm, Ugo <priv...@nospam.itwrote:
>>The best way of doing something depends at least in part on what it is
>>you are trying to do.
>A generic way to create a singleton object
I doubt that is what Richard meant by "what it is you are trying to
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.
all this things :P
A generic way to create a singleton object with global access is to
use a object literal.
var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};
But, in this way I can not to declare "private" variables/methods in an
elegant way:
I don't like it:
var singleton;
(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
singleton = {
hi : b,
a: a
};
})();

The way I'm using most often - without any claims that it is the best
out of anything:

function MySingleton() {
if (this == self) {
window.alert('Conctructor called as a function');
return MySingleton;
}
else if (
!!($isInstantiated.flag) ||
(this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this))
) {
window.alert('Only one instance is allowed');
return mySingleton;
}
else {
// instantiate your singleton
// with methods and properties
// ...
this.toString = $toString;
$isInstantiated.flag = true;
}
function $isInstantiated() {
return arguments.callee.flag;
}
function $toString() {
return ''.concat(
'function mySingleton() {\n',
' [native code]\n',
'}'
);
}

}

The benefits as I see them:
1) It is much lesser convoluted as function expression ways.
Respectively it is easier to read, to maintain and to avoid parasite
closures.
2) It allows to distinct different "not allowed" situation so to
provide more informative errors - in a real case window.alert replaced
by throw new Error of course.
3) it prevents or at least makes much harder to use reliably runtime
cloning over source code dumping and reusing in eval or new Function.
A few errors made while pulling out the code and readjusting for
posting, sorry. The corrected version would be:

function MySingleton() {
if (this == self) {
window.alert('Conctructor called as a function');
return MySingleton;
}
else if (
!!($isInstantiated.flag) &&
((this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this)))
) {
window.alert('Only one instance is allowed');
return MySingleton;
}
else {
// instantiate your singleton
// with methods and properties
// ...
this.toString = $toString;
$isInstantiated.flag = true;
}
function $isInstantiated() {
return arguments.callee.flag;
}
function $toString() {
return ''.concat(
'function mySingleton() {\n',
' [native code]\n',
'}'
);
}
}
Jun 27 '08 #17

P: n/a
Ugo
[cut]
>I don't like it:
var singleton;
(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
singleton = {
hi : b,
a: a
};
})();

Why don't you "like it"? Because it does not involve a constructor
function? Because it is not like Java? These seem like unfortunates
reason to avoid the simplest most direct technique to achieve your
goal. What you have written above is one normal way to write a
JavaScript singleton and is far simpler than your previous code
examples.
But, reconsidering...
it's applicatively equal to my original code:
[by step]
it'was the same:
var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return {
hi : b,
a: a
};
})();

that is analog to:

var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return new function()
{
this.hi = b;
this.a = a;
};
})();

my origina code
Jun 27 '08 #18

P: n/a
On May 24, 3:02 pm, Ugo <priv...@nospam.itwrote:
[cut]
I don't like it:
var singleton;
(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
singleton = {
hi : b,
a: a
};
})();
Why don't you "like it"? Because it does not involve a constructor
function? Because it is not like Java? These seem like unfortunates
reason to avoid the simplest most direct technique to achieve your
goal. What you have written above is one normal way to write a
JavaScript singleton and is far simpler than your previous code
examples.

But, reconsidering...
it's applicatively equal to my original code:
[by step]
it'was the same:

var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return {
hi : b,
a: a
};

})();

that is analog to:

var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return new function()
{
this.hi = b;
this.a = a;
};

})();

my origina code

Given the original post...

On May 7, 1:42 am, Ugo <priv...@nospam.itwrote:
Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:
[snip]

I believe I have presented several options that I think are better and
actually are standard JavaScript patterns?

What is it you want from the group?

Peter
Jun 27 '08 #19

P: n/a
Ugo
[cut]
[snip]

I believe I have presented several options that I think are better and
actually are standard JavaScript patterns?

What is it you want from the group?
Sorry, I didn't want to seem ungrateful :(
I'm very happy about "several options" were listed...

In addition, I wanted to adopt the guide lines of GoF's pattern, and
parhaps I succeed:
var SingletonClass;
(function()
{
var instance;
SingletonClass = function( )
{
if( this == window )
{
alert( 'This is no function!' );
return;
}
// else if( this.prototype != SingletonClass.prototype )
else if( ! ( this instanceof SingletonClass ) )
{
alert( 'Che cavolo stai dicendo Willis!' );
return;
}
else if( instance )
return instance;
else
instance = this;

this.$ = 'hi';
this.f = function()
{
alert( this.$ );
}
}
SingletonClass.getInstance = function( )
{
return instance || ( instance = new SingletonClass( ) );
}
})();
Jun 27 '08 #20

P: n/a
VK
On May 25, 11:01 am, Ugo <priv...@nospam.itwrote:

The solution is unnecessary convoluted by extra closures not bearing
any functional load. That is IMHO and OK if someone just loves
closures so collecting different species of them like orchids :-)

The possible failure point is in "not allowed" checks like:
if( this == window )
{
alert( 'This is no function!' );
return;
}
// else if( this.prototype != SingletonClass.prototype )
else if( ! ( this instanceof SingletonClass ) )
{
alert( 'Che cavolo stai dicendo Willis!' );
return;
}
If a function is called as constructor, thus in the context "new
SingletonClass" or "new DerivedSingletonClass", then the return value
_must_ be an object. If it tries to return a primitive value then such
return value will be silently disregarded and the current value of
"this" will be returned instead. This behavior is by design and by
ECMAScript specs.
This way say having:
else if (
!!($isInstantiated.flag) &&
((this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this)))
) {
window.alert('Only one instance is allowed');
// WRONG:
return;
}
}
your constructor doesn't return undefined as one would possibly expect
but "this" value, so still a new instance just not fully initialized
by properties and methods.

To overcome that in "not allowed" situations you have either:
1) return a reference to the constructor:
return SingletonClass;
2) throw Error _and_ return a reference to the constructor to
eliminate any possible "resume next" attempts.
3) return false wrapped into Boolean object for further condition
checks:
return new Boolean;
Jun 27 '08 #21

P: n/a
Ugo <pr*****@nospam.itwrites:
In addition, I wanted to adopt the guide lines of GoF's pattern, and
parhaps I succeed:
var SingletonClass;
(function()
{
var instance;
SingletonClass = function( )
{
if( this == window )
{
alert( 'This is no function!' );
return;
}
// else if( this.prototype != SingletonClass.prototype )
else if( ! ( this instanceof SingletonClass ) )
{
alert( 'Che cavolo stai dicendo Willis!' );
return;
....
SingletonClass.getInstance = function( )
{
return instance || ( instance = new SingletonClass( ) );
}
})();
Seems like massive overkill, probably due to not having stated
your requirements precisely.

I'd just do:

var SingletonClass = (function(){
var instance = { $ : 'hi', f : function() { alert(this.$); } };
return function() {
return instance;
}
})();

Or, if you really, really require lazy construction:

var SingletonClass = (function() {
var instance;
function createInstance() {
return {
$: 'hi',
f: function f() { alert(this.$); }
};
}
// or SingletonClassConstructor.prototype.f = function(){alert(this.$);};
return function() {
return instance || (instance = createInstance());
};
})();
You are trying to use class based patterns in a prototype based
language. A singleton type is only necessary in a class based language
because objects needs a type. In a prototype based language, you
can create an object directly, so there is no need to introduce
an otherwise unnecessary type for a single object.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #22

P: n/a
Lasse Reichstein Nielsen <lr*@hotpop.comwrites:
I'd just do:
Ok, I too would actually just do:

var singleton = {
$: 'hi,
f: function() { alert(this.$); }
}

Notice that this is how the Math object works: just a plain object,
no constructor, "type" or "class" at all.
(As opposed to how, e.g., Java does it, where there is a Class with
all static methods).

You want a single object. You don't need a "type" with a single
instance for that. That's what comes from thinking in classes,
and wanting every object to have a class. Javascript does not
need that.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #23

P: n/a
VK
On May 25, 3:42 pm, Lasse Reichstein Nielsen <l...@hotpop.comwrote:
In a prototype based language, you
can create an object directly, so there is no need to introduce
an otherwise unnecessary type for a single object.
From a clean pattern point of view it is arguable IMHO. If there is an
object distinctly different from the generic Object then why not to
introduce a specific constructor for it? Besides, the singleton can be
the privileged consumer of other objects' methods where it would be
more convenient to check if (Consumer instanceof MySingleton) rather
than using some workaround checks.

About the overwhelming "closuring" I do agree but it is just the Java/
C-way AFAIK. "The encapsulation is above everything else" -
inheritance, memory leaks, resource consuming - nothing is matter as
long as it is possible to encapsulate yet another chunk into
something. With a CS graduate - so full 4-6 years cycle of such
"training" - not too much possible to do besides nice side advises to
be disregarded :-)

Jun 27 '08 #24

P: n/a
VK <sc**********@yahoo.comwrites:
On May 25, 3:42 pm, Lasse Reichstein Nielsen <l...@hotpop.comwrote:
>In a prototype based language, you
can create an object directly, so there is no need to introduce
an otherwise unnecessary type for a single object.

From a clean pattern point of view it is arguable IMHO. If there is an
object distinctly different from the generic Object then why not to
introduce a specific constructor for it?
How is it different from a generic object? It has properties, and
that's all that really matters. The Math object does fine in this way.
No need for a constructor, because there is no need to construct
any more!
Besides, the singleton can be the privileged consumer of other
objects' methods where it would be more convenient to check if
(Consumer instanceof MySingleton) rather than using some workaround
checks.
Why check at all? Just call the method and document that objects
passed here should have such a method.
(An it's not like you can't circumvent the singleton'ness anyway,
if you really want to, or change the properties of the singleton
object).
The problem with the Singleton (anti-)pattern is that it shouldn't
be visible. If it makes sense to have a type, then there is no
reason to restrict to just one instance at the design level.
The implementation might only need one (but experience tells me
that, e.g., testing usually requires alternatives).

The singleton idea combines two concerns into one class: The behavior
of the class and that there should be a single designated instance
that an application should use.

These two concerns could just as easily be separated into two
classes: the class itself and a toolbox/factory class for controlling
instancing.
<URL:http://www.ibm.com/developerworks/webservices/library/co-single.html>

Hmm, guess I'm just rambling against singletons in general.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #25

P: n/a
VK
On May 25, 5:11 pm, Lasse Reichstein Nielsen <l...@hotpop.comwrote:
From a clean pattern point of view it is arguable IMHO. If there is an
object distinctly different from the generic Object then why not to
introduce a specific constructor for it?

How is it different from a generic object? It has properties, and
that's all that really matters. The Math object does fine in this way.
No need for a constructor, because there is no need to construct
any more!
Well, it doesn't always do _everything_ what one needs, let's do not
exaggerate ;-)
Just off my head it is often irritating that some important math
values are stored in Number and some in Math. In a rush coding I keep
mixing where to get what. So one can have a Math based derivative for
say BigMath calculations:

function BigMath() {
this.MAX_VALUE = Number.MAX_VALUE;
this.MIN_VALUE = Number.MIN_VALUE;
// other properties
}
BigMath.prototype = Math;

var m = new BigMath;
alert(m.MAX_VALUE);
alert(m.PI);
Besides, the singleton can be the privileged consumer of other
objects' methods where it would be more convenient to check if
(Consumer instanceof MySingleton) rather than using some workaround
checks.

Why check at all?
Because some methods have to be called only in a certain way and from
certain consumers. Such need happens, at least to me.
Just call the method and document that objects
passed here should have such a method.
(An it's not like you can't circumvent the singleton'ness anyway,
if you really want to, or change the properties of the singleton
object).
Oh definitely, anything can be broken or reverse-engineered. I do not
agree though that it is the reason to have everything as generic
Object instances and just keep dumping / removing properties as the
need goes. It may be fine for some form validator, but for a rich
application it will soon become a maintenance nightmare IMO.

....
Hmm, guess I'm just rambling against singletons in general.
Looks like to me too :-) Bad life experience with them?

Jun 27 '08 #26

P: n/a
On May 25, 12:01 am, Ugo <priv...@nospam.itwrote:
[cut]
[snip]
I believe I have presented several options that I think are better and
actually are standard JavaScript patterns?
What is it you want from the group?

Sorry, I didn't want to seem ungrateful :(
I'm very happy about "several options" were listed...

In addition, I wanted to adopt the guide lines of GoF's pattern, and
parhaps I succeed:
[snip convoluted code]

I read in the last few days that, when asked, Eric Gamma says the two
patterns he would no longer include in "Design Patterns" are the
Visitor and Singleton patterns. I don't have a reference for this.
Search Reddit. The justification is these patterns are too complex for
what they provide. In the case of the Singleton, a global variable can
do the job. JavaScript is particularly well suited for a global
singleton pattern. I think if you don't have extraordinary
circumstances then it is always best to program a language in a way
that is natural for that language. The other option is imposing design
patterns from languages that have deficiencies. JavaScript doesn't
have singleton deficiencies but does have class-based inheritance
deficiencies, for example.

Peter
Jun 27 '08 #27

P: n/a
Peter Michaux wrote:
On May 23, 7:22 am, Ugo wrote:
>>>how do you make a singleton access class?
How do you define a "singleton access class"?

i wanted a function/object which restricts the instantiation
of one my object one time and which it ables one global access
>>>Do you know a better way of this one:
>>The best way of doing something depends at least in part on
what it is you are trying to do.

A generic way to create a singleton object

I doubt that is what Richard meant by "what it is you are trying
to do". You are more likely trying to "implement a tabbed pane
widget" or "send user data to the server".
Those would not be the types of things that I meant. They are too far
detached from their own implementation details to say anything about
what is wanted from this 'singleton' object that might constrain its
implementation.
Unless this is just an academic exercise.
It would not mater if it was an academic exercise.
A generic way to create a singleton object with global access
is to use a object literal.

var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};
Quite right. From that simplest possible starting point there is a huge
spectrum of possible implementations running up to the ludicrously
elaborate and complex. For every step away from that simple starting
point there should be a purpose/justification/reason, and it should be
possible for the person taking that step to state what that was. And so
is it what is wanted from the object that becomes the guide as to which
steps are taken to achieve it.

Richard.

Jun 27 '08 #28

P: n/a
Ugo wrote:
>>how do you make a singleton access class?
How do you define a "singleton access class"?

i wanted a function/object which restricts the instantiation
of one my object one time and which it ables one global access
Which, as Peter pointed out, is actually extremely simple to achieve.
>>Do you know a better way of this one:

The best way of doing something depends at least in part on
what it is you are trying to do.

A generic way to create a singleton object
Why a "generic way"? Are you writing a javascript code generator that
needs to insert other code into a structure that will accommodate all
possibilities? Otherwise being generic is probably not that good an
idea.
(and if it's possible I'd like
to adopt the GoF's "roles" - applyed to JS)
Generally it seems to be possible to do anything you can imagine with
javascript, but being able to do something is not a good enough reason
for doing it in itself.
>>var singletonClass = (function( )
{
// Private variable
var instance = null;

There is little point in assigning null to this variable as its
default undefined value will be just as false as the null value
when you test it with - !instance -.

IMHO, (new myClass()) can not be null|false|undefined..
so that initialization was good
<snip>

I cannot tell what you mean from that. Assigning null is a pointless
thing to do in this case.

Richard.

Jun 27 '08 #29

P: n/a
Ugo wrote:
<snip>
>I believe I have presented several options that I think are
better and actually are standard JavaScript patterns?

What is it you want from the group?

Sorry, I didn't want to seem ungrateful :(
I'm very happy about "several options" were listed...

In addition, I wanted to adopt the guide lines of GoF's pattern,
and parhaps I succeed:

var SingletonClass;
(function()
Separating the global variable declaration from the code that
initialises it is probably not a good idea in this case. In copying this
code from place to place you risk the two becoming separate.
{
var instance;
SingletonClass = function( )
{
if( this == window )
{
alert( 'This is no function!' );
return;
}
// else if( this.prototype != SingletonClass.prototype )
else if( ! ( this instanceof SingletonClass ) )
{
alert( 'Che cavolo stai dicendo Willis!' );
return;
}
What utter nonsense. If you must have a constructor (which itself does
not make much sense if it is you intention that only one object will
ever be instantiated) and you don't want it called from other/external
code, and you are already using the inline execution of a function
expression to create a private scope, then don't mess around writing all
this code to check for misuse. Just leave the constructor in the private
scope were the external code cannot see and so cannot call it.

<snip>
this.$ = 'hi';
<snip>

The language specification for javascript (ECMA 262) states that the $
symbol "is intended for use only in mechanically generated code".

Richard.

Jun 27 '08 #30

This discussion thread is closed

Replies have been disabled for this discussion.