这篇文章是关于在Java中实现贷款模式的。
用例
在保存资源的代码与访问资源的代码之间实现分离,从而使访问代码无需管理资源。 当我们编写用于读取/写入文件或查询SQL / NOSQL数据库的代码时,上述用例适用。 在AOP的帮助下,肯定有API处理了此问题。 但是我认为,如果基于模式的方法可以帮助我们处理此类用例,那便是我了解贷款模式 (又称为贷方借出模式)的地方 。
它能做什么
贷款模式采用“借贷方式”,即保持对调用代码的资源“借贷”的代码。 一旦借方 (访问资源的代码)使用了借方 (没有兴趣),出借方 (即保存资源的代码)就对资源进行管理。 让我们进入贷方代码:
/*** This class is an illustration of using loan pattern(a.k.a lender-lendee pattern) * @author prassee*/
public class IOResourceLender {/*** Interface to write data to the buffer. Clients using this* class should provide impl of this interface * @author sysadmin**/public interface WriteBlock {void call(BufferedWriter writer) throws IOException;}/*** Interface to read data from the buffer. Clients using this* class should provide impl of this interface* @author sysadmin**/public interface ReadBlock {void call(BufferedReader reader) throws IOException;}/*** method which loans / lends the resource. Here {@link FileWriter} is the * resource lent. The resource is managed for the given impl of {@link WriteBlock}* * @param fileName* @param block* @throws IOException*/public static void writeUsing(String fileName, WriteBlock block)throws IOException {File csvFile = new File(fileName);if (!csvFile.exists()) {csvFile.createNewFile();}FileWriter fw = new FileWriter(csvFile.getAbsoluteFile(), true);BufferedWriter bufferedWriter = new BufferedWriter(fw);block.call(bufferedWriter);bufferedWriter.close();}/*** method which loans / lends the resource. Here {@link FileReader} is the * resource lent. The resource is managed for * the given impl of {@link ReadBlock}* * @param fileName* @param block* @throws IOException*/public static void readUsing(String fileName, ReadBlock block)throws IOException {File inputFile = new File(fileName);FileReader fileReader = new FileReader(inputFile.getAbsoluteFile());BufferedReader bufferedReader = new BufferedReader(fileReader);block.call(bufferedReader);bufferedReader.close();}
}
贷方代码包含一个FileWriter,资源,我们还期望实现WriteBlock,以便writeUsing方法仅在管理资源内的WriteBlock接口上调用该方法。 在客户端(lendee)一侧,我们提供了WriteBlock的匿名实现。 这是lendee代码,Iam只是给您一个方法,您可以在自己喜欢的类中使用它。
public void writeColumnNameToMetaFile(final String attrName,String fileName, final String[] colNames) throws IOException {IOResourceLender.writeUsing(fileName,new IOResourceLender.WriteBlock() {public void call(BufferedWriter out) throws IOException {StringBuilder buffer = new StringBuilder();for (String string : colNames) {buffer.append(string);buffer.append(',');}out.append(attrName + ' = ' + buffer.toString());out.newLine();}});}
该示例将借出模式用于简单的文件IO操作。 但是,可以通过提供抽象的贷方和借贷方来进一步改进此代码。本文的代码在以下要点中共享:https://gist.github.com/4481190,我欢迎您的评论和建议!
参考: Scala上Prassee上的 JCG合作伙伴 Prasanna Kumar提供的Java贷款模式(又称贷方借出模式) 。
翻译自: https://www.javacodegeeks.com/2013/01/loan-pattern-in-java-a-k-a-lender-lendee-pattern.html