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?

Similar Messages

  • Reflect public field from static Factory class

    Hi, i have a static factory(all public static fields and methods, and private constructor), and i want to reflect one of the public fields with reflection. eg.
    package pak;
    public class Factory{
    public static byte MYFIELD=0;
    //private cannot instantiate
    private Factory(){}
    I which to use reflection to do somethin like this in another class
    try {
    Class xClass= Class.forName("pak.Factory"); //getClass ref
    Object xInstance= xClass.newInstance(); //ERR**get Object to extract field Val
    //4 Field.getByte(Object)
    SPECIFIED_VAL = xClass.getField("MYFIELD").getByte(xInstance);
    } catch (ClassNotFoundException e) {
    e.prin...................
    However as the nature of the static factory, i can't instantiate it so can't use
    java.lang.reflect.Field.getByte(Object)
    what i need is something like
    java.lang.reflect.Field.getByte()
    ??Any ideas on how to over come this?

    To get a single "known" static field you would do:
    Class myClass = Class.forName("my.Class");
    Field myClassField = myClass.getField("myField");
    Object value = myField.get(null);if you want all the fields:
    Class myClass = Class.forName("my.Class");
    Field[] allClassFields = myClass.getFields();Check the API docs under java.lang.Class ;-)

  • Using Methods not Defined in a class that you are calling them from

    For one of my assignment I have had to create a class with methods and then create another class to test the methods.
    I keep getting the error message "cannot resolve symbol"
    And the error points to the line where I am calling the class.
    I have put the classes in a package and imported them.
    Here is the method I am calling.
    public boolean validDate(int day, int month, int year)
    if(leapYear(year))
    daysInMonth = 29;
    else
    getNumberOfDaysInMonth(month);
    return true;
    This is how I am calling it from the test class
    if(validDate(day1,month1,year1))
    testnewDate.java:38 cannot resolve symbol
    symbol : method validDate(int,int,int)
    location:class newdate.testnewDate
    if(validDate(day1,month1,year1))
    ^
    If anyone is able to help I can give you my java source files if I haven't given enough information.

    You can't call another class's method directly from your class. You need to get an object of that class and should call the method using that object.
    If you have written public boolean validDate(int day, int month, int year) method in class DateValidator, then from your test class, you have to call that like this,
    DateValidator dv = new DateValidator();
    if(dv.validDate(day1,month1,year1)) {
    // Take actions
    Hope it is clear.
    Sudha

  • Initializing Factory class with Digital Signature

    Hi All,
    I am trying to Initialize the Factory class using digital signature. These are the steps I fallowed.
    1. Created a Java application "Application1" in Jdeveloper.
    2. Copied config, ext, lib folder from the Design console directory to the Application1/Project1 folder.
    3. added the lib and ext jars to the project properties.
    4. Modified the run/debug profile in the project properties to point to the xlconfig file in config folder.
    5. added the "-DXL.HomeDir=. -Djava.security.auth.login.config=config\authwl.conf" in the java options.
    Java code:
    public class SignatureLogin {
    public static void main(String[] args) throws Exception {
    Properties jndi =
    ConfigurationClient.getComplexSettingByPath("Discovery.CoreServer").getAllSettings();
    tcSignatureMessage signedMsg = tcCryptoUtil.sign("xelsysadm", "PrivateKey");
    tcUtilityFactory factory = new tcUtilityFactory(jndi, signedMsg);
    tcUserOperationsIntf usrIntf = (tcUserOperationsIntf)factory.getUtility("Thor.API.Operations.tcUserOperationsIntf");
    System.out.println("signature login complete");
    // Do something with usrIntf here
    Map filter = new HashMap();
    filter.put("Users.Key", "7464");
    tcResultSet rSet = usrIntf.findAllUsers(filter);
    rSet.goToRow(0);
    System.out.println(rSet.toString());
    factory.close();
    System.out.println("logout complete");
    System.exit(0);
    Then ran the java class. I am able to get the connection but when I am using findAllUsers(map) method to search the usr table I am get a nullpointer exception.
    Exception in thread "main" java.lang.NullPointerException
         at Thor.API.Operations.tcUserOperationsClient.findAllUsers(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at Thor.API.Base.SecurityInvocationHandler$1.run(Unknown Source)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(Unknown Source)
         at weblogic.security.Security.runAs(Security.java:41)
         at Thor.API.Security.LoginHandler.weblogicLoginSession.runAs(Unknown Source)
         at Thor.API.Base.SecurityInvocationHandler.invoke(Unknown Source)
         at $Proxy0.findAllUsers(Unknown Source)
         at com.ssi.utils.custom.code.SignatureLogin.main(SignatureLogin.java:26)
    I need some help to fix this.
    Thanks

    Hi,
    Were you able to resolve the issue as I am facing same issue.
    I have a custom application deployed on same weblogic managed server where OIM is installed but when I try to find user in OIM it gives me null pointer exception.
    I have even checked the username with which connection is established using ioUtilityFactory.getUserName() and it gives me the correct user.
    Thanks
    Edited by: user1105482 on 26-Apr-2011 04:38

  • Using stored parameter from data control class with stacked bar-graph

    Hi folks,
    I'm relatively new to ADF & EJB so I want to apologise in advance if this question seems rudimentary to many of you.
    Edit:  I should have mentioned that I'm using JDeveloper 11.1.1.5
    I'm having a hard time determining how to retrieve the value from a variable to be assigned to a property of the bar graph I'm trying to display on my JSF page.
    I have tried to briefly summarise the logic below for reference.
    I have a data control class (ActivityChart) that includes a method "getActivityDetail" returns a List of custom Objects (ActivityDTO) that are the underlying data for my bar graph.
    public class ActivityChart {
        private Double axisScale;
        public ActivityChart() {
            super();
            axisScale = 0.0;
        public List<ActivityDTO> getActivityDetail(List<String> businessUnits) {
            List<ActivityDTO> returnNewList = new ArrayList<ActivityDTO>();
            List<TransactionDTO> dataList = new ArrayList<TransactionDTO>();
            TransactionSessionBean transBean = lookupTransactionSessionBean();
            if (businessUnits != null && !businessUnits.isEmpty()){
                dataList = transBean.getActivityData(SystemUtil.getCurrentUser(), businessUnits);           
                returnNewList = processTransactions(dataList);
                axisScale = calcAxisScale(returnNewList);
            return returnNewList;
    ...The TransactionDTO object is basically a mirror of the entity object to store the fields from the queried db transactions.
    The ActivityDTO object contains a String value (x-axis label) and 3 Double values for the values required for the bar graph.
    What I'm trying to do is dynamically set the scale for the 2 y-axes (I'm using a dual-axis stacked bar graph) because the auto calculated values are not aligned.
    Right now I've got the two relevant elements of the bar graph hard-coded with a specific axis value:
    <dvt:y1Axis axisMaxAutoScaled="false" axisMaxValue="100.0"/>
    <dvt:y2Axis axisMaxAutoScaled="false" axisMaxValue="100.0"/>.
    The value I want to use for the Y-axis is calculated and stored in the "axisScale" variable in the above class.
    Really at a loss of how to move forward from here.
    Would very much appreciate any guidance/direction offered.
    Thanks,
    Karim
    Edited by: 973742 on Nov 28, 2012 8:12 AM

    Looks like I may have found the answer!
    I had to set up the variable in the bindings for the page and then reference the variable from the binding and add the property inputValue.
    ie. value="#{bindings.axisScale.inputValue}"

  • Why a non static member class can be defined in an interface

    Non-static member classes are defined as instance members of other classes, just like fields and instance methods are defined in a class. An instance of a non-static member class always has an enclosing instance associated with it.
    An interface can't be instantiated then how a non static member class will have an enclosing instance associated with it.
    interface outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
        public  static class inner1{
                public void p(){System.out.println("inside interface's  static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
            nonStatic.p();
        outer.inner1 stat = new outer.inner1();
          stat.p();
    }inner is a non static member class even then " outer.inner nonStatic = new outer.inner();" working fine ?????????????

    class outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    }on compiling the above code the error message i got is
    "not an enclosing class: outer"
    the reason of this compilation error is "outer.inner nonStatic = new outer.inner();
    it should be "outer.inner nonStatic = new outer(). new inner();"
    now my question is
    interface outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    }on compiling the above code why compilation error is not coming??????????
    i think now it is more clear what i am asking

  • Using Objects to Initialize Static Fields: Good or Bad

    I have a Command interface and a bunch of Commands that implement it (i.e. CmdJoin,CmdQuit). These Commands' settings change at runtime (i.e. required access levels, String identifiers). I don't want to have to store an instance of each Command in a database to save their settings , so instead I'm using the obvious solution: making static fields in these commands for these settings. This way, I can use a Simple Factory to return a Command, change its settings, execute it, and forget it, and still have the settings for that Command apply to all Commands. Yet I want to be able to modify and access fields of different Commands polymorphically. How can I have these commands' settings-related fields be static while modifying and accessing these fields polymorphically?
    Here's what I have though of. First of all, interfaces can't have static methods. Secondly, neither can abstract classes. I also can't extend a base class which implements these settings-related fields and their interface, because then the fields would belong to all child classes of this base class, whereas I just want it to belong to a certain child class of the base class (i.e. all instances of CmdJoin or CmdQuit).
    I've thought of two solutions.
    The first is implementing a concrete interface in an abstract base class (getting rid of the Command interface) and overriding it in child classes, so that I can use the interface of the base class and the fields of the child classes.
    The second is having no base class, and just a bunch of Commands implementing the interface with their own static fields. I would initialize these fields by passing arguments to their constructors.
    These solutions seem very sloppy though! Are there any better ways?

    To clarify, I want all objects of type A to be able to respond to a static method declared in type A yet still remember their implementation of this static method. I provided two solutions that I have thought of, and I find them sloppy, so I'm asking if there's a better way.

  • ABAP-Memory per User or static ABAP-class??

    Hi there,
    I want to save some information for each user in a transaction which uses SUBMIT-statements. So I want to store the information globally across reports and transactions (starting from my own single transaction).
    So I can use the ABAP-Memory for storing this information. Is the information stored there seperated by user or is it possible that one user gehts the information of another user? When is ABAP-memory cleared? Is this done automaticly when my transaction flow is finished.
    Alternatively I think I can use a global static ABAP-class with attributes to store the information. Is such a ABAP-class also user-dependent??
    And when is this information cleared??
    Can you give me some hints?
    Thank you very much!
    Kind regards
    Jens

    Hi,
    Both ABAP and SAP memory are user specific. In your case if the issue would concern just one user you should go for SAP memory (when data should be exchanged between external sessions that is windows of SAP gui) or ABAP memory when data exchanged within one external session (between internal sessions - that is between programs run in one GUI session ).
    If you want the data be stored globally for all the users, you have to either store them in some custom global table in DDIC (and later read from different user) or use [Shared objects|http://help.sap.com/saphelp_nw70/helpdata/EN/14/dafc3e9d3b6927e10000000a114084/frameset.htm] which is a special memory buffer in Application Server, where you can exchange data between user sessions.
    Regards
    Marcin

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

  • Understanding the use of interface class?

    Hello,
    This question referes to java servlets, but the questions is about java design.
    My wrox java server pages text, includes an example where some user data is posted to servlet.
    To process the data posted and store this, they created a interface class and another class AdminManager which implements the interface.
    In the servlet they create an object from the interface class, and call the AdminManager methods through the interface object.
    In the book this was the only example which used a interface. And I wondered if this design approach was often used, or should an interface normally be used if several classes would implement the interface.
    Thanks

    It depends. You might want to create an interface even if you only have a single implementation of that interface in mind, because you want to make it easy to create more implemenations later.
    Also keep in mind that not all implementations of an interface are strictly for production use. For example, you might want to define an interface, define an implementation of that interface for production use, but then also define a "mock" version of that interface for testing, prototyping, etc.
    Generally I feel that if you have a sufficiently complex set of types and relationships between those types, it makes a lot of sense to express those relationships purely as interfaces, on a high level. Then provide implemenations as a separate step in the programming process.

  • 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

  • When  we going to use static inner class

    Hi
    when we r going use static inner class
    inner classes use for to create adaptorclasses that implement an interface.
    what about Static inner class
    if possible give some examples
    Thanks in adv

    static inner classes are used when the inner class does not require to access the encompassing class's variables/methods. By default non-static inner classes obtain a reference to the outer class instance through which they access the outer class variables and methods
    ram.

  • SessionBean class can be defined static?

    Can we define session bean class 'static'.In the EJB specification I cannot find any limitation on not defining a session bean class as static.
    regards
    ashish

    Without more info of the other bits of your system
    then it's hard to say what's best.
    How are you accessing your database? Are you using
    Entity Beans? CMP?
    If so, you should use a session bean to help with
    transactions.The current design is that for each list, I'm using a Stateful Session bean that contains a Vector of CMP EJB references. This list is what I would prefer to not have each session recreate as some of the lists contain hundreds of items (EJB's). It would be desirable in terms of memory and performance to create these Session beans intitially and have every session continue to reference them without having to recreating for each session.
    But even so, if the application-level non EJB class representing the list contained EJB references, what happens when the session they were initially created under goes away? Will the container still hold a reference to these objects?
    Like I said, I can make all these list objects and the objects they reference static application-level standard beans and create them only the first time they are referenced, but that circumvents using the container and EJB's for this part of the architecture.

  • When to use interface and when Abstract Class?

    In a recent interview I was asked "When to use interface and when Abstract Class?" Explain with an example.
    Also in what situations a class should be made final(real time example)

    Interface is a pure contract with no implementation. Typically used to define a communication contract between two different sub-systems. Example EJB home interface. This also allows the design to change as long as the contract is met.
    Abstract class is when there exists a lot of common functionality already known and can be coded. However, a few unknowns exists (typically about data) for which abstract methods need to be defined and implemented by the sub class.
    Example: Consider a workflow engine. A great example for abstract class. The workflow process has lot of common code that is independent of the workflow type (vendor flow, contract flow, payment flow etc). However, certain decisions on the route to take will depend on value of data being submitted. So the base class will define a abstract Data getData() method and proceed assuming data will come. The implementing subclass will provide the actual logic for getting the data.
    Also see the "Template" design pattern.
    Note: To some extent the common code design drives the behavior of the abstract methods. So if the design changes then so "might" the behavior expected from the abstract methods.

  • How to use a static inner class?

    what's the implication of identifier "static" before an inner class.Thank you.

    not sure what implication is, due to my poor vocabulary. But here's an uuh... "example" of a static inner class:
    public class Example {
         static class AnotherClass {
    }There you have class "Example" with the static inner class "AnotherClass." If you wanted to use "AnotherClass" you would do something like:
    public class Whatever {
         Example.AnotherClass ac = new Example.AnotherClass();
    }I don't think I'm mistaken there, but if I am someone please correct me.

Maybe you are looking for

  • Create a basic pay for the employee

    Hi all, while creating a basic pay for an employee, i am giving Payroll area,scale,group then giving 5555- basic pay wage,5556(pf allowance), 5557 (hra allowance) and when i click SAVE, I am getting an error saying "individual wage type 5555  not in

  • How to install a bigger hard drive???

    I've purchased a Seagate Momentus XT hybrid 500gb drive, I can't find a good set of instructions for making this change? Is there a logical way of transferring the data from the original HD to the new drive? Is this something I should have the genius

  • Downloading Error Photoshop CC for Mac - Not permission to write to file

    Hi Guys I've purchased a Adobe Creative Cloud membership and I'm trying to download Photoshop CC for Mac. It keeps telling me: You're not allowed to write to Users/Alex/Library/Application support/Adobe. Please provide write permissions for this fold

  • Data class and Delivery class in ABAP Dictionary

    Hi all, I want to know the exact information about Data class and Delivery class in ABAP Dictionary Moderator message : Search for available information. Thread locked. Edited by: Vinod Kumar on Aug 3, 2011 1:35 PM

  • Previewing imported bitmaps for Illustrator CS4 using Windows XP

    Hi all Can anyone tell me if it is possible to preview a bitmap while importing it into Illustrator CS4 (File>Place). I am using Windows XP SP3 and I know you can see a preview on bitmaps with the Mac version. Any help much appreciated. Thanks George