代码如下:
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
class Impl1 implements Service {
private Impl1() {
}
@Override
public void method1() {
System.out.println("Impl1 method1()");
}
@Override
public void method2() {
System.out.println("Impl1 method2()");
}
public static ServiceFactory factory = new ServiceFactory() {
@Override
public Service getService() {
return new Impl1();
}
};
// java8
// public static ServiceFactory factory = () -> new Impl1();
// public static ServiceFactory factory = Impl1::new;
}
class Impl2 implements Service {
private Impl2() {
}
@Override
public void method1() {
System.out.println("Impl2 method1()");
}
@Override
public void method2() {
System.out.println("Impl2 method2()");
}
public static ServiceFactory factory = new ServiceFactory() {
@Override
public Service getService() {
return new Impl2();
}
};
}
public class Factories {
private static void serviceConsumer(ServiceFactory factory) {
Service service = factory.getService();
service.method1();
service.method2();
}
public static void main(String[] args) {
serviceConsumer(Impl1.factory);
serviceConsumer(Impl2.factory);
}
}
运行结果:
Impl1 method1()
Impl1 method2()
Impl2 method1()
Impl2 method2()