Singleton

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ugo

    Singleton

    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.constructo r = null;

    this.getInstanc e = function( )
    {
    if( ! instance )
    {
    instance = new myClass( );
    instance.constr uctor = null;
    }

    return instance;
    }
    }
    })( );
  • Sam --

    #2
    Re: Singleton

    On Wed, 7 May 2008 10:42:51 +0200, Ugo <privacy@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.constructo r = null;
    >
    this.getInstanc e = function( )
    {
    if( ! instance )
    {
    instance = new myClass( );
    instance.constr uctor = null;
    }
    >
    return instance;
    }
    }
    >})( );
    Pure qui? :-))
    se ti vede ZERO...


    ciao

    Comment

    • RoLo

      #3
      Re: Singleton

      Do you know a better way of this one:
      Yes

      change this:
         return new function( )

      to this:
      return function( )

      ;-)

      Comment

      • RoLo

        #4
        Re: Singleton

        On May 7, 11:06 am, RoLo <roloswo...@gma il.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.

        Comment

        • Ugo

          #5
          Re: Singleton

          >>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

          Comment

          • Richard Cornford

            #6
            Re: Singleton

            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.constructo r = null;
            >
            this.getInstanc e = function( )
            {
            if( ! instance )
            {
            instance = new myClass( );
            instance.constr uctor = 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:nul l,
            getInstance:fun ction( ){
            return (
            instance||
            (
            instance = {
            constructor:nul l
            }
            )
            );
            }
            });
            })();

            - 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.

            Comment

            • Peter Michaux

              #7
              Re: Singleton

              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.constructo r = null;
              >
              this.getInstanc e = function( )
              {
              if( ! instance )
              {
              instance = new myClass( );
              instance.constr uctor = 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

              Comment

              • Ugo

                #8
                Re: Singleton

                >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|unde fined..
                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.constructo r = null;
                >>
                > this.getInstanc e = function( )
                > {
                > if( ! instance )
                > {
                > instance = new myClass( );
                > instance.constr uctor = 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:nul l,
                getInstance:fun ction( ){
                return (
                instance||
                (
                instance = {
                constructor:nul l
                }
                )
                );
                }
                });
                })();
                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

                Comment

                • Peter Michaux

                  #9
                  Re: Singleton

                  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() {},
                  someOtherProper ty: 55
                  };

                  Peter

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: Singleton

                    Ugo wrote:
                    IMHO, (new myClass()) can not be null|false|unde fined..
                    Yes, it can ;-)

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

                    window.alert(ne w 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>

                    Comment

                    • P. Prikryl

                      #11
                      Re: Singleton

                      On 23. Máj, 20:45 h., Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                      wrote:
                      Ugo wrote:
                      IMHO, (new myClass()) can not be null|false|unde fined..
                      >
                      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(ne w myClass());
                      Irrelevant code - what does it prove?

                      Comment

                      • Peter Michaux

                        #12
                        Re: Singleton

                        On May 23, 11:45 am, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                        wrote:
                        Ugo wrote:
                        IMHO, (new myClass()) can not be null|false|unde fined..
                        >
                        Yes, it can ;-)
                        >
                        function myClass()
                        {
                        this.toString = function() {
                        var a = [null, false, a];
                        return a[Math.floor(Math .random() * a.length)];
                        };
                        }
                        >
                        window.alert(ne w 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"

                        Comment

                        • Thomas 'PointedEars' Lahn

                          #13
                          Re: Singleton

                          P. Prikryl wrote:
                          Thomas 'PointedEars' Lahn wrote:
                          >Ugo wrote:
                          >>IMHO, (new myClass()) can not be null|false|unde fined..
                          >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(ne w 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

                          Comment

                          • Ugo

                            #14
                            Re: Singleton

                            >>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() {},
                            someOtherProper ty: 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
                            };
                            })();

                            Comment

                            • VK

                              #15
                              Re: Singleton

                              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() {},
                              someOtherProper ty: 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('C onctructor called as a function');
                              return MySingleton;
                              }
                              else if (
                              !!($isInstantia ted.flag) ||
                              (this instanceof MySingleton) ||
                              (MySingleton.is PrototypeOf(thi s))
                              ) {
                              window.alert('O nly one instance is allowed');
                              return mySingleton;
                              }
                              else {
                              // instantiate your singleton
                              // with methods and properties
                              // ...
                              this.toString = $toString;
                              $isInstantiated .flag = true;
                              }
                              function $isInstantiated () {
                              return arguments.calle e.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.

                              Comment

                              Working...