[{"data":1,"prerenderedAt":763},["ShallowReactive",2],{"article-javascript-patterns-benefits":3},{"article":4,"tags":139,"previous":140,"next":200},{"id":5,"title":6,"author":7,"body":8,"createdAt":128,"description":129,"extension":130,"img":129,"meta":131,"navigation":132,"path":133,"seo":134,"stem":135,"tags":136,"updatedAt":128,"__hash__":138},"articles\u002Farticles\u002Fjavascript-patterns-benefits.md","JavaScript Patterns–Benefits","[object Object]",{"type":9,"value":10,"toc":124},"minimark",[11,18,28,33,62,67,86,91,102,107],[12,13,14],"p",{},[15,16,17],"strong",{},"Closures",[19,20,21,25],"ul",{},[22,23,24],"li",{},"By default, all variables and functions are added to the global scope, possibly causing naming conflicts",[22,26,27],{},"closures can be used to define scopes nested function have always accessed to all objects defined in the outer scope\nif a nested function references an object defined in the outer scope, a closure is created and the object will not be destroyed when the outer function is returned",[12,29,30],{},[15,31,32],{},"Prototype Pattern",[19,34,35,38,41,44,47,50,53,56,59],{},[22,36,37],{},"similar to a class, a prototype is a blueprint for objects",[22,39,40],{},"encapsulates code into modules and takes it out of the global namespace",[22,42,43],{},"variables are assigned in the constructor",[22,45,46],{},"functions are defined in the prototype block",[22,48,49],{},"this keyword is required to reference variables and functions within one prototype",[22,51,52],{},"all functions are only loaded once into memory, no matter how many objects are created using the constructor",[22,54,55],{},"Allow functions to be overridden",[22,57,58],{},"variables are specific to one instance",[22,60,61],{},"functions are shared among all instances",[12,63,64],{},[15,65,66],{},"Module Pattern",[19,68,69,71,74,77,80,83],{},[22,70,40],{},[22,72,73],{},"allows definition of private\u002Fpublic members",[22,75,76],{},"if multiple objects are created, all functions are loaded into memory multiple times",[22,78,79],{},"less extensible than the prototype pattern",[22,81,82],{},"members in the return statement are public, members outside the return statement are private",[22,84,85],{},"does not require the use of a constructor and is often initialized using a self calling function (= singleton)",[12,87,88],{},[15,89,90],{},"Revealing Module Pattern",[19,92,93,96,99],{},[22,94,95],{},"Very similar to the module pattern",[22,97,98],{},"Cleaner separation between private members and public interface",[22,100,101],{},"Instead of public functions, an object literal is returned which contains references to the private functions which should be exposed",[12,103,104],{},[15,105,106],{},"Revealing Prototype Pattern",[19,108,109,112,115,118,121],{},[22,110,111],{},"very similar to the prototype pattern",[22,113,114],{},"adds the separation of private and public members from the revealing module pattern",[22,116,117],{},"if a method calls another method within the prototype, the 'this' is no longer the object but the calling method",[22,119,120],{},"'this' can be passed as a parameter or",[22,122,123],{},"the method can be called with method name.call(this, anotherParam) which passes the context (the signature of \"methodname\" is just methodname(anotherParam)",{"title":125,"searchDepth":126,"depth":126,"links":127},"",2,[],"2015-04-20T08:07:12.5700000-04:00",null,"md",{},true,"\u002Farticles\u002Fjavascript-patterns-benefits",{"title":6,"description":129},"articles\u002Fjavascript-patterns-benefits",[137],"Javascript","Gq2t3bvJ5d2golE5WDJLg47e7WKz_s48o16aPtRqkNU",[],{"id":141,"title":142,"author":7,"body":143,"createdAt":192,"description":193,"extension":130,"img":129,"meta":194,"navigation":132,"path":195,"seo":196,"stem":197,"tags":198,"updatedAt":192,"__hash__":199},"articles\u002Farticles\u002Fusing-jsrender-with-javascript-and-html.md","Using JsRender with JavaScript and HTML",{"type":9,"value":144,"toc":190},[145,152,159,162,172,177],[12,146,147,148,151],{},"JsRender is a JavaScript library that allows you to define a boilerplate structure once and reuse it to generate HTML dynamically. JsRender brings a new templating library to HTML5 development that has a codeless tag syntax and high performance, has no dependency on jQuery nor on the Document Object Model (DOM), supports creating custom functions and uses pure string-based rendering.",[149,150],"br",{},"\nThe following sample will utilize a method within a MVC controller to output json string via jquery ajax call.",[153,154,158],"pre",{"className":155},[156,157],"brush:","csharp","        public JsonResult GetCustomers()  \n        {  \n            var customers = new List(){  \n                new Customer() { ID= \"1\", Name= \"Bobby Jones\", Birthday= \"1902-03-17\" },  \n                new Customer() { ID= \"2\", Name= \"Sam Snead\",   Birthday= \"1912-05-27\" },  \n                new Customer() { ID= \"3\", Name= \"Tiger Woods\", Birthday= \"1975-12-30\" }  \n            };             \n            return this.Json(customers, JsonRequestBehavior.AllowGet);  \n            }  \n        }  \n  \n    public class Customer{  \n        public string ID {get; set;}  \n        public string Name {get; set;}  \n        public string Birthday {get; set;}  \n    }  \n    ",[12,160,161],{},"You can render templates using JavaScript in several ways. First you’ll want to define your template either as a string or in a \u003Cscript> tag. The \u003Cscript> tag option is nice when you want to define your templates in the HTML, give them an id and reuse them. You can also create templates from strings, which gives you the ability to create them on the fly in code or even pull them from a data store..  The JavaScript on the page is as follows",[153,163,166,167,166],{"className":164},[156,165],"javascript","  \n",[168,169,171],"script",{"type":170},"text\u002Fjavascript","\u002F\u002F \u003C![CDATA[  \n         function getdata() {  \n        var s = $.getJSON(\"\u002FHome\u002FGetCustomers\", function (data) {  \n             $(\"#GolferDiv\").html($(\"#InnerGolferTemplate1\").render(data));  \n        });           \n        }  \n\u002F\u002F ]]>",[173,174,176],"div",{"id":175},"GolferDiv"," ",[153,178,181,166,186,166],{"className":179},[156,180],"html",[182,183],"input",{"type":184,"value":185},"button","get data",[168,187,189],{"id":188,"type":170},"InnerGolferTemplate1","\u002F\u002F \u003C![CDATA[  \n         {{:ID}}: \u003Cb>{{:Name}}\u003C\u002Fb> \u003Ci>{{:Birthday}}\u003C\u002Fi> \u003Cbr \u002F>  \n\u002F\u002F ]]>",{"title":125,"searchDepth":126,"depth":126,"links":191},[],"2015-04-20T08:07:12.7600000-04:00","JsRender is a JavaScript library that allows you to define a boilerplate structure once and reuse it to generate HTML dynamically.",{},"\u002Farticles\u002Fusing-jsrender-with-javascript-and-html",{"title":142,"description":193},"articles\u002Fusing-jsrender-with-javascript-and-html",[165],"X9dre_jVgpJBCollFTxNxhq1RoM7KALI3HKpYTjYECA",{"id":201,"title":202,"author":7,"body":203,"createdAt":754,"description":755,"extension":130,"img":744,"meta":756,"navigation":132,"path":757,"seo":758,"stem":759,"tags":760,"updatedAt":754,"__hash__":762},"articles\u002Farticles\u002Fpattern-singleton-c.md","Pattern Singleton c#",{"type":9,"value":204,"toc":752},[205,268,388,398,409,418,434,501,508,514,517,637,648,660,716,725,735,748],[12,206,207,208,210,211,213,214,210,216,218,219,222,223,226,227,230,231,233,234,236,237,210,239,241,242,244,245,248,249,251,252,256,257,259,260,263,264,267],{},"In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.",[149,209],{},"\n ",[149,212],{},"\nImplementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private.",[149,215],{},[149,217],{},"\nNote the ",[15,220,221],{},"distinction"," between a simple ",[15,224,225],{},"static instance"," of a class, and a ",[15,228,229],{},"singleton",": although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a ",[15,232,229],{},".",[149,235],{},"\nThe singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation. ",[149,238],{},[149,240],{},"\nThe following is an example implementation with the following benefits:",[149,243],{},"\na) Because the instance is created inside the ",[15,246,247],{},"Instance ","property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.",[149,250],{},"\nb) The instantiation is not performed until an object asks for an instance; this approach is referred to as ",[253,254,255],"em",{},"lazy instantiation",". Lazy instantiation avoids instantiating unnecessary singletons when the application starts.",[149,258],{},"\nThe disadvantage of the following implementation is that it is NOT thread safe for multithreading environments. \nIf separate threads of execution enter the ",[15,261,262],{},"Instance ","property method at the same time, more than one instance\nof the ",[15,265,266],{},"Singleton"," object may be created. Each thread could execute the following statement and decide that a new instance has to be created:",[153,269,272],{"className":270,"code":271,"language":157,"meta":125,"style":125},"language-csharp shiki shiki-themes github-light github-dark","using System;  \npublic class Singleton  \n{  \n   private static Singleton instance;\n  \n   private Singleton() {}\n  \n   public static Singleton Instance  \n   {  \n      get   \n      {  \n         if (instance == null)  \n         {  \n            instance = new Singleton();  \n         }  \n         return instance;  \n      }  \n   }  \n}&nbsp;\n",[273,274,275,283,288,294,300,305,311,316,322,328,334,340,346,352,358,364,370,376,382],"code",{"__ignoreMap":125},[276,277,280],"span",{"class":278,"line":279},"line",1,[276,281,282],{},"using System;  \n",[276,284,285],{"class":278,"line":126},[276,286,287],{},"public class Singleton  \n",[276,289,291],{"class":278,"line":290},3,[276,292,293],{},"{  \n",[276,295,297],{"class":278,"line":296},4,[276,298,299],{},"   private static Singleton instance;\n",[276,301,303],{"class":278,"line":302},5,[276,304,166],{},[276,306,308],{"class":278,"line":307},6,[276,309,310],{},"   private Singleton() {}\n",[276,312,314],{"class":278,"line":313},7,[276,315,166],{},[276,317,319],{"class":278,"line":318},8,[276,320,321],{},"   public static Singleton Instance  \n",[276,323,325],{"class":278,"line":324},9,[276,326,327],{},"   {  \n",[276,329,331],{"class":278,"line":330},10,[276,332,333],{},"      get   \n",[276,335,337],{"class":278,"line":336},11,[276,338,339],{},"      {  \n",[276,341,343],{"class":278,"line":342},12,[276,344,345],{},"         if (instance == null)  \n",[276,347,349],{"class":278,"line":348},13,[276,350,351],{},"         {  \n",[276,353,355],{"class":278,"line":354},14,[276,356,357],{},"            instance = new Singleton();  \n",[276,359,361],{"class":278,"line":360},15,[276,362,363],{},"         }  \n",[276,365,367],{"class":278,"line":366},16,[276,368,369],{},"         return instance;  \n",[276,371,373],{"class":278,"line":372},17,[276,374,375],{},"      }  \n",[276,377,379],{"class":278,"line":378},18,[276,380,381],{},"   }  \n",[276,383,385],{"class":278,"line":384},19,[276,386,387],{},"}&nbsp;\n",[12,389,390,391,394,395,397],{},"There is one approach name ‘double-check locking’ to help resolve the above thread-safe issue however the .NET Framework resolve this via the ",[15,392,393],{},"static initialization ","implementation.",[149,396],{},"\n\u003C\nbr>In this strategy, the instance is created the first time any member of the class is referenced. The common language runtime takes care of the variable initialization.",[12,399,400,401,404,405,408],{},"The class is marked ",[15,402,403],{},"sealed"," to prevent derivation, which could add instances. In addition, the variable is marked ",[15,406,407],{},"readonly",", which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.",[12,410,411,412,414,415,417],{},"This implementation is similar to the preceding example, except that it relies on the common language runtime to initialize the variable. It still addresses the two basic problems that the ",[253,413,266],{}," pattern is trying to solve: global access and instantiation control.\nThe public static property provides a global access point to the instance. Also, because the constructor is private, the ",[15,416,266],{}," class cannot be instantiated outside of the class itself; therefore, the variable refers to the only instance that can exist in the system.",[12,419,420,421,423,424,427,428,431,432,233],{},"Because the ",[15,422,266],{}," instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the ",[15,425,426],{},"Instance"," property. This solution therefore implements a form of the lazy instantiation property, as in the ",[253,429,430],{},"Design Patterns"," form of ",[253,433,266],{},[153,435,437],{"className":270,"code":436,"language":157,"meta":125,"style":125},"public sealed class Singleton  \n{  \n   private static readonly Singleton instance = new Singleton();  \n     \n   private Singleton(){}  \n  \n   public static Singleton Instance  \n   {  \n      get   \n      {  \n         return instance;   \n      }  \n   }  \n}\n",[273,438,439,444,448,453,458,463,467,471,475,479,483,488,492,496],{"__ignoreMap":125},[276,440,441],{"class":278,"line":279},[276,442,443],{},"public sealed class Singleton  \n",[276,445,446],{"class":278,"line":126},[276,447,293],{},[276,449,450],{"class":278,"line":290},[276,451,452],{},"   private static readonly Singleton instance = new Singleton();  \n",[276,454,455],{"class":278,"line":296},[276,456,457],{},"     \n",[276,459,460],{"class":278,"line":302},[276,461,462],{},"   private Singleton(){}  \n",[276,464,465],{"class":278,"line":307},[276,466,166],{},[276,468,469],{"class":278,"line":313},[276,470,321],{},[276,472,473],{"class":278,"line":318},[276,474,327],{},[276,476,477],{"class":278,"line":324},[276,478,333],{},[276,480,481],{"class":278,"line":330},[276,482,339],{},[276,484,485],{"class":278,"line":336},[276,486,487],{},"         return instance;   \n",[276,489,490],{"class":278,"line":342},[276,491,375],{},[276,493,494],{"class":278,"line":348},[276,495,381],{},[276,497,498],{"class":278,"line":354},[276,499,500],{},"}\n",[12,502,176,503,505,506],{},[149,504],{},"\nThe only potential downside of this approach is that you have less control over the mechanics of the instantiation. In the Design Patterns form, you were able to use a nondefault constructor or perform other tasks before the instantiation.  Because the .NET Framework performs the initialization in this solution, you do not have these options. In most cases, static initialization is the preferred approach for implementing a Singleton in .NET.\n",[15,507],{},[12,509,510,513],{},[15,511,512],{},"Finally Multithreaded Singleton\n","Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution.  ",[12,515,516],{},"The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created:",[153,518,520],{"className":270,"code":519,"language":157,"meta":125,"style":125},"using System;  \npublic sealed class Singleton  \n{  \n   private static volatile Singleton instance;  \n   private static object syncRoot = new Object();  \n  \n   private Singleton() {}  \n  \n   public static Singleton Instance  \n   {  \n      get   \n      {  \n         if (instance == null)   \n         {  \n            lock (syncRoot)   \n            {  \n               if (instance == null)   \n                  instance = new Singleton();  \n            }  \n         }  \n  \n         return instance;  \n      }  \n   }  \n}  \n",[273,521,522,526,530,534,539,544,548,553,557,561,565,569,573,578,582,587,592,597,602,607,612,617,622,627,632],{"__ignoreMap":125},[276,523,524],{"class":278,"line":279},[276,525,282],{},[276,527,528],{"class":278,"line":126},[276,529,443],{},[276,531,532],{"class":278,"line":290},[276,533,293],{},[276,535,536],{"class":278,"line":296},[276,537,538],{},"   private static volatile Singleton instance;  \n",[276,540,541],{"class":278,"line":302},[276,542,543],{},"   private static object syncRoot = new Object();  \n",[276,545,546],{"class":278,"line":307},[276,547,166],{},[276,549,550],{"class":278,"line":313},[276,551,552],{},"   private Singleton() {}  \n",[276,554,555],{"class":278,"line":318},[276,556,166],{},[276,558,559],{"class":278,"line":324},[276,560,321],{},[276,562,563],{"class":278,"line":330},[276,564,327],{},[276,566,567],{"class":278,"line":336},[276,568,333],{},[276,570,571],{"class":278,"line":342},[276,572,339],{},[276,574,575],{"class":278,"line":348},[276,576,577],{},"         if (instance == null)   \n",[276,579,580],{"class":278,"line":354},[276,581,351],{},[276,583,584],{"class":278,"line":360},[276,585,586],{},"            lock (syncRoot)   \n",[276,588,589],{"class":278,"line":366},[276,590,591],{},"            {  \n",[276,593,594],{"class":278,"line":372},[276,595,596],{},"               if (instance == null)   \n",[276,598,599],{"class":278,"line":378},[276,600,601],{},"                  instance = new Singleton();  \n",[276,603,604],{"class":278,"line":384},[276,605,606],{},"            }  \n",[276,608,610],{"class":278,"line":609},20,[276,611,363],{},[276,613,615],{"class":278,"line":614},21,[276,616,166],{},[276,618,620],{"class":278,"line":619},22,[276,621,369],{},[276,623,625],{"class":278,"line":624},23,[276,626,375],{},[276,628,630],{"class":278,"line":629},24,[276,631,381],{},[276,633,635],{"class":278,"line":634},25,[276,636,500],{},[12,638,639,640,643,644,647],{},"This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be ",[15,641,642],{},"volatile"," to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a ",[15,645,646],{},"syncRoot ","instance to lock on, rather than locking on the type itself, to avoid deadlocks.",[12,649,650,651,653,654,656,659],{},"This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the ",[15,652,247],{},"property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient. ",[149,655],{},[15,657,658],{},"Finally, ","there is a much cleaner approach than above if using .NET 4 or greater.",[153,661,663],{"className":270,"code":662,"language":157,"meta":125,"style":125},"public sealed class Singleton  \n{  \n    private static readonly Lazy lazy =  \n        new Lazy(() =&gt; new Singleton());  \n      \n    public static Singleton Instance { get { return lazy.Value; } }  \n  \n    private Singleton()  \n    {  \n    }  \n}\n",[273,664,665,669,673,678,683,688,693,697,702,707,712],{"__ignoreMap":125},[276,666,667],{"class":278,"line":279},[276,668,443],{},[276,670,671],{"class":278,"line":126},[276,672,293],{},[276,674,675],{"class":278,"line":290},[276,676,677],{},"    private static readonly Lazy lazy =  \n",[276,679,680],{"class":278,"line":296},[276,681,682],{},"        new Lazy(() =&gt; new Singleton());  \n",[276,684,685],{"class":278,"line":302},[276,686,687],{},"      \n",[276,689,690],{"class":278,"line":307},[276,691,692],{},"    public static Singleton Instance { get { return lazy.Value; } }  \n",[276,694,695],{"class":278,"line":313},[276,696,166],{},[276,698,699],{"class":278,"line":318},[276,700,701],{},"    private Singleton()  \n",[276,703,704],{"class":278,"line":324},[276,705,706],{},"    {  \n",[276,708,709],{"class":278,"line":330},[276,710,711],{},"    }  \n",[276,713,714],{"class":278,"line":336},[276,715,500],{},[12,717,718,719,724],{},"It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the ",[720,721,723],"a",{"href":722},"http:\u002F\u002Fmsdn.microsoft.com\u002Fen-us\u002Flibrary\u002Fdd642334.aspx","IsValueCreated"," property, if you need that.",[12,726,727,728,731],{},"Reference: ",[720,729],{"title":730,"href":730},"http:\u002F\u002Fcsharpindepth.com\u002FArticles\u002FGeneral\u002FSingleton.aspx",[720,732,730],{"href":730,"rel":733},[734],"nofollow",[12,736,737],{},[720,738,740],{"href":739},"\u002Fmedia\u002Farticulate-import\u002Fsingleton.png",[741,742],"img",{"style":743,"title":229,"src":744,"alt":229,"width":745,"height":746,"border":747},"display: none;","\u002Farticles\u002Fimages\u002Fsingleton_thumb.png",181,100,0,[749,750,751],"style",{},"html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}",{"title":125,"searchDepth":126,"depth":126,"links":753},[],"2015-04-20T08:07:12.4800000-04:00","Singleton pattern is a design",{},"\u002Farticles\u002Fpattern-singleton-c",{"title":202,"description":755},"articles\u002Fpattern-singleton-c",[761],"aspnet","MUee6xaTZWbY0EfT4p6OcSf6MrAr5AuTqJfu3KqqEVY",1781574771608]