了解有效的对象创建

时间:2015-06-22 10:43:18

标签: java spring

学家Bloch写了关于对象创建的以下内容:

  

相反,通过维护自己的对象来避免对象创建   池是一个坏主意,除非池中的对象是非常的   重量级

因此,如果我们以声明方式开始创建过多的bean,那么使用在容器内创建的spring bean可能会造成一些伤害。例如,我通过declration提供Factory对象的句子:

<bean id="userFactory" class="com.foo.factory.UserFactory">
    <property name="creatorMap">
        <!-- map's declaration -->
    </property>
</bean>

public class UserFactory{
     Map<UserType, Creator> creators;

     public User create(UserType t){

         return creators.get(t).create();
     }
}

public enum UserType{
    VIP,
    GUEST,
    ACTIVE,
    //etc
}

public interface Creator{
    public User create();
}

在春豆中宣布这样的工厂不是一个坏主意吗?

1 个答案:

答案 0 :(得分:2)

I think the context of Joshua's suggestion is expensive to create objects - extremely heavyweights. You create object pools to reuse and avoid expensive creation for e.g., things like connection pool etc. The framework you are referring to (Spring) itself uses lots of such Factories inside it's infrastructure code. So in my opinion it should boil down to whether you require such factories in your application. Each application thread using such factory would create it's own contextual object and the number would depend upon such requests to the factory bean.