简体   繁体   中英

Understanding effective object creation

J. Bloch wrote the following about object creation:

Conversely, avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight

So, using spring beans being created inside the container may cause some harm if we start creating too much beans declaratively. For instance, I supply the insstance of a Factory object by the declration:

<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();
}

Isn't it a bad idea to declare such factories within the spring beans?

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 eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM