Java中的贷款模式(又名贷方承租人模式)
這篇文章是關于在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
總結
以上是生活随笔為你收集整理的Java中的贷款模式(又名贷方承租人模式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 瑞幸茅台酱香拿铁上架 喝了能开车吗?
- 下一篇: 魅族 20 独白机型新增 12GB+25