Brady
Brady

Reputation: 101

Factory class should be singleton or static method?

I made a class which create various instance. It's like a factory. As i know the factory class is singleton or create instance as static method. but my class is spring prototype scope. it has member variable. also there are methods have to call on sequence set member variable after each methods call.

I want to know in this case how does it design. could you recommend better way or good naming?

I’m working on spring framework and java 8..

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class FruiteFactory {

    private String type;
    @Setter
    private Integer field;  // set alfter call appleSupplier

    public FruiteFactory(String type) {
        Assert.notNull(type) ;
        this .type = type ;
    }

    public < T> T create(Class<T > clazz) {
        Object result;
        if (clazz == Apple.class) {
            result = appleSupplier.get();
        } else if (clazz == Banana. class) {
            result = bananaSupplier.get();
        } else {
            throw new IllegalArgumentException();
        }
        return (T ) result;
    }

    private Supplier<Apple> appleSupplier = () -> {
        Apple apple = new Apple();
        // ...
        return apple;
    };

    private Supplier<Banana> bananaSupplier = () -> {
        Banana banana = new Banana();
        banana.setField(field);
        return banana;
    };
}


@Service
public class FruiteService {
    @Autowired ApplicationContext context;

    public void buy(String type) {
        FruiteFactory fruiteFactory = context.getBean(FruiteFactory.class, type);

        Apple apple = fruiteFactory.create(Apple.class);
        // save the apple

        Integer no = apple.getNo();
        fruiteFactory.setField(no);

        Banana banana = fruiteFactory.create(Banana.class);
        // ....

    }
}

Upvotes: 1

Views: 956

Answers (1)

Dici
Dici

Reputation: 25980

If you really need to create fruits from their class name (which I would not advice in the general case), you should just use a Map<Class<?>, Supplier<?>> and then use Class.cast to return the correct type.

Also, it sounds terribly wrong that your factory includes a field only used for creating apples. This field should definitely be enclosed by whatever is the Supplier of apples.

Upvotes: 3

Related Questions