Factory class and static members

I don't understand very well why sometimes you can find a factory class (for example for the xml parsers). What's its aim?
And why sometuimes, instead of a constructor, some classes have only static methods that returns a reference to that object?
Anyone can tell me?
Thanks

Static memebers can be used in places where instances of its enclosing class is not neccesary.Only a method is required to be executed. Let me tell you with an example,
class ConnectionPool {
public static giveConnection(int index) {
In the above example, our objective is to use only the method public static giveConnection(int index) {} , and not any of the other attributes of this class. You have 2 ways to use this method : One is, you can instantiate ConnectionPool p = new ConnectionPool(); . Second is , just use ConnectionPool.giveConnection(2);
The first solution may create instance and obstruct your performance. Seond one does not do that. All invokers of this method do not instantiate and occupy space.
Usually, factory classes have static members. Because these classes are used as a supporting processing factory. Theses members can be considered as utility methods. Hence static property will better suit for them. This answer will also tell you that the use of constructors here is not neccessary.
Hope this has helped you.
Rajesh

Similar Messages

  • 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.

  • JVM and static members of classes

    Hello Experts,
    I have applet project. Recently I reorganized the code and I made so many class members "static".
    The applet starts from javascript link from browser. When I start it at first time, everythink is OK,
    but when I start it second time there is a problem with these static members(Actually they are dialogs,
    panels, vectors and s.o.) They are saved in the memory in some way. When I close the parent browser(the browser
    that holds the javascript link) and then start again, everything is OK, because I starting applet for
    first time.
    How can I make the following calls like the first one ?
    Please help me !
    Best Regards,
    Valeri

    When u are opening a browser the static variables
    are persistance unless u closed the window.
    so while u are opening the second time the
    static variables are not initalizing.
    so if u remove the static .
    Or after displaying the applet u initialize the
    staic variable.

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Your Opinions: Inner Classes Need static Members

    Hi All,
    I want to solicit opinions for a minor change to the way inner classes work. I submitted this as an RFE to Sun and they rejected it, really without giving a reason. I'd like to know your opinions. If there is strong support I will repost the RFE.
    As you probably know, inner classes cannot have static members. The following generates a compiler error:import java.util.*;
    public class MyClass {
       class MyInnerClass {
          // Next line causes compiler error...
          static Map m = new HashMap();
    }In order to get around this you have to make the Map variable a static member of the containing class:import java.util.*;
    public class MyClass {
       static Map m = new HashMap(); // so much for encapsulation...
       class MyInnerClass {
    }I am suggesting that inner class be allowed to contain static members. Here's my reasoning...please comment:
    There are times when members (i.e., fields and methods) rightfully belong to the class as a whole, not to any particular instance of a class. I'm sure we've all found times when it was necessary to have static members in our classes. The same issues that necessitated using static members in top-level classes make them desirable for inner classes as well.
    Designing a class as an inner class is a step toward encapsulation. By forcing static members that logically belong in an inner class to be declared in the containing class is to crack the encapsulation, IMHO.
    Even though a containing class has access to all of an inner class' members (including private members) and vice versa, I think the notion of inner static members still is more OO-ish.
    What are your opinions? Would allowing inner classes to contain static members make Java more object oriented? I think it would.
    Technically, I don't think there's any reason this cannot work since the JVM has no notion of inner classes, per se.
    What do you think?

    an inner class is effectively a non static instance
    variable of its enclosing class. Instance member, but not a variable. it's a class, a type, not a variable.
    >
    I think the problem here is that making a field static
    means more than just that that field and its value are
    common to every instance of the class. It means that
    the value is valid without an instantiation of that
    class.
    Since the class itself must be instantiated (it is
    not static), What do you mean, excatly, by "_must_ be instantiated"? You are not ever "required" to instantiate anything unless you want to use it.
    you can't have static member data inside it. I don't see how this follows from the previous part of the statement.
    How would you reference the static member data of
    the inner class? You would have to specify an
    instance of the inner class, and since this breaks
    the meaning of static, you can't have static members
    in an inner class.How about outerObj.InnerClass.staticMember The syntax is well defined. The question at hand is, do we really want to allow this? The syntax to do this should only be an issue after that question has been answered in the affirmative. The people at Sun have decided not to allow it, so for now, syntax is a non-issue.
    >
    if you wanted a static member in an inner class you
    could put it in a super class of the inner class...Or in the enclosing class, as suggested in the orginal post.

  • 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...

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • Classes and Static

    1. i have Class a, this has static main
    2. i have Class Conn, this connects the DB
    3. i have Class Men, has Methods
    4. i Create in Class Conn a Vector from Class Men.
    5. main is static. i call Conn in main.
    6. java doesnt allow me to call Conn from main if Conn methods are not Static.
    7. ok i made Conn methods static.
    8. now: if i want to call the Vector of Men Class in Conn Class. i cant. i have to make Men Class also Static.
    9. well greate java. everything must get Static!!!! hmm.
    whats the solution?
    thx

    I agree that you are probably best helped by reading an introduction to Java programming.
    The "main" thing in this case is that you shouldn't try to do everything directly from your main method. In your class a (which should by convention be called A, or better yet, something a little more descriptive), you have a main method that is used to start your application. This method should look something like this:public static void main(String[] args) {
       A myApplication = new A();
       a.performDuties(); // this is a method you have to create
    }That's it, no more. The method performDuties() (which is NOT static) will do all the work.

  • Factory Reset and Static when uploading! HELP!?!

    How can I factory reset Garageband 11? I think it will fix my problem below or if anyone knows how to fix the problem below??
    THANK YOU!!!
    When using the Analog Mono (default) on a loop like Trance Tunnel Bass 2 it gives it the effect I'm looking for. Now on the song I've composed sounds good on GB, the iPod, iPhone, & iTunes, but once I uploaded to Soundcloud or band camp the audio has this static sound to it. If I add Automatic Filter (Default) to the Analog effect and uploaded to those media sites it does have they static anymore. Could the settings be the issue to that or is there something wrong with GB?

    NuDroidUsrr wrote:
    wardcst24 wrote:
    NuDroidUsrr wrote:
    randallg wrote:
    What a freakin' joke.  Missed calls, screen freezes 2-3 times per day and friends sending texts that I don't get because Verizon doesn't give a rats arse about anything but YOUR $$$$!  The common verbiage from ANY REP is..."Factory Reset"...*228..."pull the battery..wait 10 minutes then hold the volume buton down...then hold it up all while re-installing the battery"..Why? Because that is what they have been told to say to pacify all the "we got taken" customers.  People...wake up!  Neither the factory reset OR * 228 have helped at any time.  We are stuck wth these *** phones until our contracts run out.  I should have purchased the i-Phone 4, but thought saving $100 on the Fascinate was a good choice.  Just face it...you are going to miss calls...you are going to miss texts...your phone is going to freeze up and you will have to pull the battery 1 or more times per day AND, Verizon and Samsung are laughing all the way to the bank!  As for myself, I will wait for my next bonus check in August and go get the i-Phone 4.  Besides me & my wife having problems with the Fascinate, I have 5 other friends that also have it and they are having the exact same problems!  I guess having the Fascinate is better than a poke in the eye with a sharp stick!   I guess.
      There was a thread someone posted about the issue of not receiving phone calls, and the fact that it seemed to lose the device with the phone number? Someone suggested taking another phone, activate that phone with your number, and then re-activate the Fascinate on your number.
     Not sure if this will help or not, but I saw it somewhere out in the forums.
    I have did that at least 7 times it Fails also
      Just a thought.
    Sorry I was not criticizing you I am at my whit's end and have tried about everything

  • Abstract class and static function

    Please tell me that why a static function can't be made abstract?
    Thanks.
    Edited by: RohitRawat on Sep 9, 2009 7:45 AM

    RohitRawat wrote:
    Please tell me that why a static function can't be made abstract?
    Thanks.Because the method belongs to the class.

  • Static class and clustering

              I have a static class that I use to cache some values during a batch process. The
              batch process uses a JMS queue to parcel our identical units of work to MDBs.
              I want this to scale using a cluster with the same MDBs on multiple machines.
              Everything works fine except that I can't figure out how to tell my cache to clear
              itself out on every node between batch runs. Is there a pattern or solution to
              this problem?
              What I've tried is to create a stateless session bean method that clears my cache.
              At the begining of my batch job, (which is a stateless session bean call) I call
              this method on each server in the cluster by getting the remote interface for
              the stateless bean via the different URLs of the servers. However, the session
              bean method always executes on the one server where I make the call. It's as if
              WebLogic gives me back a local interface instead of the remote interface that
              I asked for.
              Any ideas would be appreciated.
              Colin
              

    ... static class and static method.I have never heard of a thing called "static class". Perhaps you mean a class with only static members?
    My design approach (which is bound to needs of the moment and seldom to library-development or future re-use, since both is harder than most developers realize) is to develop straight without caring too much about static or not. When a method is done, debugged and works well, it happens that other objects access this method as well.
    It may happen that I just want to use this single method and almost nothing else of the object. If that is the case, I can start looking if it's a Good Thing(tm) to make the method static, so no object creation is needed just for the one method. Sometimes it can be done, sometimes not.
    But that's just me and you'll find quite a lot of coders that'll advice you to decide what's static and what not before you start coding. And that's as good an advice as most others you can get.
    In the end it's your decision, so start fiddling around and see what fits best for you.
    -T-

  • Unusual use of interface defining static factory class with getInstance

    This question is prompted by a recent New to Java forum question ask about the differences between Interfaces and Abstract classes. Of course one of the standard things mentioned is that interfaces cannot actually implement a method.
    One of my past clients, one of the 500 group, uses interfaces as class factories. The interface defines a pubic static class with a public static method, getInstance, that is called to generate instances of a class that implements the interface.
    This architecture was very object-oriented, made good use of polymorphism and worked very well. But I haven't seen this architecture used anywhere else and it seemed a little convoluted.
    Here is a 'pseudo' version of the basic interface template and use
    -- interface that defines public static factory class and getInstance method
    public interface abc {
        public static class FactoryClass
            public static abc getInstance ()
                return (abc) FactoryGenerator(new abcImpl(), abc.class);
    -- call of interface factory to create an instance
    abc myABC = abc.Factory.getInstance();1. Each main functional area ('abc' in the above) has its own interface factory
    2. Each main functional area has its own implementation class for that interface
    3. There is one generator (FactoryGenerator) that uses the interface class ('abc.class') to determine which implementation class to instantiate and return. The generator class can be configured at startup to control the actual class to return for any given interface.
    I should mention that the people that designed this entire architecture were not novices. They wrote some very sophisticated multi-threaded code that rarely had problems, was high performance and was easy to extend to add new functionality (interfaces and implementing classes) - pretty much plug-n-play with few, if any, side-effects that affected existing modules.
    Is this a best-practices method of designing factory classes and methods? Please provide any comments about the use of an architecture like this.

    Thanks for the feedback.
    >
    I don't see how 'the generator class can be configured at startup to control the actual class to return for any given interface' can possibly be true given this pseudo-code.
    >
    I can see why that isn't clear just from what is posted.
    The way it was explained to me at the time is that the interface uses standard naming conventions and acts like a template to make it easy to clone for new modules: just change 'abc' to 'def' in three places and write a new 'defImpl' class that extends the interface and the new interface and class can just 'plug in' to the framework.
    The new 'defImpl' class established the baseline functionality that must be supported. This line
    return (abc) FactoryGenerator(new abcImpl(), abc.class);uses the initial version of the new class that was defined, 'abcImpl()', when calling the FactoryGenerator and it acted as a 'minimum version supported'. The generator class could use configuration information, if provided, to provide a newer class version that would extend this default class. Their reasoning was that this allowed the framework to use multiple versions of the class as needed when bugs got fixed or new functionality was introduced.
    So the initial objects would be an interface 'abc' and a class 'abcImpl'. Then the next version (bug fixes or enhancements) would be introduced by creating a new class, perhaps 'abcImpl_version2'. A configuration parameter could be passed giving 'abcImpl' as the base class to expect in the FactoryGenerator call and the generator would actually create an instance of 'abcImpl_version2' or any other class that extended 'abcImpl'.
    It certainly go the job done. You could use multiple versions of the class for different environments as you worked new functionality from DEV, TEST, QA and PRODUCTION environments without changing the basic framework.
    I've never seen any Java 'pattern' that looks like that or any pattern where an interface contained a class. It seemed really convoluted to me and seems like the 'versioning' aspect of it could have been accomplished in a more straightforward manner.
    Thanks for the feedback. If you wouldn't mind expanding a bit on one comment you made then I will mark this ANSWERED and put it to rest.
    >
    I don't mind interfaces containing classes per se when necessary
    >
    I have never seen this except at this one site. Would you relate any info about where you have seen or used this or when it might be necessary?

  • Singleton with static members only

    If I have a singleton class with static members only and I'd like to ensure that nobody accidentally instantiates the class, would it make sense to declare the class abstract? Or instead should I leave it non-abstract but make the no-argument constructor private? Or both?
    Which of these approaches would you recommend?
    Thanks.

    pros of using classical singletons (per Head First
    Design Patterns):
    1) It ensures that one and only one object is
    instantiated for a given class.This is effectively the same as using a non-instantiable class with all static members. You don't have an instance, but you have exactly one of it.
    2) It gives a global point of access like a global
    variableAgain, same thing with a non-instantiable class with all static members.
    3) It is only created when you need it (unlike a
    global variable) and thus wastes no resources if it
    is not needed.Again, same thing.
    Also, Java does not have global variables.
    Also, no variable in Java requires more than 8 bytes, and most are 4 or 2.
    4) Using a static self-contained class in place of a
    singleton can be a source of subtle, hard-to-find
    bugs often involving order of initialization of
    static code.Eh? Example please?
    5) Global variables encourage developers to pollute
    the namespace with lots of global references to small
    objects.What global variable? Java doesn't have global variables? How is a class full of statics any more a global than a "real" singleton?

  • Factory class

    Hi
    I could not understand the concept of factory classes and why they are being used in many j2ee design patterns. probably this is a design question but not sure. please help me out.

    Hi
    I could not understand the concept of factory classes
    and why they are being used in many j2ee design
    patterns. probably this is a design question but not
    sure. please help me out.It tends to be about hiding concrete implementation classes behind interfaces so that, for example, a different implementation can be substituted transparently.
    For example, using this technique, the application program doesn't need to know if an object is implemented locally or remotely.
    The JDBC is an example familiar to most. You never instantiate a Connection, Statement, ResultSet yourself. All you see is interfaces. The concrete classes behind them depend which database you're using and are hidden away in the driver libraries. The DriverManager is the factory class in this case.
    You can have one central routine which searches the libraries supplied for candidate factory classes and asks each in turn if it can provide an implementation of the interface you want.

  • Life and memory space for static members of a class

    hi,
    as we all know that instance members reside on heap inside object to which they belong, where do the static members reside on the heap or on stack..

    All objects reside on the heap.*
    *I think Java 6 or 7 may allow purely local objects to live on the stack, but if an object is referred to by a member variable--whether static or not--it will live on the heap.                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • Ideas to Improve Tagging of photos in PSE Organizer

    I've been using PSE since V2 and recently upgraded from PSE 11 to PSE 13. While PSE is solid and has some nice new features, it's apparent after some use that my hopes that manual face tagging would be greatly improved were not realized.  I take some

  • MEGA180 as wireless access point?

    Since I've spent so much time and money cooling the thing off, I was wondering if I can use it as a WAP, and avoid spending more on a separate piece of equipment.  My 180 stays on all the time, so is there a way I can get internet access on a laptop

  • Oracle Database 10.1.0.2 Enterprise Windows

    Hi, Can you tell if i can download somewhere the installation files for Oracle Database 10.1.0.2? I have a production DB with this Oracle version but i can't upgrade it and need to reinstall a standby database. The problem, i lost the installation fi

  • I want to display a DIV , when a radiobutton is clicked... how ?

    how do I achieve it ? I found some examples googling around but none works good yet... please help..

  • Safari: picture issues(pixelated)/ Flash movies Flickers

    In Safari and sometimes in iTunes(rarely) pictures are presented/ rendered in low quality. You easily see grainy/ pixel noise following lines in the picture. It is not a problem in iPhoto were pictures are in excellent condition. Also when watching f