This Javascript program demonstrates how to create a JavaScript singleton class. The class CFactory is a singleton, which means that only one CFactory can be created. Singletons used to prevent multiple instances of a class. In this instance, having only one CFactory prevents the creation of multiple products with the same ID value.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> </head> <body> <script type="text/javascript" src="Singleton.js"></script> </body> </html>
// This is a singleton class class CFactory { // These are private properties that can not be accessed directly. static #sqInstance = null; #miLastId = 0; constructor() { // Use this to prevent more than one instance from being created if (CFactory.sqInstance) { return CFactory.sqInstance; } CFactory.sqInstance = this; } MakeProduct() { var qNewProduct = new CProduct(CFactory.sqInstance.miLastId); CFactory.sqInstance.miLastId += 1; return qNewProduct; } } class CProduct { // This is a private propery that can not be accessed directly. #miID; constructor(iID) { this.miID = iID; } PrintID() { document.write("Product ID = "+this.miID); } } // This function just prints out the members of an object. function PrintAnObject(qObject) { var iCount = 0; var sOutput = typeof(qObject)+": " + qObject.constructor.name + "<br />"; for (var sProperty in qObject) { sOutput += " " + sProperty + ': ' + qObject[sProperty]+"<br />"; ++iCount; if (iCount >= 15) { document.writeln(sOutput); document.writeln(" ...<br />"); return; } } document.writeln(sOutput); } // These are the same object. // The CFactory is a singleton. // So, each use of new returns the same CFactory. var qFactory1 = new CFactory(); var qFactory2 = new CFactory(); var qProduct1 = qFactory1.MakeProduct(); var qProduct2 = qFactory2.MakeProduct(); var qProduct3 = qFactory2.MakeProduct(); var qProduct4 = qFactory1.MakeProduct(); PrintAnObject(qFactory1); PrintAnObject(qFactory2); // This check verifies that the CFactory objects are the same document.write("The factories are " + ((qFactory1 != qFactory2) ? "not":"") + " equal.<br />"); // Each of the products have unique ids even though // they are created by the factory with different names. PrintAnObject(qProduct1); PrintAnObject(qProduct2); PrintAnObject(qProduct3); PrintAnObject(qProduct4);
© 20072025 XoaX.net LLC. All rights reserved.