Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
简单工厂模式
public class SimpleFactory {
public static void main(String[] args) {
Platform platform = Platform.get();
System.out.println(platform);
}
public static class Platform {
private static final Platform PLATFORM = findPlatform();
public static Platform get() {
return PLATFORM;
}
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
return new Android();
} catch (ClassNotFoundException e) {
}
try {
Class.forName("java.util.Optional");
return new Java();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}
}
public static class Android extends Platform {
@Override
public String toString() {
return "Android";
}
}
public static class Java extends Platform {
@Override
public String toString() {
return "Java";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment