Java Abstract Factory - Singleton

2.3k views Asked by At

I need to create an example to explore Java World and take a one step more ahead.

I want to implement an example of an Abstract Factory. However I want to concrete factories must be served as singletons!

Could you please show me a simple implementation and an example usage?

I have limited knowledge of Abstract Factory Pattern.

Thanks in advance.

1

There are 1 answers

1
wblanks On
public class AbstractFactory {

    private static Foo fooSingleton;
    private static Bar barSingleton;

    private AbstractFactory() {

    }

    public static AbstractFactory getSingletonInstance(string type) {
        if(type == "foo"){

            if (fooSingleton == null) {
                fooSingleton = new Foo();
            }
            return fooSingleton;
        }
        {{add additional cases for other types here}}
    }
}