473,770 Members | 1,642 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 6347
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
2656
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
8317
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 load an instance into the static unique variable. Now I have to problems with that:
2
1804
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 CA? Or shall I let IA1 to get a reference to the singleton by itself? Thanks. Eugene
13
3061
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 constructor private, so that nothing can directly create it.
4
1421
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
1405
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
14148
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 connetcing to the Database is the same in both classes (except of the database-path, which is a...
2
2421
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#" (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp)
5
2745
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 declaration "class Opts;", but didn't succeed because Opts::instance() results in an error message...
0
9432
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10232
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9873
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8891
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6682
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3974
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2822
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.