如何根据javascript中的参数创建对象的单例实例?

时间:2016-10-27 05:21:20

标签: javascript singleton closures

我需要创建一个对象的单例实现,如果它的参数(例如,doc_id)保持不变则应该只返回相同的对象,否则如果doc_id更改则创建具有doc_id属性的新实例。

实施例 -

var object;
function mysingletonObj(obj){
    obj = obj || {};
    object.doc_id = obj.doc_id || 'default';
    object.timeoutDuration = obj.timeoutDuration || 3000;

    // i need to return a new object if obj.doc_id is new and there is
    // no other instace of Object with same doc_id otherwise return
    // that instance with same doc_id

    return{
       getInstance: if(!object){
         return object;
       }
     }
}

1 个答案:

答案 0 :(得分:0)

public class LocatorObject {

     private By by;
     private String locator;

     public LocatorObject(By by, String loc) { // usual stuff }
}

links.put("Home", new LocatorObject (By.xpath, "//*[@id='oneHeader']/div[3]/div/div[2]/nav/ul/li[1]/a/span"));