Skip to content

Instantly share code, notes, and snippets.

@amitguptagwl
Created October 15, 2016 19:31
Show Gist options
  • Save amitguptagwl/82150ee11443f87b271848f0b92c1217 to your computer and use it in GitHub Desktop.
Save amitguptagwl/82150ee11443f87b271848f0b92c1217 to your computer and use it in GitHub Desktop.
Visitor Pattern
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class VisitorPatternExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
//list.add("java");
list.add("pdf");
list.add("html");
list.forEach(file -> {
FileOperator head = new Head();
FileUtil.fileIdentifier(file).doFileOperation(head);
});
}
}
//Visitable
interface ReadableFile {
public String readNextLine();
public void doFileOperation(FileOperator operator);
}
class PdfFile implements ReadableFile {
PdfFile(String fileName) {
// Create instance of File
}
public String readNextLine() {
return "Reading line from a PDF";
}
@Override
public void doFileOperation(FileOperator operator) {
operator.processPdfFile(this);
}
public boolean isSecure() {
return false;
}
}
class HtmlFile implements ReadableFile {
HtmlFile(String fileName) {
// Create instance of File
}
public String readNextLine() {
return "Reading line from a HTML";
}
@Override
public void doFileOperation(FileOperator operator) {
operator.processHtmlFile(this);
}
}
interface FileOperator{
public void processPdfFile(PdfFile file);
public void processHtmlFile(HtmlFile file);
}
class Head implements FileOperator{
public void operation(PdfFile file) {
file.readNextLine();
}
@Override
public void processPdfFile(PdfFile file) {
if(file.isSecure()){
System.out.println("Can't read secure file");
}else{
System.out.println(file.readNextLine());
}
}
@Override
public void processHtmlFile(HtmlFile file) {
System.out.println(file.readNextLine());
}
}
class FileUtil {
public static ReadableFile fileIdentifier(String fileName) {
if (fileName.toString().contains("pdf"))
return new PdfFile(fileName);
else if (fileName.toString().contains("html"))
return new HtmlFile(fileName);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment