Last active
September 7, 2017 06:21
-
-
Save JeasonWong/acd7f683623a5a4eecb73013654688ab to your computer and use it in GitHub Desktop.
简单工厂模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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