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) { } } }
夜已经深了,看客老爷看完之后是否有一点点的感觉呢。
如果你不喜欢将世间万物抽象到计算机的世界,或许程序员只是你谋生的手段,你可能体会不到代码的美丽。