/** * file: Singletonts.ts * Singleton Pattern 单例是一种创建型设计模式, 让你能够保证一个类只有一个实例, 并提供一个访问该实例的全局节点。 * The Singleton class defines the `getInstance` method that lets clients access * the unique singleton instance. */ class Singleton { private static instance: Singleton; /** * The Singleton's constructor should always be private to prevent direct * construction calls with the `new` operator. */ private constructor() { } /** * The static method that controls the access to the singleton instance. * * This implementation let you subclass the Singleton class while keeping * just one instance of each subclass around. */ public static getInstance(): Singleton { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return Singleton.instance; } /** * Finally, any singleton should define some business logic, which can be * executed on its instance. */ public someBusinessLogic() { // ... } } /** * The client code. */ function clientCodeDu() { const s1 = Singleton.getInstance(); const s2 = Singleton.getInstance(); let stdu=""; if (s1 == s2) { console.log('Singleton works, both variables contain the same instance.'); stdu="Singleton works"; } else { console.log('Singleton failed, variables contain different instances.'); stdu="Singleton failed"; } return stdu; } let ssig="gevindu"; let strsig=clientCodeDu(); let strsig1="geovindu"; let messagesig: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du Web'; document.body.innerHTML = messagesig+","+strsig+","+strsig1+",TypeScript 单例模式"
調用:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <head><title>TypeScript:单例模式</title> <meta name="Description" content="geovindu,涂聚文,Geovin Du"/> <meta name="Keywords" content="geovindu,涂聚文,Geovin Du"/> <meta name="author" content="geovindu,涂聚文,Geovin Du"/> </head> <body> <script src="dist/Singletonts.js"></script> </body> </html>
輸出:
npm install --save-dev ts-loader
npm install --save-dev webpack webpack-cli
npm install webpack
https://www.typescriptlang.org/docs/handbook/2/modules.html
https://www.typescriptlang.org/tsconfig#module
标签:Singleton,typescript,getInstance,Pattern,instance,let,单例,stdu From: https://www.cnblogs.com/geovindu/p/17744590.html