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

时间:2016-02-12 22:02:02

标签: java

Let's assume I have a package $sql = $con->query("UPDATE register SET firstname = '$updateFname', lastname = '$updateLname', email='$updatEmail', password='$updatePassword' WHERE id = $user"); with few classes; foo. All of them implements Foo1, Foo2, Foo3 which has one method. Now, I have another class, IFoo which make use of all those classes. Basically Baz need to call the method of every baz class.

Note:

  • They can be reused. Meaning, we only need to create them once.
  • I might want to add IFoo someday.

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

  1. reading a FooSingleton file.
  2. reflection
  3. just write foo.xml, new Foo1(); 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.

3 个答案:

答案 0 :(得分:1)

你可以使用一个依赖注入框架:它允许你为IFoo的实例拥有单例。

您也可以执行类似

的操作
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实施将是单身人士。您也可以将FoolPool设为单身人士。

答案 1 :(得分:1)

使用工厂模式可以解决您的问题。

用FooFactory类替换你的单例,它可以是Bean或静态的。 getFoo(?)方法将包含返回正确对象的逻辑。

编辑:根据你的评论添加了另一条建议。

创建一个侦听器,在实例化时将注册所有IFoo实现。当它出现时,Baz将遍历列表并调用在监听器中注册的每个IFoo的方法。

答案 2 :(得分:1)

  

对于每个run(),它调用每个IFoo类的这个方法

我将enum用于策略类,其中每个策略有一个实例

interface IFoo {
    void doSomething();
}

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

     }
  },
  FOO2 {
     public void doSomething() {

     }
  },
  FOO3 {
     public void doSomething() {

     }
  }

}

在所有实例上调用doSomething

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

以下是我使用过这个的例子。

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