{
    "componentChunkName": "component---src-templates-post-js",
    "path": "/blog/2013/05/01/when-is-a-singleton-not-a-singleton",
    "result": {"data":{"site":{"siteMetadata":{"title":"your friend Joel's digital garden","description":"Articles and notes from a collaborator at egghead.io. Musings on software, business, and life from a skilled virtual assistant.","author":{"name":"Joel Hooks"},"keywords":["Video Blogger"]}},"mdx":{"excerpt":"The Singleton is the Highlander of design patterns.  There can be only one . An example of a Singleton implementation might look something like this: from Tom Roggero The above JavaScript is from an  answer \nfrom StackOverflow that seemed…","fields":{"github":"https://github.com/joelhooks/joelhooks-com/tree/master/content/legacy_blog/2013-05-01-when-is-a-singleton-not-a-singleton.markdown"},"body":"var _excluded = [\"components\"];\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"layout\": \"post\",\n  \"title\": \"AngularJS, Dependency Injection, and when is a singleton not a Singleton?\",\n  \"date\": \"2013-05-01T00:00:00.000Z\"\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, _excluded);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"The Singleton is the Highlander of design patterns. \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"There can be only one\"), \".\"), mdx(\"p\", null, \"An example of a Singleton implementation might look something like this:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"(function(global) {\\n  'use strict';\\n  var MySingletonClass = function() {\\n    if (MySingletonClass.prototype._singletonInstance) {\\n      return MySingletonClass.prototype._singletonInstance;\\n    }\\n    MySingletonClass.prototype._singletonInstance = this;\\n\\n    this.Foo = function() {\\n      // ...\\n    };\\n  };\\n\\n  var a = new MySingletonClass();\\n  var b = new MySingletonClass();\\n  global.result = a === b;\\n})(window);\\n\")), mdx(\"p\", null, mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://stackoverflow.com/a/6733919/87002\"\n  }, \"from Tom Roggero\")), mdx(\"p\", null, \"The above JavaScript is from an \", mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://stackoverflow.com/questions/1635800/javascript-best-singleton-pattern\"\n  }, \"answer\"), \"\\nfrom StackOverflow that seemed resonable. I've never actually needed an enforced Singleton in JavaScript.\\nI suspect I never will, but... know thy enemy!\"), mdx(\"p\", null, \"Singletons have some use cases, but it is generally considered poor form to use\\nthem. They are especially bothersome when you start trying to unit test your\\ncode. They effectively create global state, and shared state is a real pain to\\nmanage when you are writing unit tests.\"), mdx(\"p\", null, \"It \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"is\"), \" extremely handy to only have one instance of a thing within a certain\\ncontext, so how do we gain the benefit of a Singleton, without the pain?\"), mdx(\"h2\", null, \"Dependency Injection (DI)\"), mdx(\"p\", null, mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://en.wikipedia.org/wiki/Dependency_injection\"\n  }, \"Dependency injection\"), \" is a lovely thing. It can be accomplished in several ways, from simply\\npassing arguments into a constructor, to full blown DI containers like\\n\", mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://code.google.com/p/google-guice/\"\n  }, \"Guice\"), \",\\n\", mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://github.com/tschneidereit/SwiftSuspenders\"\n  }, \"SwiftSuspenders\"), \", and\\n\", mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://angularjs.org/\"\n  }, \"AngularJS\"), \". I'm not going to go to deep in this post, but \", mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://joelhooks.com/2009/07/12/inversion-of-control-and-dependency-injection-in-flex-using-the-parsley-application-framework-part-1/\"\n  }, \"here is one from\\nthe archives\"), \" that is still relevant (if you don't mind a little AS3). \", mdx(\"a\", {\n    parentName: \"p\",\n    \"href\": \"https://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/\"\n  }, \"Here are a couple\"), \" of awesome talks from Mi\\u0161ko Hevery that I highly recommend.\"), mdx(\"p\", null, \"Most containers have a mechanism for\\nproviding \", mdx(\"em\", {\n    parentName: \"p\"\n  }, \"context-based singletons\"), \".\"), mdx(\"h2\", null, \"Context-Based singletons.\"), mdx(\"p\", null, \"With a DI container, we have contexts. In the case of AngularJS, we have\\nthe application module, which provides the overall container for a given\\napplication. Within this container we define dependencies that can be\\nliberally injected into other actors within the module, such as directives,\\ncontrollers, and/or utility classes. The module and its sub-modules \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"are\"), \" the context.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-javascript\"\n  }, \"angular\\n  .module('someModule', [])\\n  .service('mySingletonThing', MySingletonThing);\\n\")), mdx(\"p\", null, \"Here's a very typical line of config code in an AngularJS application. This configures\\na service for \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"someModule\"), \" called \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"mySingletonThing\"), \". \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"mySingletonThing\"), \" is a\\nsingleton, but it is not a Singleton. \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"MySingletonThing\"), \" does not enforce its\\nsingleton nature. We can create as many instances as we desire. We won't, but it\\nis nice to have freedom. ;)\"), mdx(\"p\", null, \"Instead we rely on AngularJS's ability to inject dependencies.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-javascript\"\n  }, \"angular.module(\\\"someModule\\\").\\n    controller(\\\"MyController\\\", [\\\"mySingletonThing\\\", function(mySingletonThing) {\\n        //do stuff\\n    };\\n\\nangular.module(\\\"someModule\\\").\\n    controller(\\\"MyOtherController\\\", [\\\"mySingletonThing\\\", function(mySingletonThing) {\\n        var hahaTakeThat = new MySingletonThing();\\n        console.log(hahaTakeThat === mySingletonThing); //false\\n    };\\n\")), mdx(\"p\", null, \"When we talk about a context-based singleton, these defined dependencies\\nare what we mean. Within a given context the \", mdx(\"em\", {\n    parentName: \"p\"\n  }, \"DI container\"), \" will only allow a single\\ninstance of the object to be injected. The object itself does not protect\\nagainst or prevent multiple instances. You can \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"new\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"new\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"new\"), \" it all day long,\\nand there will be no complaints. With objects managed by a DI container you\\nshould \", mdx(\"em\", {\n    parentName: \"p\"\n  }, \"never\"), \" need to use \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"new\"), \" for objects that are injectable.\"), mdx(\"p\", null, \"This provides you with all the benefits of a Singleton, with none of the\\nsadness. Now when you write your units tests, you can use as many individual instances as\\nyou might need, without managing global state. \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"Joy\"), \".\"), mdx(\"p\", null, \"With Angular's DI implementation, we are a bit limited. Within a given module, we only\\nhave access to a single context. This limits some flexibility that would\\nbe gained by allowing nested contexts. Consider for example a user with\\nmultiple accounts. What I'd really like is for each account to represent a\\ncontext that could have its \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"own\"), \" singleton objects. It would be \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"very\"), \"\\nhandy to dynamically add/remove account sub-modules from the user. The singleton\\ninjectables defined in the user module would cascade to sub-modules, but a\\nsub-module could also define its own singleton mappings, perhaps even overriding\\nthe parent module's. I don't know if this is on the roadmap, but it would be awesome to\\nhave a more robust injector.\"), mdx(\"h2\", null, \"Conclusion\"), mdx(\"p\", null, \"A Singleton is a singleton, but a singleton is not \", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"always\"), \" a Singleton in the\\n\", mdx(\"em\", {\n    parentName: \"p\"\n  }, \"formal\"), \" sense. The enforced Singleton is generally regarded as \\\"\", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"to be avoided\"), \"\\\", but context-based\\nsingletons are an extremely useful tool that play nice and\\ndon't represent hairy global state. YMMV\"));\n}\n;\nMDXContent.isMDXComponent = true;","frontmatter":{"title":"AngularJS, Dependency Injection, and when is a singleton not a Singleton?","date":"May 01, 2013","banner":null,"slug":null,"keywords":null}}},"pageContext":{"id":"90f36e1d-df8c-5c05-8e75-02c2aa5e9541","prev":{"id":"38331ba3-a55e-5bf9-aa92-aa1db8f4edcc","parent":{"name":"2013-05-21-size-and-composition-of-effective-teams","sourceInstanceName":"legacy"},"excerpt":"The success or failure of  any  project is based on the team or teams working on\nit. Teams are like fingerprints and snowflakes. They are composed of individuals\nwith unique experiences and skillsets. When we set out to build large\napplications in a…","fields":{"title":"Size and Composition of Effective Software Teams","slug":"blog/2013/05/21/size-and-composition-of-effective-teams","date":"2013-05-21T00:00:00.000Z"}},"next":{"id":"b0046216-c8ca-59d6-bb34-48c977c066f6","parent":{"name":"2013-04-26-a-rose-by-any-other-name","sourceInstanceName":"legacy"},"excerpt":"I posted  an\narticle  about using models to assist in creating leaner, meaner controllers. It resulted in a lively conversation in the comments that spawned an interesting  rebuttal  from  Rob Conery  that essentially says I am full of it, and the…","fields":{"title":"A rose by any other name?","slug":"blog/2013/04/26/a-rose-by-any-other-name","date":"2013-04-26T00:00:00.000Z"}}}},
    "staticQueryHashes": ["1045846374"]}