473,573 Members | 3,075 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A Singleton with Inheritance

I have been playing around with a couple of ways to add inheritance to a
JavaScript singleton pattern. As far as I'm aware, using an anonymous
constructor to create a singleton does not allow any kind of inheritance:

singletonObj = new function() {
this.prop = true;
}

Here are two ways to create a singleton with inheritance:

// class to inherit from
SuperClass = function() {
this.superProp = true;
}

// first way
with ({
SingletonClass: function() {
this.prop = true;
}
}) {
SingletonClass. prototype = new SuperClass();
singletonObj = new SingletonClass( );
}

// second way
singletonObj = (function() {
function SingletonClass( ) {
this.prop = true;
}
SingletonClass. prototype = new SuperClass();
return new SingletonClass( );
})();
These also allow you to add prototype based methods and properties to
the Singleton Class (I'm not sure what the benefits and drawbacks of
that are vs just creating the methods and properties within the
constructor - especially since it's a singleton and will only be
instantiated once).

There may be a bunch of better ways to achieve that, but I found it
useful, so I thought I'd share. :-)

Kevin N.

Dec 8 '05 #1
2 6313
Kevin Newman <Ca******@unFoc us.com> writes:
I have been playing around with a couple of ways to add inheritance to
a JavaScript singleton pattern.
Does the singleton (anti-)pattern make sense at all in a prototype based
language.

In a class based language, a singleton is a type for which there is
only ever one value, i.e., a non-inheritable class with only one
instance.

In a prototype based language, there are no classes and no
corresponding type. Any object can be used as a prototype,
so the singleton behavior cannot be enforced.
As far as I'm aware, using an anonymous constructor to create a
singleton does not allow any kind of inheritance:

singletonObj = new function() {
this.prop = true;
}
While this creates an object with a prototype different from
Object.prototyp e, there isn't really any advantage over just
doing
singletonObj = { prop:true };
Here are two ways to create a singleton with inheritance:

// class to inherit from
SuperClass = function() {
this.superProp = true;
}
So we restrict ourselves to constructors that can be seen as
representatives of the instances they create, i.e., as pseudo classes.
// second way .... both ways work the same, just using different scoping mechanisms ...
singletonObj = (function() {
function SingletonClass( ) {
this.prop = true;
}
SingletonClass. prototype = new SuperClass();
return new SingletonClass( );
})();


Here the singletonObj uses an instance of SuperClass as its prototype.

Notice that this is not similar to class based inheritance, where
you inherit from the class. It is prototype based inheritance,
where you inherit from a specific instance.

Again I fail to see the advantage over
singletonObj = new SuperClass();
All that happens is that one extra object is put into the
prototype chain.
It is impossible to enforce the singleton pattern, since you can
always create a object inheriting from the existing one:

function clone(o) {
function dummy(){};
dummpy.prototyp e = o;
return new dummy();
}

notSoSingletonO bj = clone(singleton Obj);
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Dec 9 '05 #2
Lasse Reichstein Nielsen wrote:
Kevin Newman <Ca******@unFoc us.com> writes:
I have been playing around with a couple of ways to add inheritance to
a JavaScript singleton pattern.
Does the singleton (anti-)pattern make sense at all in a prototype based
language.


Reading the rest of your response, I would question whether it does :-)
However, I would argue that creating an object with methods to be
invoked (something reasonably like a singleton), rather than creating an
function (something like a class) to be instantiated, might help someone
who uses my code to understand how I intended them to use it, though I
guess there is nothing like good documentation.

In a class based language, a singleton is a type for which there is
only ever one value, i.e., a non-inheritable class with only one
instance.
Hmm.. I guess some patterns just do not apply to JavaScript then. Maybe
this should be described as something other than a Singleton, but it may
still be useful. I am using it to discourage (since as you have pointed
out, I cannot completely stop) re-instantiation, or inheriting from,
since in my real life implementation the object will be setting up some
resource hungry processes (like an interval function that we wouldn't
want to create more than one of). I wonder if there is a better way to
achieve that though (again, maybe it's just good documentation).

In a prototype based language, there are no classes and no
corresponding type. Any object can be used as a prototype,
so the singleton behavior cannot be enforced.
As far as I'm aware, using an anonymous constructor to create a
singleton does not allow any kind of inheritance:

singletonObj = new function() {
this.prop = true;
}
While this creates an object with a prototype different from
Object.prototyp e, there isn't really any advantage over just
doing
singletonObj = { prop:true };


In my example there is no advantage. I should have included some
privileged variables, or set up a setInterval function, to demonstrate
why I have used this (non-)pattern I suppose. I'll have to do some
thinking on this..
Here are two ways to create a singleton with inheritance:

// class to inherit from
SuperClass = function() {
this.superProp = true;
}
So we restrict ourselves to constructors that can be seen as
representatives of the instances they create, i.e., as pseudo classes.
// second way

... both ways work the same, just using different scoping mechanisms ...
singletonObj = (function() {
function SingletonClass( ) {
this.prop = true;
}
SingletonClass. prototype = new SuperClass();
return new SingletonClass( );
})();


Here the singletonObj uses an instance of SuperClass as its prototype.

Notice that this is not similar to class based inheritance, where
you inherit from the class. It is prototype based inheritance,
where you inherit from a specific instance.

Again I fail to see the advantage over
singletonObj = new SuperClass();
All that happens is that one extra object is put into the
prototype chain.
It is impossible to enforce the singleton pattern, since you can
always create a object inheriting from the existing one:

function clone(o) {
function dummy(){};
dummpy.prototyp e = o;
return new dummy();
}

notSoSingletonO bj = clone(singleton Obj);


Well that's a good point. I hadn't considered that. :-) I guess with a
language as flexible as JavaScript, discipline is the only solution to
prevent re-instantiation.

At the more abstract level, I would argue that your method for cloning
the (non-)singleton is pretty advanced, and that creating an
instantiated object in the global space, instead of a function that a
user must instantiate only once, could be useful to help prevent novice
JavaScript users from re-using a "class" that they should really only
have one instance of.

I guess I could consider a different architecture for my app - maybe one
where the object that the user is instructed to use (by the
documentation), would utilize something like a singleton on it's own,
and make sure that the resource are not duplicated, even with
reinstantiation .
/L


Well anyway, thanks for the reply. I always learn something, and I
appreciate it.

Kevin N.

Dec 9 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2626
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
13
8281
by: Stampede | last post by:
I woundered if the following would be possible: I want to create an abstract Singleton class, which implements the singleton behaviour with the limitation, that the unique object will not be created within the getInstance() method. The classes which are derived from the Singleton class, have to implement a static constructor, where they...
2
1784
by: Eugene | last post by:
Hi, I got a singleton class. Then in another class (CA), i would declare a variable with this singleton class and get a reference to it. I would have another class (IA1) that would inherit from CA and I would want to allow IA1 to access the singleton class. My question is is it better to declare the singleton class as private or protected in...
13
3049
by: Robert W. | last post by:
At the beginning of my C# days (about 6 months ago) I learned about the Singleton pattern and implemented for Reference data, such as the kind that appears in an Options dialog box. My Singleton code looks like this: public sealed class Reference { private static readonly Reference instance = new Reference(); // Make the default...
4
1403
by: Srini | last post by:
Hi , Can anyone tell me when I can use singleton pattern. Will it be good for implementing the dataaccess Layer. Will it be usefull for the buisness object layer . Could you give me a practicle example for using the singleton object. Regards, Srini
3
1399
by: Jeremy Cowles | last post by:
Will the keyword "Me" ever be able to be the target of an assignment? Because singleton classes would be MUCH simplier if you could just point Me to a different address. For example: Class SingletonClassic Private Shared sm_Instance as SingletonClassic Public Shared Sub GetInstance() Return sm_Instance End Sub
9
14132
by: Marcel Hug | last post by:
Hallo NG ! I Have a little question about inheritance of a singleton class. In my application i have a Database-Connection Lib, in which I would ¨like to connect different databases of the same project (thats why it is in a lib). For the database A I created a singleton class AProxy and for the database B the same as BProxy. Initializing and...
2
2410
by: baba | last post by:
Hi all, I'm quite new to C#. I am trying to implement some basics reusable classes using this language and the .NET Framework technology. What I'm trying to do now is to implement a singleton class. I did have a look at the Microsoft "Patterns and Practices" article "Implementing Singleton in C#"...
5
2729
by: Markus Dehmann | last post by:
I need a Singleton for general program options so that all classes can access it. I use the code below (adapted from the Wikipedia singleton example). But the problem is if I change one variable in it, all my classes have to re-compile. But I am planning to add more options often during development. I tried to solve it through a forward...
0
7776
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7686
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8060
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5581
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5289
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3731
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1297
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1038
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.