openpojo icon indicating copy to clipboard operation
openpojo copied to clipboard

Can I create multiple instance of RandomFactory

Open kuros opened this issue 9 years ago • 1 comments

I have a requirement where I want to have two difference instance of RandomFactory to exist. For instance having, different factory to create positive/negative integers respectively.

RandomFactory randomFactory = new RandomFactory();
factory.RandomFactory.addRandomGenerator(new RandomGenerator() {
            public Collection<Class<?>> getTypes() {
                return Lists.newArrayList(Integer.class);
            }

            public Object doGenerate(Class<?> aClass) {
                return RandomUtils.nextInt();
            }
        });

RandomFactory randomFactory2 = new RandomFactory();
factory2.addRandomGenerator(new RandomGenerator() {
            public Collection<Class<?>> getTypes() {
                return Lists.newArrayList(Integer.class);
            }

            public Object doGenerate(Class<?> aClass) {
                return -1 * RandomUtils.nextInt();
            }
        });

Assert.assertTrue(factory.getRandomValue(Integer.class) > 0);
Assert.assertTrue(factory2.getRandomValue(Integer.class) < 0);

How Can I achieve this behavior?

kuros avatar Jun 21 '15 14:06 kuros

There has been something similar I've been thinking about - but haven't had time to implement yet which is getRandomValueWithCriteria, allowing you to specify the valid range for an Integer, or the max length on a string, or number of items in a collection, ...etc.

I haven't spent enough time thinking / POCing a solution to provide that, but if there is enough interest in such a feature, a sample implementation could be provided.

Let me know what you think?

And thank you for your continued interest and support of OpenPojo.

oshoukry avatar Aug 14 '15 21:08 oshoukry