Created
January 8, 2013 04:36
-
-
Save prassee/4481190 to your computer and use it in GitHub Desktop.
loan pattern in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
} | |
} | |
// client code | |
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(); | |
} | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment