📄 strapfontfactory.java
字号:
import java.awt.*;class StrapFont { // Functions to return fonts reliably static int countdownToDoom = 0; public static void simulateMemoryFailureNext( int n ) { // Simulates memory allocation failure for all allocs starting with the // n-th allocation // after now (n=1 for first). Resets previous calls to this func. // n==0 resets to normal countdownToDoom = n; } static Font myDefaultFont = new Font("Dialog",Font.PLAIN,12); public static Font defaultFont() { // Returns the default font object. return myDefaultFont; } public static Font font( String fontDescription ) { Font f; try { f = privateGetFont(fontDescription); } catch (BadFontException e) { return defaultFont(); } catch (OutOfMemoryError e) { return defaultFont(); } return f; }; protected static Font privateGetFont(String fontDescription ) // Returns a font. throws BadFontException { if ("BadFont".equals(fontDescription)) { throw new BadFontException(); } if (countdownToDoom > 0) { if (countdownToDoom == 1) throw new OutOfMemoryError(); countdownToDoom--; }; return new Font(fontDescription,Font.PLAIN,12); }};class BadFontException extends Exception { };class PartialFailureTest { // Test class for StrapFont: private static final String GoodFontDescription = "Dialog"; public static void assert( boolean b, String reason ) { if (!b) { System.out.println("Assertion failed: " + reason ); try {System.in.read();} catch (Exception e) {}; System.exit(1); } } public static void main( String[] args ) { // StrapFont factory = new StrapFont(); // Tests: try { // Get a font normally. Font newFont = StrapFont.font( GoodFontDescription ); System.out.print("."); assert( newFont != null, "Courier font null" ); assert( newFont != StrapFont.defaultFont(), "Courier font same as system" ); assert( newFont.getName().equals(GoodFontDescription), "wrong font name!" ); // TODO Check semantics of Font class ...! // Kill this instance (Some implementations might use weak collections // to cache it): newFont = null; System.gc(); System.out.print("."); // Get a font that doesn't exist newFont = StrapFont.font( "BadFont" ); assert( newFont != null, "Bad font returns null" ); assert( newFont.equals(StrapFont.defaultFont()), "Bad font not same as system" ); System.out.print("."); // Get a font with memory failure StrapFont.simulateMemoryFailureNext(20); for (int i=1; i < 25; i++) { System.out.print("."); assert( i < 25, "Mem failure testing problem" ); newFont = StrapFont.font( GoodFontDescription ); assert( newFont != null, "Mem failure returns null" ); assert( newFont.equals(StrapFont.defaultFont()) || i < 20, "Mem failure doesn't return system font" ); } assert( newFont.getName().equals(GoodFontDescription) , "Wrong font name" ); } catch (Exception e) { assert( false, "font function threw exception" ); } System.out.println("done"); return; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -