在JavaScript中实现单例的最简单/最干净的方法
在JavaScript中实现的最简单/最干净的方法是什么?我认为最简单的方法是声明一个简单的对象文字:在JavaScript中实现单例的最简单/最干净的方法,javascript,function,design-patterns,singleton,Javascript,Function,Design Patterns,Singleton,在JavaScript中实现的最简单/最干净的方法是什么?我认为最简单的方法是声明一个简单的对象文字: var myInstance = { method1: function () { // ... }, method2: function () { // ... } }; 如果您想在singleton实例上使用私有成员,可以执行以下操作: var myInstance = (function() { var privateVar = ''; fun
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
如果您想在singleton实例上使用私有成员,可以执行以下操作:
var myInstance = (function() {
var privateVar = '';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// All private members are accessible here
},
publicMethod2: function () {
}
};
})();
function Class()
{
var obj = {}; // Could also be used for inheritance if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod = publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
ClassSingleton = function()
{
var instance = null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no 'new' keyword;
return instance;
}
return { getInstance : getInstance };
}();
var myInstance = YourClass.singleton();
这被称为,它基本上允许您通过使用来封装对象上的私有成员
如果要防止修改singleton对象,可以使用ES5方法冻结它
这将使对象不可变,防止对其结构和值进行任何修改
如果您使用的是ES6,那么您可以非常轻松地使用ES模块来表示一个单例,甚至可以通过在模块范围内声明变量来保持私有状态:
然后,只需导入singleton对象即可使用它:
import myInstance from './my-singleton.js'
// ...
我认为最干净的方法是:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
之后,您可以根据需要调用该函数
var test = SingletonFactory.getInstance();
给猫剥皮的方法不止一种:)根据你的口味或具体需要,你可以采用任何建议的解决方案。只要有可能(当你不需要隐私时),我个人都会选择 既然问题是关于最简单和最干净的,那就是赢家。甚至:
var myInstance = {}; // Done!
这(引用我的博客)
没有多大意义(我的博客示例也没有),因为它不需要任何私有变量,所以它与:
var SingletonClass = {
myFunction: function () {
// Do stuff
},
instance: 1
}
我不赞成我的回答,明白吗 通常模块模式(请参阅)不是单例模式就足够了。但是,singleton的一个特性是它的初始化延迟到需要对象时。模块模式缺少此功能 我的建议(咖啡脚本): 在JavaScript中编译为:
window.singleton = function(initializer) {
var instance;
instance = void 0;
return function() {
if (instance !== void 0) {
return instance;
}
return instance = initializer();
};
};
然后我可以做以下几点:
window.iAmSingleton = singleton(function() {
/* This function should create and initialize singleton. */
alert("creating");
return {property1: 'value1', property2: 'value2'};
});
alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
window.iAmSingleton().property2 = 'new value';
alert(window.iAmSingleton().property2); // "new value" will pop up
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
我不确定我是否同意将模块模式用作单例模式的替代品。我经常看到在完全不必要的地方使用和滥用单例,我确信模块模式填补了程序员使用单例的许多空白。但是,模块模式不是单例模式 模块模式: 当声明
Foo
时,模块模式中初始化的所有内容都会发生。此外,模块模式可用于初始化构造函数,然后可以多次实例化构造函数。虽然模块模式是许多作业的正确工具,但它并不等同于单例
单件模式:
缩略形式
长格式,使用模块模式
在我提供的两个单例模式版本中,构造函数本身都可以用作访问器:
var a,
b;
a = new Foo(); // Constructor initialization happens here
b = new Foo();
console.log(a === b); //true
如果您不喜欢以这种方式使用构造函数,可以在If(instance)
语句中抛出一个错误,并坚持使用长格式:
var a,
b;
a = Foo.getInstance(); // Constructor initialization happens here
b = Foo.getInstance();
console.log(a === b); // true
我还应该提到,singleton模式与隐式构造函数模式非常匹配:
function Foo() {
if (Foo._instance) {
return Foo._instance;
}
// If the function wasn't called as a constructor,
// call it as a constructor and return the result
if (!(this instanceof Foo)) {
return new Foo();
}
Foo._instance = this;
}
var f = new Foo(); // Calls Foo as a constructor
-or-
var f = Foo(); // Also calls Foo as a constructor
我需要几个单身汉:
- 惰性初始化
- 初始参数
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
必须是数组才能工作,所以如果有空变量,只需传入args
[]
- 我在函数中使用了window对象,但我可以传入一个参数来创建自己的作用域
- name和construct参数是window[]工作的唯一字符串,但通过一些简单的类型检查,window.name和window.construct也是可能的
function Klass() {
var instance = this;
Klass = function () { return instance; }
}
这两个问题都给出了很好的答案,但我只是根据我从PHP/Zend框架进入heavy Node.js开发的情况添加了我自己的解释,在PHP/Zend框架中,单例模式很常见
以下注释记录的代码基于以下要求:
- 可以实例化函数对象的一个且仅一个实例
- 该实例不公开,只能通过公共方法访问
- 构造函数不是公共可用的,只有在没有可用实例的情况下才能实例化
- 构造函数的声明必须允许修改其原型链。这将允许构造函数从其他原型继承,并为实例提供“公共”方法
// Declare 'Singleton' as the returned value of a self-executing anonymous function
var Singleton = (function () {
"use strict";
// 'instance' and 'constructor' should not be available in a "public" scope
// here they are "private", thus available only within
// the scope of the self-executing anonymous function
var _instance=null;
var _constructor = function (name) {
this.name = name || 'default';
}
// Prototypes will be "public" methods available from the instance
_constructor.prototype.getName = function () {
return this.name;
}
// Using the module pattern, return a static object
// which essentially is a list of "public static" methods
return {
// Because getInstance is defined within the same scope
// it can access the "private" 'instance' and 'constructor' vars
getInstance:function (name) {
if (!_instance) {
console.log('creating'); // This should only happen once
_instance = new _constructor(name);
}
console.log('returning');
return _instance;
}
}
})(); // Self execute
// Ensure 'instance' and 'constructor' are unavailable
// outside the scope in which they were defined
// thus making them "private" and not "public"
console.log(typeof _instance); // undefined
console.log(typeof _constructor); // undefined
// Assign instance to two different variables
var a = Singleton.getInstance('first');
var b = Singleton.getInstance('second'); // passing a name here does nothing because the single instance was already instantiated
// Ensure 'a' and 'b' are truly equal
console.log(a === b); // true
console.log(a.getName()); // "first"
console.log(b.getName()); // Also returns "first" because it's the same instance as 'a'
请注意,从技术上讲,自执行匿名函数本身就是一个单例函数,Christian C.Salvadó提供的代码很好地证明了这一点。这里唯一的问题是,当构造函数本身是匿名的时,不可能修改构造函数的原型链
请记住,对于JavaScript,“public”和“private”的概念并不适用于PHP或Java。但我们通过利用JavaScript的功能范围可用性规则实现了同样的效果。模块模式:以“更具可读性的风格”。您可以很容易地看到哪些方法是公共的,哪些是私有的
var module = (function(_name){
/* Local Methods & Values */
var _local = {
name : _name,
flags : {
init : false
}
}
function init(){
_local.flags.init = true;
}
function imaprivatemethod(){
alert("Hi, I'm a private method");
}
/* Public Methods & variables */
var $r = {}; // This object will hold all public methods.
$r.methdo1 = function(){
console.log("method1 calls it");
}
$r.method2 = function(){
imaprivatemethod(); // Calling private method
}
$r.init = function(){
inti(); // Making 'init' public in case you want to init manually and not automatically
}
init(); // Automatically calling the init method
return $r; // Returning all public methods
})("module");
现在您可以使用公共方法,如
module.method2();//->我正在通过公共方法警报调用私有方法(“嗨,我是私有方法”)
您只需执行以下操作:
var singleton = new (function() {
var bar = 123
this.foo = function() {
// Whatever
}
})()
另一种方法——确保课程不会再次出现 这样,您可以使用
instanceof
op。此外,您还可以使用原型链来继承类。这是一门普通课,但你不能上新课。如果要获取实例,只需使用getInstance
:
function CA()
{
if(CA.instance)
{
throw new Error('can not new this class');
}
else
{
CA.instance = this;
}
}
/**
* @protected
* @static
* @type {CA}
*/
CA.instance = null;
/* @static */
CA.getInstance = function()
{
return CA.instance;
}
CA.prototype =
/** @lends CA# */
{
func: function(){console.log('the func');}
}
// Initialise the instance
new CA();
// Test here
var c = CA.getInstance()
c.func();
console.assert(c instanceof CA)
// This will fail
var b = new CA();
如果不想公开实例
成员,只需将其放入闭包即可
function Unicode()
{
var i = 0, unicode = {}, zero_padding = "0000", max = 9999;
// Loop through code points
while (i < max) {
// Convert decimal to hex value, find the character,
// and then pad zeroes to the code point
unicode[String.fromCharCode(parseInt(i, 16))] = ("u" + zero_padding + i).substr(-4);
i = i + 1;
}
// Replace this function with the resulting lookup table
Unicode = unicode;
}
// Usage
Unicode();
// Lookup
Unicode["%"]; // Returns 0025
function CA()
{
if(CA.instance)
{
throw new Error('can not new this class');
}
else
{
CA.instance = this;
}
}
/**
* @protected
* @static
* @type {CA}
*/
CA.instance = null;
/* @static */
CA.getInstance = function()
{
return CA.instance;
}
CA.prototype =
/** @lends CA# */
{
func: function(){console.log('the func');}
}
// Initialise the instance
new CA();
// Test here
var c = CA.getInstance()
c.func();
console.assert(c instanceof CA)
// This will fail
var b = new CA();
function Unicode()
{
var i = 0, unicode = {}, zero_padding = "0000", max = 9999;
// Loop through code points
while (i < max) {
// Convert decimal to hex value, find the character,
// and then pad zeroes to the code point
unicode[String.fromCharCode(parseInt(i, 16))] = ("u" + zero_padding + i).substr(-4);
i = i + 1;
}
// Replace this function with the resulting lookup table
Unicode = unicode;
}
// Usage
Unicode();
// Lookup
Unicode["%"]; // Returns 0025
/*************************************************
* SINGLETON PATTERN IMPLEMENTATION *
*************************************************/
// Since there aren't any classes in JavaScript, every object
// is technically a singleton if you don't inherit from it
// or copy from it.
var single = {};
// Singleton Implementations
//
// Declaring as a global object...you are being judged!
var Logger = function() {
// global_log is/will be defined in the GLOBAL scope here
if(typeof global_log === 'undefined'){
global_log = this;
}
return global_log;
};
// The below 'fix' solves the GLOABL variable problem, but
// the log_instance is publicly available and thus can be
// tampered with.
function Logger() {
if(typeof Logger.log_instance === 'undefined') {
Logger.log_instance = this;
}
return Logger.log_instance;
};
// The correct way to do it to give it a closure!
function logFactory() {
var log_instance; // Private instance
var _initLog = function() { // Private init method
log_instance = 'initialized';
console.log("logger initialized!")
}
return {
getLog : function(){ // The 'privileged' method
if(typeof log_instance === 'undefined') {
_initLog();
}
return log_instance;
}
};
}
/***** TEST CODE ************************************************
// Using the Logger singleton
var logger = logFactory(); // Did I just give LogFactory a closure?
// Create an instance of the logger
var a = logger.getLog();
// Do some work
// Get another instance of the logger
var b = logger.getLog();
// Check if the two logger instances are same
console.log(a === b); // true
*******************************************************************/
var singleton = function(initializer) {
var state = 'initial';
var instance;
var queue = [];
var instanceReady = function(createdInstance) {
state = 'ready';
instance = createdInstance;
while (callback = queue.shift()) {
callback(instance);
}
};
return function(callback) {
if (state === 'initial') {
state = 'waiting';
queue.push(callback);
initializer(instanceReady);
} else if (state === 'waiting') {
queue.push(callback);
} else {
callback(instance);
}
};
};
var singletonInitializer = function(instanceReady) {
var preparedObject = {property: 'value'};
// Calling instanceReady notifies the singleton that the instance is ready to use
instanceReady(preparedObject);
}
var s = singleton(singletonInitializer);
// Get the instance and use it
s(function(instance) {
instance.doSomething();
});
var simpleInitializer = function(instanceReady) {
console.log("Initializer started");
instanceReady({property: "initial value"});
}
var simple = singleton(simpleInitializer);
console.log("Tests started. Singleton instance should not be initalized yet.");
simple(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
simple(function(inst) {
console.log("Access 2");
console.log("Current property value: " + inst.property);
});
var heavyInitializer = function(instanceReady) {
console.log("Initializer started");
var onTimeout = function() {
console.log("Initializer did his heavy work");
instanceReady({property: "initial value"});
};
setTimeout(onTimeout, 500);
};
var heavy = singleton(heavyInitializer);
console.log("In this example we will be trying");
console.log("to access singleton twice before it finishes initialization.");
heavy(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
heavy(function(inst) {
console.log("Access 2. You can see callbacks order is preserved.");
console.log("Current property value: " + inst.property);
});
console.log("We made it to the end of the file. Instance is not ready yet.");
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
function Class()
{
var obj = {}; // Could also be used for inheritance if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod = publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
var objInst = Class(); // !!! NO NEW KEYWORD
ClassSingleton = function()
{
var instance = null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no 'new' keyword;
return instance;
}
return { getInstance : getInstance };
}();
var obj = ClassSingleton.getInstance();
function Singleton() {
var i = 0;
var self = this;
this.doStuff = function () {
i = i + 1;
console.log('do stuff', i);
};
Singleton = function () { return self };
return this;
}
s = Singleton();
s.doStuff();
var A = function(arg1){
this.arg1 = arg1
};
var X = function(){
var instance = {};
return function(){ return instance; }
}();
var x1 = new X();
var x2 = new X();
console.log(x1 === x2)
class YourClass {
@Singleton static singleton() {}
}
function Singleton(target, name, descriptor) {
var instance;
descriptor.value = () => {
if(!instance) instance = new target;
return instance;
};
}
var myInstance = YourClass.singleton();
export default class Singleton {
static instance;
constructor(){
if(instance){
return instance;
}
this.state = "duke";
this.instance = this;
}
}
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
class Foo {
constructor(msg) {
if (Foo.singleton) {
return Foo.singleton;
}
this.msg = msg;
Foo.singleton = this;
return Foo.singleton;
}
}
const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }
console.log(Singleton.getInstance().field1);
console.log(Singleton.getInstance().field2);
DefaultField1
DefaultField2
function Once() {
return this.constructor.instance || (this.constructor.instance = this);
}
function Application(name) {
let app = Once.call(this);
app.name = name;
return app;
}
class Once {
constructor() {
return this.constructor.instance || (this.constructor.instance = this);
}
}
class Application extends Once {
constructor(name) {
super();
this.name = name;
}
}
console.log(new Once() === new Once());
let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');
console.log(app1 === app2);
console.log(app1.name); // Barfoo
const singleton = new class {
name = "foo"
constructor() {
console.log(`Singleton ${this.name} constructed`)
}
}
class Singleton {
constructor(name, age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
}
let x = new Singleton('s', 1);
let y = new Singleton('k', 2);
console.log(x.name, x.age, y.name, y.age) // s 1 s 1
function AnotherSingleton (name,age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
let a = new AnotherSingleton('s', 1);
let b = new AnotherSingleton('k', 2);
console.log(a.name, a.age, b.name, b.age) // s 1 s 1