Abstract Singleton

Hi, I have the following problem.
I have an ObjectManagerFactory, that is used to get an instance of an ObjectManager. Which implementation of an ObjectManager is returned is decided by the factory. So I have an interface specifying the common methods of the ObjectManagers:
public interface IObjectManager{
  public ArrayList getAll();
  public Object getOne(int id);
  public store(Object o);
  public update(Object o);
}All classes only work on the interface and do not know which implementation they actually use.
Now to get an ObjectManager the ObjectManagerFactory is called:
public class ObjectManagerFactory{
  public IObjectManager getObjectManager(){
     // code to decide which implementation to use
    return new PgsqlObjectManager();
}That would be fine. But since some implementations have to be Singleton, I wanted to force all Implementations to be a Singleton. That would change the Factory-Method getObjectManager() to:
  public IObjectManager getObjectManager(){
     // code to decide which implementation to use
    return PgsqlObjectManager.getInstance();
  }This however required that there is a getInstance method. To enforce all implementations to be a Singleton I need to define this in the Interface. Since getInstance() had to be static I would use an abstract class instead of an interface. But that leads to another problem. A typical Implementation of getInstance() is this:
public static synchronized AbstractObjectManager getInstance(){
  if (instance == null){
    instance= new AbstractObjectManager();
  return instance;
}The problem is "instance= new AbstractObjectManager();" Since AbstractObjectManager is an abstract class, I cannot call its constructor.
So how can I force all Implementations to be a Singleton? Any ideas?

The service locator pattern seems to be a bit of a overkill for my problem. It is not a J2EE application, so I want to avoid too much overhead, when it is not needed. But what I want to do is very similar to the pattern.
So the question that remains is, do I have to enforce all ObjectManagers to be Singleton. The reason I wanted to do this is consistency. My first idea was to not enforce this. I only wanted one singe way to get an instance of an ObjectManager. Whether this instance is a Singleton instance or not would be no difference to me. So the actual implementation of getInstance() is not provided. That would of cource lead to the problem that one may assume a call to getInstance() would always return a singleton. So I have decided against this. But still want a single way to instantiate such an ObjectManager. This way I configure which ObjectManager declaratively. I only would have to know the name of the class and can use Class.ByName() and call one specific method on it. If some Implementations are singleton and some are not, that wouldn't work, since I had to call getInstance() for the Singleton ones and the constructor for the others. Of course that could also be declared in the configuration, but seems a bit odd.
Or I would mimic the Service Locator Pattern a bit more and each Implementation of an ObjectManager would have to provide a factory. This factory would then return an instance and is responsible for this.
And, I am not sure about it, but maybe it really makes a difference to the "user" of the ObjectManager. When using such an ObjectManager it may be necessary to know whether two instances of them are always the same or different objects. (I know that would be possible with getInstance(), but this shouldn't be necessary for the client).
I hope I made clear what I mean.

Similar Messages

  • Abstract Singleton Class?

    hi all
    i have an abstract class and i want to extend it such that it becomes a singleton. However i wish i can also gain the benefits of abstraction so that i can reference the abstract class whatever the concrete class that extends it
    so how can i write the "getInstance()" method in both the abstract and concrete classes knowing that i can't create an abstract static method?!
    thanks in advance

    this has nothing to do with my question
    my question is:
    if you have class A abstract and class B inherits from class A
    then i want to make class A a singleton with a single underlaying instance of class B
    such that when i call A.getInstance() it first checks if the instance it has is null it creates a new object from class B and use it as an instance but ofcourse it has to be general to all several subclasses to be used according to each case.

  • Enforce static Singleton from Abstract/Interface??

    Hi,
    I'm trying to describe an interface IMyInterface which enforces all concrete subclass implementations to have a singleton "getInstance()" method whose method signature is always this "getInstance".
    So declaring the interface
    Interface IMyInterface{
    public IMyInterface getInstance();
    is fine, BUT in subclasses you can't override this method with a static class method.
    ie.
    public class X implements IMyInterface
    private static X instance=null;
    public static X getInstance()//ERR cannot override with static??
    if( instance==null)
    instance = new X()
    return instance;
    private X(){...}
    I thought about using an abstract superclass but this doesn't strictly enforce subclasses to implement their own singleton class-method.
    Why can't you override the method as a class-method?...and any ideas how to achieve this enforcement of the implementation of a singleton??

    If you have an abstract base class with the method
    public static Singleton getSingleton()  {
           return getSingletonImpl();
    }where getSingletonImpl is an abstract method
    protected abstract Singleton getSingletonImpl() ;This forces subclasses to provide an implmentation of the getSingletonImpl method.
    However you cannot guarentee that the returned Singleton is actually a singleton
    matfud

  • A Singleton variable in an Abstract Class

    Hello there people
    I have a quick question. I have made an abstract class in which I want to put an identifier (ID) int to be incremented whenever I make any of the concrete class instances that extend this abstract class.
    whould that declairation be as follows?:
    public static int IDAdditionally, I have a quick question about abstract constructors. If constructors are defined in the concrete classes, are their declairations needed in the abstract class?
    and finally, if I wanted to use the int ID (as mentioned above) then would I have to use constructor from the abstract class?
    thanks in advance for the help

    I think the OP would want a constructor in the abstract class to update that variable. Otherwise, he'd have to remember to update it in the constructor for all concrete classes. But, you don't declare constructors for the concrete class in the abstract class. You only declare constructors for the abstract class in the abstract class.

  • A question about Abstract Classes

    Hello
    Can someone please help me with the following question.
    Going through Brian's tutorials he defines in one of his exercises an  'abstract' class as follows
    <ClassType ID="MyMP.MyComputerRoleBase" Base="Windows!Microsoft.Windows.ComputerRole" Accessibility="Internal" Abstract="true" Hosted="true" Singleton="false">
    Now I am new to authoring but get the general concepts, and on the surface of it, it appears odd to have an 'abstract' class that is also 'hosted' I understand and abstract class to be a template with one or more properties defined which is then used
    as the base class for one or more concrete classes. Therefore you do not have to keep defining the properties on these concrete classes over and over as they inherit the properties from their parent abstract class, is this correct so far?
    if the above is correct then it seems odd that the abstract class would be hosted, unless (and this is the only way it makes sense to me) that ultimately (apart from singleton classes) any class that is going to end up being discovered and
    thereby an instance of said class instigated in the database must ultimately be hosted somewhere, is that correct?
    in other words if you has an abstract class, which acts as the base class for one or more concrete classes (by which I mean ones for which you are going to create lets say WMI discoveries ), if this parent abstract class is not ultimately
    hosted to a concrete class of its own then these child concrete classes (once discovered) will never actually create instances in the database.
    Is that how it is?
    Any advise most welcome, thanks
    AAnotherUser__
    AAnotherUser__

    Hi,
    Hosting is the only relationship type that doesn't require you to discover it with a discovery rule. OpsMgr will create a relationship instance automatically for you using a 'hosted' properties 'chain' in a class\model definition. In an abstract class definition
    you need to have this property set to 'true' or you will 'brake' a hosting 'chain'.
    http://OpsMgr.ru/

  • Event ID 10801 - Abstract class ID not allowed in a discovery data item.

    Hi All,
    I am getting very frequent event id 10801 on my RMSE -  
    Discovery data couldn't be inserted to the database. This could have happened because  of one of the following reasons:
    - Discovery data is stale. The discovery data is generated by an MP recently deleted.
    - Database connectivity problems or database running out of space.
    - Discovery data received is not valid.
    The following details should help to further diagnose:
    DiscoveryId: a8cc450e-fdfa-9ff0-e46f-0b8a3f58a57b
    HealthServiceId: 4e1815a1-6704-e686-f490-15d7d46773d2
    Microsoft.EnterpriseManagement.Common.DiscoveryDataAbstractClassIdNotAllowedException,Abstract class ID not allowed in a discovery data item.
    Class ID: e2ea0f3e-a2ac-41d8-9ba2-7c0b524a121e
    Rule ID: a8cc450e-fdfa-9ff0-e46f-0b8a3f58a57b
    Instance:
    <?xml version="1.0" encoding="utf-16"?><ClassInstance TypeId="{e2ea0f3e-a2ac-41d8-9ba2-7c0b524a121e}"><Settings><Setting><Name>5c324096-d928-76db-e9e7-e629dcc261b1</Name><Value>ABCD.domain.domain</Value></Setting><Setting><Name>af13c36e-9197-95f7-393c-84aa6638fec9</Name><Value>11</Value></Setting></Settings></ClassInstance>.
    When I check the Discovery ID it gives me the below discovery.
    PS C:\> [guid]$g = "a8cc450e-fdfa-9ff0-e46f-0b8a3f58a57b"
    PS C:\> Get-SCOMDiscovery | where {$_.Id -eq $g}
    HasNonCategoryOverride          : False
    Enabled                         : onEssentialMonitoring
    Target                          : ManagementPackElementUniqueIdentifier=3c998a33-cbc3-a258-b728-a67982377058
    ConfirmDelivery                 : False
    Remotable                       : True
    Priority                        : Normal
    Category                        : Discovery
    DataSource                      : DiscoveryDataSource
    DiscoveryClassCollection        : {}
    DiscoveryRelationshipCollection : {ManagementPackElementUniqueIdentifier=08d64c2a-2ba5-cafa-54ad-bfe91e2a39b3}
    XmlTag                          : Discovery
    ManagementGroup                 : SCOMPRODUCTION
    ManagementGroupId               : 1a77df0b-1a31-721c-be9d-aebe3f85db8c
    Identifier                      : 1|Microsoft.Windows.HyperV.2012.Discovery/31bf3856ad364e35|1.0.0.0|Microsoft.Windows.
                                      HyperV.2012.VirtualNetworkContainsNetworkAdapterDiscovery||
    Name                            : Microsoft.Windows.HyperV.2012.VirtualNetworkContainsNetworkAdapterDiscovery
    Id                              : a8cc450e-fdfa-9ff0-e46f-0b8a3f58a57b
    DisplayName                     : Hyper-V 2012 Virtual Network Relationship Discovery
    Description                     : Discovers Microsoft Windows Hyper-V 2012 Virtual Network contains Network Adapter
                                      relationship
    LanguageCode                    : ENU
    Comment                         :
    Status                          : Unchanged
    LastModified                    : 12/11/2014 12:18:01 AM
    TimeAdded                       : 12/11/2014 12:18:01 AM
    InstanceName                    :
    PS C:\>
    I am getting this event for multiple agents now. I checked the discovery highlighted "Hyper-V 2012 Virtual Network Relationship Discovery" but did not get anything.
    Can anybody help me in resolving this.
    Thanks, S K Agrawal

    Microsoft.Windows.HyperV.2012.VirtualNetworkContainsNetworkAdapterDiscoveryDataSourceModule Code (Code executed for your discovery Hyper-V 2012 Virtual Network Relationship Discovery)
    Set oNIC = oDiscoveryData.CreateClassInstance("$MPElement[Name='WSLib!Microsoft.Windows.Server.NetworkAdapter']$")
          Call oNIC.AddProperty("$MPElement[Name='Windows!Microsoft.Windows.LogicalDevice']/DeviceID$", nicId)
          Call oNIC.AddProperty("$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", ComputerIdentity)
    This class (Microsoft.Windows.Server.NetworkAdapter) is defined as abstract class in “Microsoft.Windows.Server.Library.mp”
    <ClassType ID="Microsoft.Windows.Server.NetworkAdapter"
    Abstract="true" Accessibility="Public" Base="Windows!Microsoft.Windows.NetworkAdapter" Hosted="true" Singleton="false">
    This was filed as a Bug with Microsoft.
    Thanks, S K Agrawal

  • Create client classes in Abstract Factory

    Hi!
    Let's we have one of the next classes in AbstractDesign patterns:
    1.WindowFactory - abstract factory
    2.MotifWindowFactory, MacWindowFactory - concrete factory
    3.Window - abstract product
    4.MotifWindow, MacWindow - concrete products
    5.Client - client class
    6.ClientCreator - class that creates our client class
    The source code of Client is like this:
    public class Client {
    private AbstractFactory af = null;
    public Client(AbstractFactory af) {
    this.af = af;
    af.createAbstractProduct();
    The code of ClientCreator will be like this:
    public class ClientCreator {
    Client client = new Client(new MotifWindowFactory());
    OK!
    But we can have many client classes. And this client classes can create from different places (many ClientCreator classes) in our project.In our project we have:
    public class ClientCreator1 {
    Client client1 = new Client(new MotifWindowFactory());
    public class ClientCreator2 {
    Client client2 = new Client(new MotifWindowFactory());
    public class ClientCreatorN {
    Client clientN = new Client(new MotifWindowFactory());
    And what will happen when I need to change concrete factory. I must go to EVERY ClientCreator classe and change code to create client classes with another concrete factory:
    public class ClientCreator1 {
    Client client1 = new Client(new MacWindowFactory());
    public class ClientCreator2 {
    Client client2 = new Client(new MacWindowFactory());
    public class ClientCreatorN {
    Client clientN = new Client(new MacWindowFactory());
    I think that this is not flexibility.
    Can any tell me what I wrong understand in AbstractFactory pattern?
    Thanks.

    The code
    Client client1 = new Client(new MacWindowFactory());
    Client clientN = new Client(new MacWindowFactory());results in the creation of a factory for each client. This is unnecessary. Typically, you'd use a singleton here - this is mentioned in GoF 1995:
    Client client1 = new Client(MacWindowFactory.getInstance());
    Client clientN = new Client(MacWindowFactory.getInstance());This means that only one factory is created (assuming a singleton implementation within MacWindowFactory.getInstance).
    This approach ties each client creation to a given factory type. If you want all clients to use the same factory type, then you would change the code to:
    Client client1 = new Client(WindowFactory.getInstance());
    Client clientN = new Client(WindowFactory.getInstance());where WindowFactory would return the appropriate factory type. Now if WindowFactory is an interface, then you create a "Factory Factory", or "Factory Manager". i.e.
    Client client1 = new Client(WindowFactoryManager.getFactoryInstance());
    Client clientN = new Client(WindowFactoryManager.getFactoryInstance());The implemenetation of getFactoryInstance can work any of many ways. If you've only one concrete WindowFactory for now, then hard code it into getFactoryInstance. If you have many, then you could have a setFactoryInstance method on WindowFactoryManager. Or getFactoryInstance could use reflection to create a factory based on a Property, etc.

  • Question  about Abstract,Final Class

    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private. From usability perspective both are same ? or is there any difference?
    Secondly accounting to java syntax a class can be either final or abstract and not both .Then why language specification doesn't impose any restriction on making abstract classes constructor private. We can create an Abstract class with private Constructor (Basically utility class with all methods are static) ,to make this class Singleton .This situation is equal to abstract final class ?
    Thanks,
    Paul.

    EJP wrote:
    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private.No it doesn't.
    Secondly accounting to java syntax a class can be either final or abstract and not both.Correct.
    Then why language specification doesn't impose any restriction on making abstract classes constructor private.Why should it? That proposition doesn't follow from your previous sentence.I think OP is asking about this case
    public abstract class WTF {
      private WTF() {}
      private WTF(...) {}
    }where the class is abstract and all the c'tors are final. It's an abstract class that cannot be extended, much like a final abstract class would be if it were allowed. So, since purpose of abstract classes is to be extended, the OP seems to be asking, "Why can we, in this fashion, create an abstract class that cannot be extended?"
    I don't know the answer to that, but I would guess that, while final is an explicit syntactical element for the purpose of making a class non-extensible, in the all-private-c'tors case, the non-extensibility is simply a side effect, and probably enough of a corner case that it wasn't worth the effort to explicitly forbid it in the spec.
    I also think it's something not worth thinking much about. It was certainly not a key point of some grand design.

  • ThreadLocals With Singletons

    We are using a 3rd party product here. This product runs in its own JVM. We can customize it by subclassing some of their classes. But their architecture will only create one instance of our subclasses. This instance is reused for multiple requests.
    My subclass is pretty complicated and is just an abstract class for numerous other subclasses. I need to make my class thread safe. My first inclination is to use a ThreadLocal class variable to hold the state for each instance of my class.
    I've never used ThreadLocal before, so I wrote a little test. As I haven't used Java Threads in years, I am having trouble getting this sample code to work.
    The sample essentially starts 2 threads. The 1st thread is supposed to wait 4 seconds so the 2nd thread can start running and I can test 2 threads in the same instance to make sure I get two separate serial numbers.
    The problem is, for some reason the 1st thread runs t o completion before the 2nd thread starts. I don't know why. I'm sure I'm an idiot and the solution is very simple. But I can't figure it out and would appreciate any help.
    Thanks.
    Here is the thread creator/driver:
    public class ThreadMgr
        public void runIt()
            ThreadTest t1 = ThreadTest.getInstance();
            ThreadTest t2 = ThreadTest.getInstance();
            System.out.println("t1 == t2: " + (t1 == t2));
            System.out.println("Start A");
            Thread threadA = new Thread(t1);
            threadA.setName("ThreadA");
            threadA.run();
            System.out.println("A has been started");
            System.out.println("Start B");
            Thread threadB = new Thread(t2);
            threadB.setName("ThreadB");
            threadB.run();
            System.out.println("B has been started");
        public static void main(String[] args)
            new ThreadMgr().runIt();
        }Here is the singleton which I need to ensure is threadsafe:
    public class ThreadTest implements Runnable
        private ThreadLocal serialNumber = null;
        private static ThreadTest threadTest = null;
        public static ThreadTest getInstance()
            if (threadTest == null)
                threadTest = new ThreadTest();
            return threadTest;
        private ThreadTest()
        public void run()
            System.out.println("In ThreadTest");
            serialNumber = new ThreadLocal();
            Double randomNbr = new Double(Math.random());
            serialNumber.set(randomNbr); //Just for testing
            try
                Thread.sleep(4000);  //Sleep 4 seconds to allow the other thread to enter
            catch (InterruptedException e)
                e.printStackTrace();
            System.out.println("Serial # for thread " + Thread.currentThread().getName() + " = " + serialNumber.get());
    }

    Or (I didn't think of Your driver, at first...):        System.out.println("Start A");
            Thread threadA = new Thread(t1);
            threadA.setName("ThreadA");
            threadA.start();                     // Use the "start"-method.
            System.out.println("A has been started");
            System.out.println("Start B");
            Thread threadB = new Thread(t2);
            threadB.setName("ThreadB");
            threadB.start();                     // Use the "start"-method.
            System.out.println("B has been started");

  • Singleton or static methods for DAO?

    Which is the preferred way of creating a DAO which has no state...Singleton or static methods for DAO? and why? What are the issues implement one over the other?

    A [url http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html]DAO is an object that abstracts different data source access mechanisms by providing a common interface, decoupling the client code from the data layer implementation, and allowing differrent data sources to be used without changing the client code.
    This is not possible with static methods- you would have to change the client code to use a different data source.
    There is a similar pattern, the facade, where an object/utility class provides the interface to a set of functionality. In the case of a facade with static methods, the facade class needs to be rewritten to use a different implementation. This is possible, but means only one implementation may exist in each version of the software. A static method facade is a tighter coupled solution to a similar problem; tight coupling occasionally makes a measurable improvement in performance, but always reduces flexibility and requires destructive editing to change its implementation.
    Pete

  • Using a Singleton Mediator to provide loose coupling

    I need to discuss the pros and cons of using a singleton mediator to provide loose coupling between component implementation classes.
    Suppose you are building a SE or a BC where an endpoint is defined upon a SU deployment. In this scenario, you will end up finding out that the Component, ComponentLifeCycle and ServiceUnitManager implementations should know each others instances. I can figure out these solutions:
    -     Use tight coupling
    -     The component implements the three interfaces (or two of them and associates the third)
    -     Use a singleton mediator to hold the instances
    -     Use a third party solution, like Spring's ApplicationContext and ApplicationContextAware contracts
    -     Some other solution I didn't think of (the scenario has to be more specific)
    Assuming the scenario as described above, I prefer the third solution.
    I appreciate your opinions.
    Hossam Karim

    When you evaluate the JBI implementations available, you will notice that each one has built a less abstraction layer over the JBI component contracts in order to simplify its subsequent tasks. As a component builder, you would either reuse one of these layers and get tight with a specific implementation, or start writing your own.
    I recently proposed a simple framework to my team; you can find a class diagram here (http://www.gaiati.com/products/emee/framework.png), it has the following elements:
    �     AbstractBootstrapAdapter: Simple adapter for the Bootstrap interface
    �     ComponentApplicationContext: Provides a Spring based Application context for this component, the context beans should be loaded upon component initialization. An instance of this class will be available to all classes or interfaces that extend the ApplicationContextAware Spring interface. All classes and interfaces on the previous diagram that associate a ComponentApplicationContext instance (applicationContext) implement the ApplicationContextAware interface. One exception is the AbstractComponentAdapter class, because it actually creates the instance.
    �     AbstractComponentAdapter: Adapter for the component and lifecycle contracts. Upon initialization, this class creates a ComponentApplicationContext instance, and uses the beans to configure itself, the class recognizes other framework contracts and able to communicate with them.
    �     AbstractMessageListener: Consumes this component's DeliveryChannel message exchanges, and fires a handling trigger.
    �     DeployedEndpoint: Represents an endpoint that was deployed using a SU
    �     DeployedEndpointConfiguration: Holds the configuration needed by a DeployedEndpoint instance
    �     DeployedEndpointTarget: Represents the target JBI specific address that a DeployedEndpoint instance should route the messages to.
    �     GenericMessageListener: Handles the trigger fired by the AbstractMessageListener, delegating the work to an instance of the DeployedEndpoint interface
    �     GenericServiceUnitManager: Handles GenericServiceUnit instances
    �     GenericServiceUnit: Acts as a proxy and encapsulates a DeployedEndpoint instance
    �     AbstractDeployedEndpointFactory: An abstract factory for creating DeployedEndpoint instances using DeployedEndpointConfiguration instances
    Yes, I ended up using Spring, and you are right, it might not be appropriate to attempt to separate the interfaces, may be I misunderstood or was mislead by Open-ESB implementation of the SOAP and file binding components.
    It is true sometimes you can have "personal taste", but most important is to achieve best practice.
    Finally, I hope the specification in its next versions, would provide us with a best practice framework or proposal, instead of so much choices.
    Hossam Karim

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

  • Forcing singleton on inharitance

    I am trying to create an inheritance structure, so that each inheritor implementation would be forced to be a singleton. so:
    public interface Singleton{
        ...method definitions...
    public abstract class AbsSingleton implements Singleton{
       ..common method implementation...
    public class SingletonImpl extends AbsSingleton{
       private static SingletonImpl me = null;
       public static SingletonImpl instance{
            if (me == null){
                 me = new SingletonImpl();
            return me;
       private SingletonImpl(){}I thought initially to create the instance method in the abstract and use reflection to instantiate the implementer, but that need the implementers' constructor to be public, which looses the point of forcing. is there a way I can enforce that?
    thank you,
    Ehud
    Edited by: Kaldor on Jul 2, 2009 12:08 AM

    Hi Tom,
    Try: butt.doclick();
    JButton butt=new JButton();
    butt.doClick();
    BR
    Mohit

  • Abstraction problem

    I'm trying to develop a CommandFactory that can, given a known set of parameters, instantiate one Command in a dynamic set of Commands.
    class CommandFactory
      Hashtable commandKeys;
      private static CommandFactory instance = null;
      private CommandFactory()
        //code that initializes and populates commandKeys
      public static CommandFactory getInstance()
        if( instance == null ) instance = new CommandFactory();
      public Command parse( String cmd )
        String key = cmd.substring(0,cmd.indexOf(" "));
        String cmd_parms = cmd.substring( cmd.indexOf(" ")+1 );
        Method m = (Method)commandKeys.get(key);
        return (Command) m.invoke( null, new Object[] { cmd_parms } );
    public abstract class Command
      public abstract execute();
    }Now, I'd like to be able to know at compile time that every sub-class of Command has a static method defined such as:
    //adding to my above Command a bit
    abstract class Command
      public abstract void execute();
      public abstract static Command parse( String cmd );
    class CommandSubclass
      public void execute()
        //do something
      public static Command parse( String cmd )
        //does something
       return newCommand;
    }The closest thing I can think of to naming what I want here is an abstract static method. That way at compile-time I know with certainty that the Command subclasses have the proper tidbits to initialize and give me back a Command.
    Now, I know that Java does not support abstract static methods. And what I've done instead is just assume that my various Command classes have the "parse" static method. But I run the risk of not knowing until run-time that a Command subclass does not have the needed static method.
    Essentially, I need a means to enforce a uniform way of initializing subclasses of an abstract superclass. Anyone know how to get that other than reflection, hoping, and praying? Or, is there a different pattern I should be using here?
    Thanks,
    --mb

    It removes the ability of the Factory to say what it should/should not have. No, an interface places no such restriction. What you have is three different problems:
    1/how to delegate the instantiation of command objects to command specific mappings.
    2/how to load the mappings of command names to the instantiation mechanism at runtime
    and now you have
    3/ the factory to have a say in what mappings it will support.
    1/ is handled perfectly well using interfaces and registry/delegate factory objects; it's convienent to implement these factories as command prototypes, but not necessary, hence there are separate factory and command interfaces.
    2/ would be handled by loading the mappings from some data source together with an expression for instantiting the factory instances, together with a controlling registry factory that delegates to the specific factories. One mechanism for this is java.beans.XMLEncoder, or you can hand craft your own restricted version using Class.forName().newInstance. In the above example I didn't do this for you, and created the registry as part of initialising the application.
    3/ you've just introduced and you haven't specified what more control you want inside the factory-registery that 1 + 2 don't give you.
    I already have the mechanism of telling the Factory what factories it should use to build it's look-up table.So use that mechanism to populate the registry, instead of the test code above.
    I suppose an alternative is to have the Factory act as a kind of security manager. This seems to be extra to the previous requirements; what do you want it to do as well as being a factory?
    As CommandFactory subclasses are loaded, they create an instance of them, and attempt to register with the top-level CommandFactory to build a look-up or chain of responsibility -- just like your static block. Yes. Though typically I'd use a more flexible mechanism, so that you can load the class without it registering. The static block above in is the class that sets up the application, not the class that implements CommandFactory. If you put the registration code there, then you are forced to have a singleton registry and it becomes tightly bound to one use pattern, and hard to maintain.
    Also, when the CommandFactory is instantiated, it can forName all the classes it knows it's looking for to ensure they are loaded.They will be loaded when you create an instance to register. You don't need to do any extra calls to forName. You can use the forName to implement the creation of an instance to register, or you can use the more flexible mechanism built into XmlEncoder. Don't rely on subclasses implementing a particualar registration mechanism, but separate that to a different place. So the only thing that a correct implementation of CommandFactory does is implement a method that creates a command. That way, everything is part of the contract.
    ...but isn't it bad coding practice to initialize in static code blocks?No. They exist exactly for the purpose of initialising static state; you just have to ensure you don't throw any exceptions and are aware of load-order dependencies. They're also useful for throwaway stuff like the example above, where you want to set up global state for tests rather than writing a full application. But don't use them to do things which are not required to load the class- there's a very big difference between flow of control in the code above and:class EchoCommand extends PrototypeCommand {
      public void execute () {
        System.out.println(args);
      static {
        MB10Command.register.register("echo", new EchoCommand());
    class SortCommand extends PrototypeCommand {
      public void execute () {
        List sort = new ArrayList(args);
        Collections.sort(sort);
        System.out.println(sort);
      static {
        MB10Command.register.register("sort", new SortCommand());
    public class MB10Command {
      static CommandRegister register = new CommandRegister();
      static {
        new EchoCommand();
        new SortCommand();
      public static void main (String[] args) {
        register.parse(args).execute();
    }Because EchoCommand is tied to one particular global registry, it's unusable in any other context, and you end up thinking about adding extra code to overcome the hard coded global variable (otherwise known as singleton anti-pattern).
    You also lose the expression of intent- in the previous code, when you load the main class, you explicitly create a registry, then register a couple of prototypes with it. If you start using static blocks so that a side-effect of loading a class is that it registers a prototype with a third party, and then use Class.forName so that registration is a side-effect of a side-effect, you will get very confused very rapidly. Keep both implementation and state as local as possible.
    Pete

  • In bpm(abstract message used in container)

    hi expects,
    for what purpose we are using abstract message in container).

    Hey Rohit,
    To give an exact picture of  the use of container variables you can refer them as direction less interfaces.
    When we Create Message Interfaces We define <b>Category</b> (Inbound, Outbound, Abstract) , <b>Mode</b> (Synchronous , Assynchronous).
    <b>Inbound</b> refers to Incoming message to the XI server.
    <b>Outbound</b> refers to Outgoing Message from XI server
    <b>Abstract:</b>
    When the concept of integration process comes into picture it has to refer to interfaces defined in its own s/w component version. It can only refer to Abstract interfaces as they are direction less and when used in integration process they are assigned direction dynamically. EX: if you have a defined a container variable XYZ  which refers to some abstract interface ABC and call this XYZ container variable in in receieve step of the int pro then it can as inbound.
    For further clarification please refer <a href="http://help.sap.com/saphelp_nw04/helpdata/en/78/62373f58502e48e10000000a114084/content.htm">Defining Data Process  in Containers</a>
    Hope itz clear.
    Cheers,
    *Raj*
    *Reward Point If Found  Usefull*

Maybe you are looking for

  • Error Message when running BI Publisher

    Hi- Getting the following error message when running a custom report, report has been defined but still getting the error message in HCM 9.2 with PeopleTools 8.53 Template definition MAC_CONF_STM not found in the report definition. (235,2012) PSXP_RP

  • Using CLOB in 8.1.7

    Hi, Well, everything here seems simple with the use of CLOB. But unfortunately, it springs up a surprise,to me atleast, when compiled. l_clob clob := '<?xml version = "1.0"?>      <ROWSET>      <ROW num="1">      <EMPNO>7369</EMPNO>      <ENAME>SEAND

  • Business Objects Excel Analyser

    Hi, We are currently using BEx reporting tols on top of SAP BI and considering replacing BEx Tools with that of BO Tools. Can you help me with list of available BO Reporting Tools and advantages of them compared to BEx tools. and Provide more info on

  • Printing blank spaces using dbms_output.put_line

    There is one string getting generated dynamically. Upon generation, it may or may not contain blank spaces in the beginning. Then I am trying to print this on standard I/O using DBMS_OUTPUT.PUT_LINE. But if there are some leading spaces in the string

  • Transport Movement for BI Content Installation

    Hi All, We are working on BW 3.5 version. Yesterday I have Installed BI Content Infosource 2LIS_12_VCITM for a previously Inactive DataSourcre 2LIS_12_VCITM.  I followed below steps: 1. Activated 2LIS_12_VCITM in RSA5 2. Activation and Maintenance in