Java 中實例化類的動作,你是否還是一成不變 new 對應對象呢?
經手的項目多了,代碼編寫量自然會增加,漸漸的會對設計模式產生感覺。
怎樣使書寫出來的類實例化動作,高內聚,低耦合,又兼具一定的擴展能力呢?
本文試圖從幾段鮮活的代碼入手,給大家呈現不一樣的 Java 實例化類。
下面代碼取自 com.google.zxing 源碼實現:
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException { Object writer; switch(format.ordinal()) { case 1: writer = new AztecWriter(); break; case 2: writer = new CodaBarWriter(); break; case 3: writer = new Code39Writer(); break; case 4: case 10: case 13: case 14: default: throw new IllegalArgumentException("No encoder available for format " + format); case 5: writer = new Code128Writer(); break; case 6: writer = new DataMatrixWriter(); break; case 7: writer = new EAN8Writer(); break; case 8: writer = new EAN13Writer(); break; case 9: writer = new ITFWriter(); break; case 11: writer = new PDF417Writer(); break; case 12: writer = new QRCodeWriter(); break; case 15: writer = new UPCAWriter(); break; case 16: writer = new UPCEWriter(); } return ((Writer)writer).encode(contents, format, width, height, hints); }
public enum BarcodeFormat { AZTEC, CODABAR, CODE_39, CODE_93, CODE_128, DATA_MATRIX, EAN_8, EAN_13, ITF, MAXICODE, PDF_417, QR_CODE, RSS_14, RSS_EXPANDED, UPC_A, UPC_E, UPC_EAN_EXTENSION; private BarcodeFormat() { } }
BitMatrix bitMatrix = new MultiFormatWriter().encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints); MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile);
switch(format.ordinal()) { case 1: writer = new AztecWriter(); break; case 2: writer = new CodaBarWriter(); break; case 3: writer = new Code39Writer(); break; ...............
public interface Writer { BitMatrix encode(String var1, BarcodeFormat var2, int var3, int var4) throws WriterException; BitMatrix encode(String var1, BarcodeFormat var2, int var3, int var4, Map<EncodeHintType, ?> var5) throws WriterException; }
在來看經典 MVC 框架 Webwork 動態實例化類的一段方法代碼:
private static Configuration getDefaultConfiguration () { if (defaultImpl == null) { defaultImpl = new DefaultConfiguration(); try { String className = getString("webwork.configuration"); if (!className.equals(defaultImpl.getClass().getName())) { try { defaultImpl = (Configuration) ObjectFactory.getObjectFactory().buildBean(Thread.currentThread().getContextClassLoader().loadClass(className)); } catch (Exception e) { LOG.error("Could not instantiate configuration", e); } } return defaultImpl; } catch (IllegalArgumentException localIllegalArgumentException) { } } }
夜已經深了,看客老爺看完之後是否有一點點的感覺呢。
如果你不喜歡將時間萬物抽象到計算機的世界,或許程序員只是你謀生的手段,你可能體會不到代碼的美麗。