Why use Factory classes

Why do we use Factory classes such BorderFactory, to get an instance of Border class, why cant we directly create an object of such classes like we do with regular concrete classes

Why do we use Factory classes such BorderFactory, to
get an instance of Border class, why cant we directly
create an object of such classes like we do with
regular concrete classesFactory methods (I mean static create methods here) have two advantages.
First, the library designer doesn't have to expose concrete classes to the outside world, just interfaces. This adds flexibility.
Second, the library designer is free to make object creations more flexible. The create method may take parameters that doesn't exactly correspond to a constructor of one specific class.

Similar Messages

  • Why use abstract classes?

    Why should I use abstract classes instead of a regular class with empty method bodies? Just better design? Is there some logical or performance based reason?

    Why should I use abstract classes instead of aregular
    class with empty method bodies? Just better design?Is
    there some logical or performance based reason?Because it describes what you're doing.
    If you define a "regular" class with empty message
    bodies, everyone who looks at it will say "WTF is he
    trying to do" or, if they're charitable, "Look,
    Harvey, someone who's trying to make Java look just
    like C++!".
    sigh Maybe answers like THIS are why people keep asking the same question.
    Here's a couple things an abstract class does that a "regular" class with empty methods bodies doesn't:
    1) An abstract class cannot be instantiated.
    2) An abstract class forces it's abstract methods to be implemented.
    If you were to extend a non-abstract class with empty method bodies, you wouldn't have to override the methods... you could just leave them empty. An abstract class forces it.
    There's a lot more reasons... those are a couple obvious ones.

  • Why Use Nested Classes

    Hi All,
    Why do we use Nested Classes ? Explain it with example ....
    If we say - It is a way of logically grouping classes that are only used in one place. Then we can say we use it through "Package" so why inner class ??
    Thanks in advance ....

    A real life example to jschell's explaination may be this.
    The pistons in your automobile engine are encapsulated by the engine block -- or the engine block encapsulates the pistons inside. This is the desired effect because as soon as we take the pistons out of the engine block, and put them say, in the backseat of the car instead, they no longer perform the function they were intended. There is another side effect to this analogy. When the pistons are properly installed in the engine block, there is only one movement the pistons can move -- up and down movement, that's it... they cannot rotate, spin, twist around or anything inside the engin block. Furthermore, the up and down movement is the only useful thing a piston can do. As soon as we throw the pistons in the backseat of the car, they can roll around, spin, and generally rotate to any configuration or orientation -- which does not produce any useful power.
    Inner classes are generally the same way. So we can see this example with a little code -- which we like.
    public class Engine
      Piston[] pistons = new Piston[8];
      class Piston
        // the usual methods here..
    }Of course, if your program is extremely sohisticated, this may not be a good solution -- for example, if you are making a catalog of automotive parts, then you would probably want your <tt>Piston</tt> class to be stand-alone.
    Edited by: pierrot_2. Also notice that the class <tt>Piston</tt> is not an INNER class of Backseat!

  • Hiding fields with zeros or blanks in ALV using factory classes

    Hi all,
    I am using Factory Method for displaying ALV.
    And I want to hide all the fields with Zeros or Blanks.
    Any help wud be rewarded.
    Thanks
    Preeti

    Hi,
       Below is the code used to hide a particular field ,here it is MANDT.This code is put after the factory method.
       data: lr_columns type ref to cl_salv_columns.
        lr_columns = gr_table->get_columns( ).
        lr_columns->set_optimize( abap_true ).
       data: lr_column type ref to cl_salv_column.
      try.
          lr_column = lr_columns->get_column( 'MANDT' ).
          lr_column->set_technical( if_salv_c_bool_sap=>true ).
        catch cx_salv_not_found.                          
      endtry.
    Thanks.

  • Why use helper classes?

    I am confused about the purpose of helper classes when using EJB's. Is the idea simply to make the code more maintainable? To separate data access code from the business logic? To aid the reuse of code? Why should I choose to use a helper class rather than creating a new EJB to do the job?
    I have been unable to find any comprehensive articles, and am a bit confused!
    Thanks in advance.

    - split out code into distinct functional models
    - split out code that can be reused effectively elsewhere
    - wrap objects that need to be passed to other modules as a whole
    - performance (EJBs are slow compared to standard beans)
    - keep code shorter (per file/method) so it's easier to read and maintain
    etc. etc.

  • Connection Factory class for Distributed Transaction?

    Definition of Managed Datasources goes like this at URL: http://download.oracle.com/docs/cd/B31017_01/web.1013/b28958/datasrc.htm#CHDDADCE
    Managed data sources are managed by OC4J. This means that OC4J provides critical system infrastructure such as global transaction management, connection pooling, and error handling.
    In the same document, I could also see a section for configuring Connection Pool, that uses 'factory-class' as 'oracle.jdbc.pool.OracleDataSource' as shown below:
    <connection-pool name="myConnectionPool">
    <connection-factory
    factory-class="oracle.jdbc.pool.OracleDataSource"
    user="scott"
    password="tiger"
    This configuration has worked well for my web application where I was using a single instance of Oracle database. In a new application I've to use two separate instance of Oracle databases and there is a need of distributed transaction.
    I know, I've to create two separate datasources for the two separate Oracle instances.
    My question is: Since now my transaction will be distributed in nature, do I need to use any other factory-class for configuring XA aware Datasources on OC4J? Or whether the same factory-class (oracle.jdbc.pool.OracleDataSource) will work even for distributed transactions?

    Here is the link for using Oracle RAC with WLS
    http://e-docs.bea.com/wls/docs81/jdbc/oracle_rac.html

  • Java Factory Classes

    What is the importance of using Factory Classes?How are they different from other Java classes?

    What is the importance of using Factory Classes?How
    are they different from other Java classes? Factory is a design pattern. The idea is that you
    don't do new of a class all over your program. Instead
    you call a static method of the class which
    instatiates the class for you. So new objects are
    created within the class itself. The class has become
    a "factory" of objects of itself.
    The discussion about how-to do conditional compiling and integrate the fact that you are developing cross-platform into the code is a good example of a possible use
    Another reason you might want to implement a factory, is when a certain object is very resource hungry in some way and you can reduce and regulate the instantiations of the class by using a factory to keep handig out a set of objects. The object must be usuable in this manner though.

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

  • Why to use Factory?

    Two options for creating an object within a certain class are to directly instantiate or use a factory:
    A a = new A();
    or
    A a = MyFactory.getA();
    The supposed advantage of using the factory is that the factory can return A or any subclass of A. But here's what confuses me: If you wanted to return a subclass of A, you would still have to make the change somewhere.
    If you decided that you wanted to return a subclass of A instead, you'd have to either change the code to "new SubclassA()", or change the implementation of the getA() factory method. Either way, you have to make a change somwhere...so what's the advantage of using a factory?
    Thanks.

    The factory method can decide which subclass to return at runtime based on whatever conditions are relevant.. You wouldn't just put return new A(); inside the factory class. There'd be some intelligence there.
    For instance, java.sql.DriverManager.getConnection(String url) looks through the registered JDBC drivers to find one that can handle the url passed in and returns an instance of that class.

  • Why are we using Abstract class?

    Why are we using Abstract class? What is specify use of Abstract class?

    The way I understand it....and I may be wrong because
    I am very new....is that by making the class abstract
    you will add abstract methods to it. Those abstract
    methods MUST be defined in in any subclass that
    inherits from the abstract class thereby making the
    abstract a template for subclasses.
    If your animal class is abstract then you would need
    an abstract method (Which is just siganture, no body)
    of say "numberOfLegs". Then in your dog and cat
    classes which extend animal you must define a
    "numberOfLegs" method with appropriate code.it isn't mandatory for an abstract class to have abstract methods. if a class does have abstract methods, the class must be abstract. but the following is perfectly legal
    public abstract class NoAbstractMethods {
      public void doStuff() {
         // do stuff
    }a subclass of an abstract class can also be abstract, and as such need not implement any additional methods

  • Why to use wrapper class?

    hello,
    can anybody please tell me why wrapper class are used in JAVA and what are exactly wrapper class?
    reply me soon....

    I want to give an example and then explain why it is for. Primitives will be good example for this situation.
    Example:
    Below are the primitive types and their wrapper classes...
    Primitive to Wrapper Class
    byte - Byte
    short - Short
    int - Integer
    long - Long
    char - Character
    float - Float
    double - Double
    boolean - Boolean
    USING OBJECT CREATION
    Think a situation when you create an integer object using this code:
    ---> Integer intVar = new Integer();
    you have the methods and constants:
    1 MAX_VALUE ,
    2 MIN_VALUE ,
    3 byteValue() ,
    4 compareTo(Integer anotherInteger) ,
    5 compareTo(Object o) ,
    6 decode(String nm) ,
    7 doubleValue() ,
    8 equals(Object obj) ,
    9 floatValue() ,
    10 getInteger(String nm) ,
    11 getInteger(String nm, int val) ,
    12 getInteger(String nm, Integer val) ,
    13 hashCode() ,
    14 intValue() ,
    15 longValue() ,
    16 parseInt(String s) ,
    17 parseInt(String s, int radix) ,
    18 shortValue() ,
    19 toBinaryString(int i) ,
    20 toHexString(int i) ,
    21 toOctalString(int i) ,
    22 toString(),
    23 toString(int i) ,
    24 toString(int i, int radix) ,
    25 valueOf(String s) ,
    26 valueOf(String s, int radix)
    now you have an object with 2 constants and 24 methods.
    USING WRAPPER CLASS
    and think using wrapper class of Integer..
    CODE ---> int intVar = Integer.parseInt((String)someStringData);
    In this case your Integer object have the methods and constants
    1 MAX_VALUE ,
    2 MIN_VALUE ,
    3 parseInt(String s) ,
    4 parseInt(String s, int radix) ,
    5 toBinaryString(int i) ,
    6 toHexString(int i) ,
    7 toOctalString(int i) ,
    8 toString(int i) ,
    9 toString(int i, int radix) ,
    10 valueOf(String s) ,
    11 valueOf(String s, int radix)
    as you in this situation you have 2 constants and 9 methods.
    AS YOU SEE THERE ARE 15 METHODS DIFFERENCE FROM THE OBJECT AND THE WRAPPER CLASS OF INTEGER OBJECT.
    NOW TALKING ABOUT PRIMITIVE TYPES ALL PROGRAMMERS USED THIS TYPES FOR THEIR CODES AND THEY ALWAYS NEED SOME THIS KIND OF CASTING. IN MY EXAMPLE I TAKE THE VALUE OF AN STRING VARIABLE. AND THERE ARE LOTS OF THINGS SIMILIAR TO THIS EXAMPLE.
    IDEA OF THIS WRAPPER CLASSES IS THAT USE AS YOU NEED NOTHING MORE. IN THE WRAPPER CLASS YOU DONT HAVE INTEGER OBJECT. YOU ONLY NEED THE PARSEINT METHOD OF INTEGER OBJECT INSTEAD OF CREATING THE INTEGER OBJECT YOU USE THE WRAPPER CLASS OF THIS TYPE...
    OBJECTS ARE STORED IN A MEMORY PLACE CALLED HEAP WHICH IS PLACED ON RAM AND GARBAGING OF THIS OBJECTS TAKES MORE TIME TO ALLOCATE FROM HEAP STORAGE.
    AND ANOTHER NOTE FOR THIS WRAPPER CLASSES if you want to store an int inside a container such as an ArrayList (which takes only Object references), you can wrap your int inside the standard library Integer class
    EX:
    import java.util.*;
    public class ImmutableInteger {
    public static void main(String[] args) {
    List v = new ArrayList();
    for(int i = 0; i < 10; i++)
    v.add(new Integer(i));
    // But how do you change the int inside the Integer?
    } ///:~
    GOOD LUCK...
    REALKINGTA....

  • Why JSP not use new class that I compile again?

    I use bean class with JSP. But When I add some code and compile new bean. JSP not use new been class it use old class.
    I try to set file server.xml and set <DefaultContext reloadable="true"/> and restart Tomcat. But it not work?
    any help please?

    I run JSP in http://localhost:8080/stringbean.jsp
    is context name mean localhost
    in c:\tomcat\work has following directory
    standalone (level1 dir)
    localhost (level2 dir)
    - (level3 dir)
    examples (level3 dir)
    manager (level3 dir)
    tomcat-doc (level3 dir)
    webdav (level3 dir)

  • 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

  • Why can't classes with private constructors be subclassed?

    Why can't classes with private constructors be subclassed?
    I know specifying a private nullary constructor means you dont want the class to be instantiated or the class is a factory or a singleton pattern. I know the workaround is to just wrap all the methods of the intended superclass, but that just seems less wizardly.
    Example:
    I really, really want to be able to subclass java.util.Arrays, like so:
    package com.tassajara.util;
    import java.util.LinkedList;
    import java.util.List;
    public class Arrays extends java.util.Arrays {
        public static List asList(boolean[] array) {
            List result = new LinkedList();
            for (int i = 0; i < array.length; i++)
                result.add(new Boolean(array));
    return result;
    public static List asList( char[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Character(array[i]));
    return result;
    public static List asList( byte[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Byte(array[i]));
    return result;
    public static List asList( short[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Short(array[i]));
    return result;
    public static List asList( int[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Integer(array[i]));
    return result;
    public static List asList( long[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Long(array[i]));
    return result;
    public static List asList( float[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Float(array[i]));
    return result;
    public static List asList( double[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Double(array[i]));
    return result;
    // Now that we extend java.util.Arrays this method is not needed.
    // /**JCF already does this so just wrap their implementation
    // public static List asList(Object[] array) {
    // return java.util.Arrays.asList(array);
    public static List asList(Object object) {
    List result;
    Class type = object.getClass().getComponentType();
    if (type != null && type.isPrimitive()) {
    if (type == Boolean.TYPE)
    result = asList((boolean[])object);
    else if (type == Character.TYPE)
    result = asList(( char[])object);
    else if (type == Byte.TYPE)
    result = asList(( byte[])object);
    else if (type == Short.TYPE)
    result = asList(( short[])object);
    else if (type == Integer.TYPE)
    result = asList(( int[])object);
    else if (type == Long.TYPE)
    result = asList(( long[])object);
    else if (type == Float.TYPE)
    result = asList(( float[])object);
    else if (type == Double.TYPE)
    result = asList(( double[])object);
    } else {
    result = java.util.Arrays.asList((Object[])object);
    return result;
    I do not intend to instantiate com.tassajara.util.Arrays as all my methods are static just like java.util.Arrays. You can see where I started to wrap asList(Object[] o). I could continue and wrap all of java.util.Arrays methods, but thats annoying and much less elegant.

    Why can't classes with private constructors be
    subclassed?Because the subclass can't access the superclass constructor.
    I really, really want to be able to subclass
    java.util.Arrays, like so:Why? It only contains static methods, so why don't you just create a separate class?
    I do not intend to instantiate
    com.tassajara.util.Arrays as all my methods are static
    just like java.util.Arrays. You can see where I
    started to wrap asList(Object[] o). I could continue
    and wrap all of java.util.Arrays methods, but thats
    annoying and much less elegant.There's no need to duplicate all the methods - just call them when you want to use them.
    It really does sound like you're barking up the wrong tree here. I can see no good reason to want to subclass java.util.Arrays. Could you could explain why you want to do that? - perhaps you are misunderstanding static methods.
    Precisely as you said, if they didn't want me to
    subclass it they would have declared it final.Classes with no non-private constructors are implicitly final.
    But they didn't. There has to be a way for an API
    developer to indicate that a class is merely not to be
    instantiated, and not both uninstantiable and
    unextendable.There is - declare it abstract. Since that isn't what was done here, I would assume the writers don't want you to be able to subclass java.util.Arrays

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

Maybe you are looking for

  • Message app wont open up

    i have some problems opening up the Message app (apples own). It starts and closes immidiatley. the same goes for some of the other built in apps. like fonts wont open, i had som e problems with mail before. i have an imac mid 2010 and the latest ver

  • Please help with error message while trying to update i tunes

    Errors occurred while installing the updates, if the problem persists, choose tools, download only and installing manually

  • Boolean error with a If else statement

    Hello, i am new to java, and the only other programing language i have used is pascal, and compared to java its ALOT different any ways my problem. I am trying to write a simply little program which random selects a number between 1 and 10, i did tha

  • Can I get a HP Deskjet 960 to work on a new macbook pro?

    A friend of mine just bought a new MacBook 13" and has a Deskjet 960 and cannot find a driver, is it possible to find a driver that will work?

  • Multiple like statements in a query

    Hi, I wonder if it's possible to have multiple like statements in a query. suppose instead of select * from someTable where remarks like '%ab%' I want to search for many string patterns such as '%edi%' '%odi%' '%di%' '%gf%' '%od%' '%podi%' etc. in on