Loan pattern in Java (a.k.a lender lendee pattern)

This post is about implementing loan pattern in Java.

Use Case

Implement separation between the code that holds resource from that of accessing it such that the accessing code doesn’t need to manage the resources. The use case mentioned holds true when we write code to read/write to a file or querying SQL / NOSQL dbs. There are certainly API’s handled this with the help of AOP. But I thought if a pattern based approach could help us to deal with these kind of use case, that’s where I came to know about Loan Pattern (a.k.a lender lendee pattern).
 

What it does

Loan pattern takes a “lending approach” i.e the code which keep hold of the resources “lends” if to the calling code. The lender (a.k.a code which holds resources) manages the resources once the lendee (code accessing the resource) has used it (with no interest ). Lets get in to lender code:

/**
 * 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();
	}
}

The lender code holds a FileWriter, the resource and we also expect an implementation of WriteBlock so that writeUsing method just calls the method on the WriteBlock interface which is enclosed within the managing the resource. One the client(lendee) side we provide an anonymous implementation of WriteBlock. Here is the lendee code, Iam just giving an method its up to the you to use it in the class which you may like.

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();
					}
				});
	}

The example uses the loan pattern for a simple file IO operation. However this code could be further improved by providing abstract lenders and lendee.The code for this post is shared in the following gist https://gist.github.com/4481190 I welcome your comments and suggestions !!
 

Reference: Loan pattern in Java (a.k.a lender lendee pattern) from our JCG partner Prasanna Kumar at the Prassee on Scala blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

2 Responses to "Loan pattern in Java (a.k.a lender lendee pattern)"

  1. Christian Schlichtherle says:

    Note that you must close the streams in a finally-block, otherwise a file descriptor remains open if the Block.call() fails. In a long running server app, this may exhaust the OS resources and trigger a grinding halt.

  2. Young says:

    I usually use this pattern,but I never call “Loan pattern” and I don’t even call it what!

Leave a Reply


× eight = 24



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books