Singleton pattern class and static class

Hi,
what is difference between the singleton pattern class and static class ?
in singleton pattern, we declare a static member[which hold one value at a time] ,static method[ which return static member value] and a private constructor[not allow to direct instantiation]. My words are -- as a singleton pattern we implement static class .
so can we say a singleton pattern is static class it means both are same or is any difference between these two ??

malcolmmc wrote:
On several occasions I've had to convert a static (never instanceated) class to a singleton type, for example because I realise I need an instance per thread, or I decide to make a program more modular, with more than one configuration.
I've never done the opposite.
So generally I favour the singleton if there any "state" involved, because it's more flexible in unanticipated directions. It also gives extra flexibility when building tests, especially if you program to an interface.Total agreement; if anything it is dead hard to override static method logic with mock code in unit tests (I had to do it by keeping the static methods in place but making them internally use a singleton instance of itself of which the instance variable could be overwritten with a mock implementation for unit testing purposes...).
'Static classes' and/or methods are great for very simple util functions, but I wouldn't use them for anything other than that.

Similar Messages

  • Singleton pattern over Factory pattern

    What is the difference between the Factory and Singleton pattern.
    Can we use a singleton (pattern) class to create other object instances and return them.
    What are the advantages and disadvantages for using the Singleton pattern here.
    Or do we have to use only a factory (pattern) class to do the above type of task.

    The Factory pattern and the Singleton pattern are used to achieve different things. That's not to say they can't be used together. A Singleton pattern is used to force the use of a single instance of a class, hence the name. The Factory pattern is used to determine at runtime what class will be used.

  • Singletons and Static class behavior

    Hi all and thanks for taking a look at this,
    I was playing around with a Singleton class today and it raised raised a few questions around Static methods in the singleton. When my class is instatiated I load some data into a HashMap map that I want to make available for read only purposes through other methods in my singleton.
    I really wanted to just call a static method to look up the value, so I followed the standard model. I had a private static HashMap that is loaded with data when the Contructor is called from the getInstance(). I included the standard model example for you if you wanted to refer to it.
    I ran my code making a static MyClass.getData() call to see what would happen. The static call did not return a value, I wasn't surprised. Then I added a call to MyClass.getInstance() followed by the static MyClass.getData() call and this returned the appropriate value.
    Then I changed my Singleton as follows and was wondering if there were any issues that might result because of this and I was wondering what the process that is followed by java when calling a static method (what does it use, where does it look).
    My Code:
    public class MyClass {
    private static MyClass instance;
    private static HashMap myData;
    private MyClass() {
    myData = new HashMap();
    myData.put("1", "value 1");
    myData.put("2", "value 2");
    private static synchronized void getInstance() {
    if (instance == null)
    instance = new MyClass();
    public static String getData(String key) {
    if (myData == null)
    getInstance();
    return (String)myData.get(key);
    The standard singleton model class:
    public class MyClass {
    private static MyClass instance;
    private MyClass() { }
    public static synchronized MyClass getInstance() {
    if (instance == null)
    instance = new MyClass();
    return instance;
    ... rest of methods (not static)
    }

    Thanks for the reply,
    Really my only reason for making it static was so the calling class would not have to get a handle to the actual MyClass Instance. Therefore avoiding the Synchronization method.
    I was attempting to aviod the famous broken double check locking by having the checks in different methods. I am assuming from you warning that keeping the methods seperate and synchronizing the getInstance is really no different than putting a synchronize(this) block around the second check and the constructor call?
    Really my objective is to retrive data once, not really create a single access point for getting the data. As an alternative, I tried the following code and it seems to work, any issues you can see with this?
    public class MyClass {
    private static HashMap hm;
    static {
    hm = new HashMap();
    // code to get Data into HashMap
    public static String getData(String key) {
    return hm.get(key);

  • Serializing a class that implements the Singleton pattern

    Hello,
    I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
    I have a class that implements the singleton pattern. It's definition is as follows:
    public class JCOption implements Serializable {
      private int x = 1;
      private static JCOption option = new JCOption();
      private JCOption() {}
      public static JCOption getOption() { return option; }
      public int getX() { return x; }
      public void setX(int x) { this.x = x; }
      public static void main(String args[]) throws IOException {
        JCOption opt = JCOption.getOption();
        opt.setX(10);
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
        encoder.setPersistenceDelegate(opt.getClass(),  new JCOptionPersistenceDelegate());
        encoder.writeObject(opt);
        encoder.close();
    }Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
      protected Expression instantiate(Object oldInstance, Encoder out) {
           Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
            return expression;
      }The problem is that the resulting XML file only contains the following lines:
        <java version="1.5.0_06" class="java.beans.XMLDecoder">
            <object class="JCOption" property="option"/>
        </java> so there is no trace of the property x.
    Thank you in advance for your answers.

    How about this:
    import java.beans.DefaultPersistenceDelegate;
    import java.beans.Encoder;
    import java.beans.Expression;
    import java.beans.Statement;
    import java.beans.XMLEncoder;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    public class JCOption {
        private int x = 1;
        private static JCOption option = new JCOption();
        private JCOption() {}
        public static JCOption getOption() { return option; }
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }
        public static void main(String args[]) throws IOException {
          JCOption opt = JCOption.getOption();
          opt.setX(10);
          ByteArrayOutputStream os = new ByteArrayOutputStream();
          XMLEncoder encoder = new XMLEncoder( os );
          encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
          encoder.writeObject(opt);
          encoder.close();
          System.out.println( os.toString() );
    class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            return new Expression(
                    oldInstance,
                    oldInstance.getClass(),
                    "getOption",
                    new Object[]{} );
        protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
            super.initialize( type, oldInstance, newInstance, out );
            JCOption q = (JCOption)oldInstance;
            out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
    }   Output:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
    <object class="JCOption" property="option">
      <void property="x">
       <int>10</int>
      </void>
    </object>
    </java>

  • Best Practice:  Using a static variables and methods vs singleton pattern

    Just curious, since when anything, within a class, is denoted as static it typically will be stored in main memory as a class property(method, variables, etc). Is it a good practice to be doing this all the time or is the singleton pattern a better choice. Please explain why. Thanks.

    I wouldnot make anything other than the constants and the instance itself static. And I cant think of a reason wjy one would.

  • Serializing object of class implementing Singleton Pattern

    hi ,
    if i've a object of a singleton pattern based class and i seriailize that and when i'm desrializing that, i 'll get the object back, but on calling getInstance() method for my singleton class, it will agian call constructor because for the class's static object reference is null, i need to avoid this, for this i've written a setInstance method, which sets the Singleton class's static refernce to the object i desialized, which is fine, but it defeats the singleton pattern
    can anybody suggest me some other way of achieving this...

    If you are trying to deserialize a Singleton implement the Object readResolve() method.
    http://java.sun.com/javase/6/docs/platform/serialization/spec/input.html#5903
    ~Ryan

  • Abstract classes and static methods

    I have an abstract report class AbstractReportClass which I am extending in multiple report classes (one for each report, say ReportA, ReportB, ...). Each report class has its own static column definitions, title, etc., which I have to access through a static method getDataMeta() in a web application. Each report has the same exact code in getDataMeta, and no report may exist without these fields. My intuition tells me that AbstractReportClass should contain the code for getDataMeta, but I know that you can't mix abstract and static keywords.
    Am I missing a simple solution to unify the getDataMeta code in the abstract base class? or do I really need to have a static function getDataMeta with the same code in each of the base classes?
    My apologies if this has been discussed many times before.
    Thanks,
    -Andrew

    I'm not trying to be "right"; rather I just asked a question about whether I can do something that seems intuitive. Perhaps you might write code in a different way than I would or perhaps I wasn't clear about every little detail about my code? Do you regularly belittle people who ask questions here?
    I have a loadFromDB() member function in AbstractReport for which all sub classes have an overloaded version. All reports I'm displaying have 4 common fields (a database id and a name and a monetary value, for example), but then each other report has additional fields it loads from the database. Inside ReportX classes' loadFromDB(), I call the superclass loadFromDB() function and augment values to get a completely loaded object. In fact, the loadedData member object resides in AbstractReport.
    I can't use a report unless it has these common features. Every report is an AbstractReport. There is common functionality built on top of common objects. Isn't this the point of inheritance? I'm essentially saying that abstract class Shape has a getArea function and then I'm defining multiple types of Shapes (e.g. Rectangle and Circle) to work with...

  • Regex problem using Pattern class

    Hi everybody,
    I am using the Pattern class to create a pattern which has to match "Sanofi-Aventis" (without the quotes). The pattern is created like this:
    Pattern p = Pattern.compile("(?i)(" + Pattern.quote(match) + ")");It is then matched as follows:
    Matcher m = p.matcher(retval);
    String retval = m.replaceAll("<font color=\"#CCCCCC\"><strong>$1</strong></font>");I have printend the value of "match" and of "Pattern.quote(match)", and they look like this:
    >
    match: Sanofi-Aventis
    Pattern.quote(): \QSanofi-Aventis\E
    However, "Sanofi-Aventis" does not get matches in the text. Words / Strings without a "-" work fine, so I guess I am doing something wrong with respect to the dash. Can anybody help me out?
    Best regards,
    Jethro

    Hi there,
    I now sort the p_matches ArrayList on String length to make sure I find the longest possible match. Besides that I am now using the CASE_INSENSITIVE flag instead of "(?i)". This is my final code:
    public static String colorOccurences(String p_text, ArrayList<String> p_matches, String p_HTMLColorCode)
         String retval = p_text;
            // Sort the matches ArrayList on String length, starting with the longest String.
            Collections.sort(p_matches, new StringLengthComparator());
            // Color the matches.
            for (String match : p_matches)
                Pattern p = Pattern.compile("(" + Pattern.quote(match) + ")", Pattern.CASE_INSENSITIVE);
                Matcher m = p.matcher(retval);
                retval = m.replaceAll("<font color=\"" + p_HTMLColorCode + "\"><strong>$1</strong></font>");
         return retval;
    * Comparator object for Strings. Orders by length of String from large to small,
    * then alphabetically.
    private static class StringLengthComparator implements Comparator
         public int compare(Object x,Object y)
              if(x instanceof String && y instanceof String)
                   String xstr = (String) x, ystr = (String) y;
                   if(xstr.length() == ystr.length()) return xstr.compareTo(ystr);
                   else if(xstr.length() < ystr.length()) return 1;
                   else return -1;
              else return 0;
    }Best regards,
    Jethro

  • Why the singleton pattern used rather than static things?

    class Single
        private Single() {}
        private void print() { System.out.println("Foo~"); }
        private static Single one = new Single();
        public static void print() { one.print(); }
    class Stat
        public static void print() { System.out.println("Foo~"); }
    }What's the different?? What is the benefit of the singleton one?

    There is no practical difference - because, in fact, that is not the singleton pattern!
    A singleton would look like:
    class Singleton {
        private Singleton() {}
        public void print() { System.out.println("Foo~"); }
        private static Singleton instance = new Singleton();
        public static Singleton getInstance() { return instance; }
    }The benefit of this pattern is, that your client code doesn't have to know that there is only one instance (getInstance could return another instance for every call) or of which actual type it is (getInstance could return an instance of any Subclass of Singleton).
    See http://c2.com/cgi/wiki?SingletonPattern for more information on the pattern.

  • Unable to parse control character using regular expression & Pattern class

    I am trying to parse the Ctrl-X character from a string using the Pattern class but for some or the other reason it is not finding it.
    Here is the code that I wrote,
    Pattern p=Pattern.compile("\\cX");
    Matcher m=p.matcher(str);
    System.out.println(str+": "+m.find());
    the result is prop^Xau,bu,ca,en,fe,fi,ge,hj,ma,pe,re,sh,sr,tr^Yto^Xym^Yfmt^Xh : false
    where, str= prop^Xau,bu,ca,en,fe,fi,ge,hj,ma,pe,re,sh,sr,tr^Yto^Xym^Yfmt^Xh
    Thanks,
    Arunraj

    arunraj.nair wrote:
    I am trying to parse the Ctrl-X character from a string using the Pattern class but for some or the other reason it is not finding it.
    Here is the code that I wrote,
    Pattern p=Pattern.compile("\\cX");
    Matcher m=p.matcher(str);
    System.out.println(str+": "+m.find());
    the result is prop^Xau,bu,ca,en,fe,fi,ge,hj,ma,pe,re,sh,sr,tr^Yto^Xym^Yfmt^Xh : false
    where, str= prop^Xau,bu,ca,en,fe,fi,ge,hj,ma,pe,re,sh,sr,tr^Yto^Xym^Yfmt^XhWhat does str.length() give you? And posting, and trying with, a (much) shorter String might help you and others here to more easily see the problem.
    db

  • White space in regular expressions (Pattern class)

    Hello,
    I have to check if a String contains ONLY the following characters: a-z, A-Z, ' and ( ) .
    The regular expression that I wanted to use with the Pattern class was [[a-zA-Z][\u0027][\u0028][\u0029][\s]] .
    Now, my compiler (Eclipse) doesnt recognize \s as an expression. Is this the proper expression for a white space?
    Also, in this notation, will the Pattern check for the order of the characters, cause the order isn't supposed to matter.
    I would appreciate any help you could give me on this subject.
    With Best Regards, Roderick

    I'm not a regex expert, but I don't see any of the regex gurus online, and this I can tell you.
    my compiler (Eclipse) doesnt recognize \s as an expressionYou need to escape the backspace in a String literal. Use"\\s"
    in this notation, will the Pattern check for the order of the charactersFor that I think (note:think, not know) you need to put the entire set of characters to be matched in one character class. Could you try this and post back whether it works for your requirement?"[^a-zA-Z'()\\s]"Note the negation operator at the start of the characer class, which will match positive for any character not in the character class.
    db
    edit You can test your regex here:
    {color:0000ff}http://www.dotnetcoders.com/web/Learning/Regex/RegexTester.aspx{color}
    but remember to double the backslashes whe you include it in your java code as a String literal.
    Edited by: Darryl.Burke

  • JDK1.4 Pattern Class

    Has anyone taken a peak at the new java.util.regex classes. I can't seem to get the ^, indicating beginning of line, and the $, indicating the end of line, to work. Everything else seems to work as it does in perl.
    String str = "#hello";
    if(Pattern.matches("^#", str))
    System.out.println("match found");
    this does not work and I have tried many variants
    ^[#]....^(#)....(^#)
    I have tried things that I know should not work. neither ^ or $ seems to do what the Pattern class says or what "Unicode Regular Expression Guidelines" says. Basically both say that ^ and $ show match the beginning/end of a given string, like perl.
    $str = "#hello";
    if($str =~ /^#/){
    print "match found";
    works in perl???? and works this way in javascript

    I FIGURED IT OUT, FALSE ALARM
    it's weird but for some reason you must match the rest of the string, unlike other languages I have used regexs in. so "^#" is not enough, this works though "^[#].*"
    1. read in a conf file allowing # or ; as comment
    2. looking for key=value pairs
    3. my readLine() call removes \n's so I append one to the string. This allows me to toggle blank lines in conf file becuase without \n, my regex would fail trying to make a "" string.
    if(Pattern.matches("^[#;\n].*", string+"\n")){
    // this works
    }

  • Java Pattern Matcher (Pattern.class bug? Stuck in Infinite Loop)

    Hi,
    I'm using the java pattern matcher and it appears to be stuck in an infinite loop and will not return from Pattern.class.
    It stays stuck in the following two code sequences...
    I'm using the following regex...
    java.util.regex.Matcher[pattern=[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|biz|info) region=0,353648 lastmatch=
    MAIN BLOCK STUCK IN LOOP:
    boolean study(TreeInfo info) {
    if (type != INDEPENDENT) {
    int minL = info.minLength;
    atom.study(info);
    info.minLength = minL;
    info.deterministic = false;
    return next.study(info);
    } else {
    atom.study(info);
    return next.study(info);
    SECOND BLOCK STUCK IN LOOP:
    boolean match(Matcher matcher, int i, CharSequence seq) {
    // Check for zero length group
    if (i > matcher.locals[beginIndex]) {
    int count = matcher.locals[countIndex];
    if (count < cmin) {
    matcher.locals[countIndex] = count + 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    if (next.match(matcher, i, seq))
    return true;
    if (count < cmax) {
    matcher.locals[countIndex] = count + 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    return false;
    return next.match(matcher, i, seq);
    Is this a bug with the Java 1.6 Pattern Matcher?
    Thanks
    V$h3r

    The Java Pattern Matcher is getting stuck in the following code...
    boolean study(TreeInfo info) {
    if (type != INDEPENDENT) {
    int minL = info.minLength;
    atom.study(info);
    info.minLength = minL;
    info.deterministic = false;
    return next.study(info);
    } else {
    atom.study(info);
    return next.study(info);
    boolean match(Matcher matcher, int i, CharSequence seq) {
    // Check for zero length group
    if (i > matcher.locals[beginIndex]) {
    int count = matcher.locals[countIndex];
    if (count < cmin) {
    matcher.locals[countIndex] = count 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    if (next.match(matcher, i, seq))
    return true;
    if (count < cmax) {
    matcher.locals[countIndex] = count + 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    return false;
    return next.match(matcher, i, seq);
    }Here is a copy of the REGEX that I'm using...
    It works on most of the other STRINGS but when I do a REGEX on the the html source for http://www.exponent.com it will get stuck...
    Pattern p = Pattern.compile("[a-zA-Z0-9+_~-]+(?:\\.[a-zA-Z0-9+_~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+(?:com|org|net|biz|info|[a-zA-Z]{2})");Thanks,
    V$h3r

  • Singleton pattern, scheduled receive location and suspended orchestrations

    Hello,
    In our project we have several orchestrations that are triggered every minute with the Scheduler Adapter (business requirement is near real-time).
    Each of these orchestration must have only 1 instance running at the same time, so we have implemented the singleton pattern. We followed a design like this one: https://fehlberg.wordpress.com/2008/06/06/biztalk-singleton-orchestration-design/
    But we end up having suspended orchestrations with the error "The instance completed without consuming all of its messages. The instance and its unconsumed messages have been suspended."
    I know it's a risk with this pattern. I thought it would happen only when the instance would run in more than 1 min (because the scheduler adapter is sending a file every minute).
    But it happens even with some instances running in about 15sec, so there is something I don't understand, here is an example:
    Here we can see that the TransferRegion orchestration started at 10:26:00 (which is expected) and failed.
    When I open the orchestration debugger, the time is different, the orchestration is shown starting at 10:26:44 (44 sec later):
    And the orchestration ended at 10:27:00:453.
    The message not consumed that caused the error has been triggered at 10:27:00.
    So I understand that the message arrived just after the listen shape but before the orchestration ends, but I don't understand why the orchestration started 44 sec after is was supposed to ...
    Any idea? I'm kind of clueless for now ...

    So, are these 8 Orchestrations actually processing messages or are they doing some other work every minute or so?
    If they're not processing actual messages, maybe a Windows Service or job scheduled by the SQL Agent or Windows Scheduler would be more...appropriate.  We all love BizTalk, but some parts of the stack do some things better.
    If they are processing messages or doing some genuine BPI type work, calling services, transformations etc., then maybe a Singleton+Scheduled Task is not the best solution.
    I'm assuming the actual requirement is the process must run with no less than 1 minute between executions, but if an execution takes >1 min, don't overlap.  An internal 1 min timer would probably work very well, but you still have the problem of
    activating and deactivating the Orchestration.  You'd basically have to build some control infrastructure similar to the EDI Batching Service.
    Here's a completely different suggestion:
    SQL Table that maintains the state of each process, say Active or Complete.
    Poll every 15 seconds a Stored Procedure that tests the status and returns an activation message when that process shows Complete.  It would flip it to Active at the same time.
    Orchestration runs and the last shape sends a message to change the status to Complete.
    Rinse Repeat.  No long running Orchestrations, Singletons, Correlations, etc...
    Hi John,
    We have 8 independent orchestrations. Each of them is triggered by different scheduled receive location.
    The orchestrations then process messages (calling stored procedures, mapping and calling web services).
    You are right for the requirement. I tried to deactivate the receive location at the beginning of the process and restart it at the end, but I ran into some weird errors on the SSO DB and others like "Could not retrieve transport type data for Receive
    Location 'Trigger_xxxxx_SCHEDULE' from config store. The transaction associated with the current connection has completed but has not been disposed.  The transaction must be disposed before the connection can be used to execute SQL statements."
    Thanks for the new design suggestion, I will see the effort required and if the client approves it ;)

  • Is abap thread safe? Some question in Singleton pattern in ABAP

    Hi Grus,
    I have a very basic question but really make me headache...
    Recently I am learning the design pattern in ABAP and as you know in JAVA there is a key word "Synchronized" to keep thread safe. But in ABAP, I didn't find any key words like that. So does that mean ABAP is always a single thread language? And I found that there is a way looks like "CALL FUNCTION Remotefunction STARTING NEW TASK Taskname DESTINATION dest" to make multi-thread works. As you can see it use the destination, so does that mean actually the function module is always executed in a remote system, and in every system, it is always single thread?
    Could you help me on the question? Thanks a lot, grus
    And here comes up to my mind another question...It's a little bit mad but I think it may works....What if I set every attribute and method as static in the singleton class...Since as you can see it is already a singleton so every attribute in it should be only one piece. So then I don't even need to implement a get_instance( ) method to return the instance. Just call "class_name=>some_method( )" directly then singleton is achieved...What do you think?
    BR,
    Steve

    Steve,
    I've the same question, few days ago I tried to use the singleton in ABAP. In Java programming is possible to use the same reference in two sessions or programs, sharing attributes, methods and all data, but I could not do in ABAP.
    In my test I created a program with one global class using the singleton pattern, so I expected that when I run my program and see the reference returned after the get_instance method it should be equal to the same program run in another session, but the ABAP will create a new reference and instantiate again.
    So I deduced that the only way to share it between sessions in ABAP is using the ABAP Shared Memory Objects.
    I can be wrong, but I think that ABAP use a thread by user session (Each window) and we can't change it.
    Best regards.

Maybe you are looking for