Elimination
Elimination

Reputation: 2723

What is the right Java-way to create objects dynamically?

Let's assume I have a package foo with few classes; Foo1, Foo2, Foo3. All of them implements IFoo which has one method. Now, I have another class, Baz which make use of all those classes. Basically baz need to call the method of every IFoo class.

Note:

Now, what I was able to think of is creating a singleton, FooSingleton which encapsulate all those classes and load them by:

  1. reading a foo.xml file.
  2. reflection
  3. just write new Foo1();, new Foo2(); etc, inside the init function of the singleton.

So I wanted to know what's the preferable way (Maybe there's another neat way I haven't think of)

By the way, I've encountered with Spring Dependency Injection but that looked to me a little bit of an overhead.

Upvotes: 1

Views: 96

Answers (3)

Master Mind
Master Mind

Reputation: 3084

You can use one the dependency injection frameworks: it will permit to you to have singletons for the instance of IFoo.

You can also do something like

FooPool {

    private List<IFoo> foos;

    FooPool () {
        foos.add(Foo1.getInstance());
        foos.add(Foo2.getInstance());
        foos.add(Foo3.getInstance());
    }

    public List<IFoo> getFoos() {
        return foos
    }
}

IFoo Implementation would be singletons. You can make FoolPool also as a singleton.

Upvotes: 1

Paulo Pedroso
Paulo Pedroso

Reputation: 3685

Your problem can be solved applying the Factory pattern.

Replace your singleton by a FooFactory class that can either be a Bean or static. The method getFoo(?) will contain the logic to return the right object.


EDIT: added another suggestion according to your comment.

Create a listener where all IFoo implementations will be registered upon instantiation. When it's time, Baz will run through the list and call the method of every IFoo registered in the listener.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

for every run() it calls this method of every IFoo class

I use enum for strategy classes, where there is one instance per strategy

interface IFoo {
    void doSomething();
}

enum Foos implements IFoo {
  FOO1 {
     public void doSomething() {

     }
  },
  FOO2 {
     public void doSomething() {

     }
  },
  FOO3 {
     public void doSomething() {

     }
  }

}

To call doSomething on all instances

for (IFoo foo : Foos.values()) {
   foo.doSomething();
}

Here is an example where I have used this.

https://github.com/OpenHFT/Chronicle-Wire/blob/master/src/main/java/net/openhft/chronicle/wire/WireType.java

Upvotes: 1

Related Questions