Friday 30 August 2013

Intercepting Filter Design Pattern - Implementation


Click here to watch in Youtube : https://www.youtube.com/watch?v=sWtchigtgXk

Click the below Image to Enlarge
Intercepting Filter Design Pattern - Implementation






















Filter.Java

public interface Filter
{
public void processRequest(String request);
}

AuthenticationFilter.java

public class AuthenticationFilter implements Filter
{

@Override
        public void processRequest( String request )
        {
System.out.println("Authenticating the request by AuthenticationFilter : " + request);
       
        }

}

LoggingFilter.java

public class LoggingFilter implements Filter
{
@Override
        public void processRequest( String request )
        {
System.out.println("Request Tracking is done by LoggingFilter : " + request);        
        }
}

Target.java

public class Target
{
public void processRequest( String request )
{
System.out.println("Process the Request by Target Class: " + request);
}
}

FilterChain.java

import java.util.ArrayList;
import java.util.List;

public class FilterChain
{
private List<Filter> filters = new ArrayList<Filter>();
private Target       target;

public void addFilter( Filter filter )
{
filters.add(filter);
}

public void execute( String request )
{
for( Filter filter : filters )
{
filter.processRequest(request);
}
target.processRequest(request);
}

public void setTarget( Target target )
{
this.target = target;
}
}

FilterManager.java

public class FilterManager
{
FilterChain filterChain;

public FilterManager( Target target )
{
filterChain = new FilterChain();
filterChain.setTarget(target);
}

public void setFilter( Filter filter )
{
filterChain.addFilter(filter);
}

public void filterRequest( String request )
{
filterChain.execute(request);
}
}

Client.java

public class Client
{
FilterManager filterManager;

public void setFilterManager( FilterManager filterManager )
{
this.filterManager = filterManager;
}

public void sendRequest( String request )
{
filterManager.filterRequest(request);
}

public static void main( String[] args )
{
FilterManager filterManager = new FilterManager(new Target());
filterManager.setFilter(new AuthenticationFilter());
filterManager.setFilter(new LoggingFilter());
Client client = new Client();
client.setFilterManager(filterManager);
client.sendRequest("HOME");

}

}

Output

Authenticating the request by AuthenticationFilter : HOME
Request Tracking is done by LoggingFilter : HOME


1 comment:

  1. Why don't you create a login/authentication app and show the real implementation of Filters?

    ReplyDelete