samedi 30 juillet 2016

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);
        // ....

    }
}

Aucun commentaire:

Enregistrer un commentaire