Tim Tuckle
Tim Tuckle

Reputation: 1354

Java Abstract Factory - Singleton

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.

Upvotes: 1

Views: 2368

Answers (1)

wblanks
wblanks

Reputation: 598

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}}
    }
}

Upvotes: 1

Related Questions