/**
* Author: Tom
* Date: 25/06/2015
* Time: 22:12
*/
public class FactoryExample {
public static abstract class SomeAbstractClass {}
public static class SomeAbstractClassImplA extends SomeAbstractClass {}
public static class SomeAbstractClassImplB extends SomeAbstractClass {}
public static class SomeAbstractClassImplC extends SomeAbstractClass {}
public enum SomeAbstractClassFactory {
IMPL_A() {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplA();
}
},
IMPL_B {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplB();
}
},
IMPL_C() {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplC();
}
};
public abstract SomeAbstractClass create();
}
public enum SomeAbstractClassSingletonFactory {
IMPL_A() {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplA();
}
},
IMPL_B {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplB();
}
},
IMPL_C() {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplC();
}
};
private final SomeAbstractClass implementation;
SomeAbstractClassSingletonFactory() {
implementation = create();
}
public SomeAbstractClass getImpl() {
return implementation;
}
protected abstract SomeAbstractClass create();
}
public enum SomeAbstractClassLazySingletonFactory {
IMPL_A() {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplA();
}
},
IMPL_B {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplB();
}
},
IMPL_C() {
@Override
public SomeAbstractClass create() {
return new SomeAbstractClassImplC();
}
};
private SomeAbstractClass implementation;
public SomeAbstractClass getImpl() {
if (implementation == null) {
synchronized (this) {
if (implementation == null) {
implementation = create();
}
}
}
return implementation;
}
protected abstract SomeAbstractClass create();
}
}