Reputation: 2723
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:
Foo4
someday. Now, what I was able to think of is creating a singleton, FooSingleton
which encapsulate all those classes and load them by:
foo.xml
file.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
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
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
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.
Upvotes: 1