[See below for updates]
I am having a hard time defining a pattern. My colleague says it's adaptor pattern. I'm not sure. We're stuck mainly because we want to correctly name our components.
Question: Is it adapter pattern? If not what is it? If it is something else, is this the best way to implement the idea?
To put it in summary, it is a main component(is this the adapter?) that shares an interfaces with sub-components (are these providers?). The main components decides/orchestrates which of the sub-components are called. The main component behaves as some sort of "wrapper" to call one of the others that have the same interface. The instances of which are injected through the constructor.
Assumptions:
For simplicity, we will ignore DR/IoC for now, but we understand and apply the pattern/principle.
The code is not the best implemented form...feel free to suggest.
My use of the words main/sub does not infer some kind of inheritence...just bad naming on my part, if confusing.
It's language-agnostic, because I love contributions from C# and Java guys, and the knowledge they share.
I am using a Social Networking scenario where a main component gets stats on a hastag and instantiates the appropriate Social Sub Component (
There is a Social Component interface:
ISocialComponent
{
SomeStatsObject GetStats(string hashTag);
}
Social Sub-Components implement ISocialComponent Interface
Twitter Sub-Component
public class TwitterSubComponent : ISocialComponent
{
public SomeStatsObject GetStats(string hashTag)
{
return SomeMethodThatReturnsStatsObject(hashTag);
}
private SomeMethodThatReturnsStatsObject(string hashTag)
{
//... Twitter-specific code goes here
}
}
Facebook Sub-Component
public class FacebookSubComponent : ISocialComponent
{
public SomeStatsObject GetStats(string hashTag)
{
return SomeMethodThatReturnsStatsObject(hashTag);
}
private SomeMethodThatReturnsStatsObject(string hashTag)
{
//... Facebook-specific code goes here
}
}
Instagram Sub-Component
public class InstagramSubComponent : ISocialComponent
{
public SomeStatsObject GetStats(string hashTag)
{
return SomeMethodThatReturnsStatsObject(hasTag);
}
private SomeMethodThatReturnsStatsObject(string hashTag)
{
//... Instagram-specific code goes here
}
}
Main Component
There is a main social component object that calls any one of the Sub-Components (defined below) that implement the shared ISocialComponent interface
public class MainSocialComponent : ISocialComponent
{
//this is an enum
private RequestedNetwork _requestedNetwork{ get; set;}
//the SocialComponent instance is injected outside of this class
private readonly ISocialComponent _socialComponent;
public MainSocialComponent(ISocialComponent socialComponent)
{
_socialComponent = socialComponent;
}
public SomeStatsObject GetStats(string hashTag)
{
return _socialComponent.GetStats(hashTag)
/**** original code, kept for historical purposes****
switch(_requestedNetwork)
{
case RequestedNetwork.Twitter:
var twit = new TwitterSubComponent();
return twit.GetStats(hashTag)
break;
case RequestedNetwork.Facebook:
var fb = new FacebookSubComponent();
return fb.GetStats(hashTag)
break;
case RequestedNetwork.Instagram:
var in = new InstagramSubComponent();
return in.GetStats(hashTag)
break;
default:
throw new Exception("Undefined Social Network");
break;
}*/
}
}
Updates:
I see why some say it is Factory pattern because it is creating objects. I had mentioned that we use an IoC container and DR. It was my mistake to exclude that. I have refactored the code
As others have mentioned, this is part of the Factory/Service pattern which is pretty popular for Dependency Injection and Inversion of Control.
Right now though there is no reason to declare your sub components as non static, since you aren't saving your instances to anything.
So it seems to me unless you have missing code where you add the components to a list or something, you could just do this:
public static class InstagramSubComponent : ISocialComponent
{
public static SomeStatsObject GetStats(string hashTag)
{
return stuff;
}
}
public class MainSocialComponent : ISocialComponent
{
//this is an enum
private RequestedNetwork _requestedNetwork{ get; set;}
private static var Mappings = new Dictionary<string, Func<SomeStatsObject>> {
{ "Twitter", TwitterSubComponent.GetStats },
{ "Facebook", FacebookSubComponent.GetStats },
{ "Instagram", InstagramSubComponent.GetStats }
}
public SomeStatsObject GetStats(string hashTag)
{
return Mappings[hashTag].invoke();
}
}
}
Now if you are doing stuff like actually saving your instances of sub components to a list for later or whatever, then that changes everything. But I am not seeing that so there's no reason not to just make it all static if these methods are simple.
If they are very complex then you'll want to use dependency injection so you can unit test everything proper.
I believe you can extract creation of SubComponent into a Factory and pass this Factory to MainSocialComponent. Inside of the GetStats method, you will call _factory.Create(hashTag); and than call GetStats on the returned object.
This way you'll have factory pattern.
This is definitely not an adapter pattern.
An adapter pattern does the following in most cases :
• Works as a bridge between two incompatible interfaces.
• Allows classes with incompatible interfaces work together
Your case is more like a Factory pattern. You use high level abstraction and return the type of interface/component whenever you need to.
Related
Our application is getting complex, it has mainly 3 flow and have to process based on one of the 3 type. Many of these functionalities overlap each other.
So currently code is fully of if-else statements, it is all messed up and not organised. How to make a pattern so that 3 flows are clearly separated from each other but making use of power of re-usability.
Please provide some thoughts, this is a MVC application, where we need to produce and consume web servicees using jaxb technology.
May be you can view the application as a single object as input on which different strategies needs to be implemented based on runtime value.
You did not specify what your if-else statements are doing. Say they filtering depending on some value.
If I understand your question correctly, you want to look at Factory Pattern.
This is a clean approach, easy to maintain and produces readable code. Adding or removing a Filter is also easy, Just remove the class and remove it from FilterFactory hashmap.
Create an Interface : Filter
public interface Filter {
void Filter();
}
Create a Factory which returns correct Filter according to your value. Instead of your if-else now you can just use the following :
Filter filter = FilterFactory.getFilter(value);
filter.filter();
One common way to write FilterFactory is using a HashMap inside it.
public class FilterFactory{
static HashMap<Integer, Filter> filterMap;
static{
filterMap = new HashMap<>();
filterMap.put(0,new Filter0());
...
}
// this function will change depending on your needs
public Filter getFilter(int value){
return filterMap.get(value);
}
}
Create your three(in your case) Filters like this: (With meaningful names though)
public class Filter0 implements Filter {
public void filter(){
//do something
}
}
NOTE: As you want to reuse some methods, create a FilterUtility class and make all your filters extend this class so that you can use all the functions without rewriting them.
Your question is very broad and almost impossible to answer without some description or overview of the structure of your application. However, I've been in a similar situation and this is the approach I took:
Replace conditions with Polymorphism where possible
it has mainly 3 flow and have to process based on this one of the 3
type. Many of these functionalities overlap each other.
You say your project has 3 main flows and that much of the code overlaps each other. This sounds to me like a strategy pattern:
You declare an interface that defines the tasks performed by a Flow.
public interface Flow{
public Data getData();
public Error validateData();
public void saveData();
public Error gotoNextStep();
}
You create an abstract class that provides implementation that is common to all 3 flows. (methods in this abstract class don't have to be final, but you definitely want to consider it carefully.)
public abstract class AbstractFlow{
private FlowManager flowManager
public AbstractFlow(FlowManager fm){
flowManager = fm;
}
public final void saveData(){
Data data = getData();
saveDataAsXMl(data);
}
public final Error gotoNextStep(){
Error error = validateData();
if(error != null){
return error;
}
saveData();
fm.gotoNextStep();
return null;
}
}
Finally, you create 3 concrete classes that extend from the abstract class and define concrete implementation for the given flow.
public class BankDetailsFlow extends AbstractFlow{
public BankDetailsData getData(){
BankDetailsData data = new BankDetailsData();
data.setSwiftCode(/*get swift code somehow*/);
return data;
}
public Error validateData(){
BankDetailsData data = getData();
return validate(data);
}
public void onFormSubmitted(){
Error error = gotoNextStep();
if(error != null){
handleError(error);
}
}
}
Lets take example, suppose you have model say "Data" [which has some attributes and getters,setters, optional methods].In context of Mobile application ,in particular Android application there can be two modes Off-line or On-line. If device is connected to network , data is sent to network else stored to local database of device.
In procedural way someone can , define two models as OnlineData,OfflineData and write code as[The code is not exact ,its just like pseudo code ]:
if(Connection.isConnected()){
OnlineData ond=new OnlineData();
ond.save();//save is called which stores data on server using HTTP.
}
else{
OfflineData ofd=new Onlinedata();
ofd.save();//save is called which stores data in local database
}
A good approach to implement this is using OOPS principles :
Program to interface not Implementation
Lets see How to DO THIS.
I am just writing code snippets that will be more effectively represent what I mean.The snippets are as follows:
public interface Model {
long save();//save method
//other methods .....
}
public class OnlineData extends Model {
//attributes
public long save(){
//on-line implementation of save method for Data model
}
//implementation of other methods.
}
public class OfflineData extends Model {
//attributes
public long save(){
//off-line implementation of save method for Data model
}
//implementation of other methods.
}
public class ObjectFactory{
public static Model getDataObject(){
if(Connection.isConnected())
return new OnlineData();
else
return new OfflineData();
}
}
and Here is code that your client class should use:
public class ClientClass{
public void someMethod(){
Model model=ObjectFactory.getDataObject();
model.save();// here polymorphism plays role...
}
}
Also this follows:
Single Responsibility Principle [SRP]
because On-line and Off-line are two different responsibilities which we can be able to integrate in Single save() using if-else statement.
After loong time I find opensource rule engine frameworks like "drools" is a great alternative to fit my requirement.
The title might not be very clear but i could not figure out a better one. Here is the problem. I have a Scope interface which gives all the pages where a QueryEngine should query in.
interface Scope{
Set<Page> getPages();
}
interface QueryEngine{
void query(Scope scope){
queryIn(scope.getPages());
}
}
There is another type of scope which says query all the pages other than the ones it provides.
I was trying to model this behavior.
interface ExcludeScope extends Scope{
}
In which case i have to do something like below in QueryEngine
interface QueryEngine{
void query(Scope scope){
if(scope instanceof ExcludeScope){
queryInPagesOtherThan(scope.getPages());
}else{
queryIn(scope.getPages());
}
}
}
Or should it be something which is driven by a boolean
interface Scope{
Set<Page> getPages();
boolean shouldExclude();
}
I feel both the above approaches would lead to if, else conditions in the QueryEngine
which means that it is not closed for modifications.
How to design such a behaviour? What should be the approach one should follow while tackling any design problem? Should we start by checking whether SOLID principles were followed? Should we look to classify the problem under a design pattern thus arrive at a solution?
One possibility is to perform an inversion of control: The QueryEngine asks a Scope whether to process a page or not and the Scope answers independently true or false, similar to
interface Scope {
boolean process(Page page);
}
interface QueryEngine {
void query(Scope scope, Set<Page> pages) {
Set<Pages> pagesToProcess = new HashSet<Page>();
for (Page page : pages) {
if (scope.process(page)) {
pagesToProcess.add(page);
}
}
queryIn(pagesToProcess);
}
}
class IncludeScope implements Scope {
private static final Set<Page> INCLUDING_PAGES = ...
public boolean process(Page page) {
return INCLUDING_PAGES.contains(page);
}
}
class ExcludeScope implements Scope {
private static final Set<Page> EXCLUDING_PAGES = ...
public boolean process(Page page) {
return !EXCLUDING_PAGES.contains(page);
}
}
In my opinion the root of your problem is in this sentence:
There is another type of scope which says query all the pages other than the ones it provides".
Scope has nothing to do with querying, it should only represent a subset of all elements. You seem to want to perform a query in a different way, so I would suggest to go for a new method in the QueryEngine:
interface QueryEngine{
void query(Scope scope){
...
}
void queryComplement(Scope scope) {
...
}
}
The following is an approximation of the problem I'm facing.
Think we have a password validator with some rules.
public interface RuleChecker{
//Checks for a password strenght, returns 10
//for strong or 0 for soft password.
int check(String pass);
}
And then we have several implementations, our service will only accept the password if it is over 8 score.
public class NoCheck implements RuleChecker {
public int check(String pass){return 10;}
}
public class LengthCheck implements RuleChecker{
...
}
public class AlphanumericCheck implements RuleChecker{
...
}
public class AlphaAndLenghtCheckAdapter implements RuleChecker{
...
}
But for testing purposes, we want to implement a webservice within the application where we can "admin" those rules, and select which ones to have.
public class PasswordCheckService{
private RuleChecker checker;
#Inject
public PasswordCheckService(final RuleChecker checker){
this.checker = checker;
}
public boolean checkPassword(String password){
return checker.check(password) > 8;
}
}
So, is there any way in Guice, to change at runtime, the injection a service has?
Example:
We started the application and by default LengthCheck is selected and injected on the application, at the website we select the NoCheck checkbox and save options, which is stored into the database, can I configure Guice to automatically change the bean the service had injected before? so from now and on there will be no checks on new passwords?
--
As for now, I have found those topics
Google Guice and varying injections at runtime
But i dont know if that kind of providers fits my problem.
Guice runtime dependency parameters reinjection
That nice question is talking something similar, but not what I'm looking form.
guice: runtime injection/binding at command line
This is the closest to my problem but he only does on starting "runtime" and does not change it over the time.
Any helps?
Thank you!
Using the tip of the first comment I implemented this POC but still does not works, if you change select another button the service bean is not updated.
https://bitbucket.org/ramonboza/guicedynamicconfig
Create a provider for each field type (login, password, birth date...), with a parameter to change the implementation to return.
public class MyModule extends AbstractModule {
public void configure() {
bind(RuleChecker.class).annotatedWith(named("password")).toProvider(PasswordRuleCheckerProvider.class);
bind(RuleChecker.class).annotatedWith(named("login")).toProvider(LoginRuleCheckerProvider.class);
}
}
public static class PasswordRuleCheckerProvider implements Provider<RuleChecker> {
private static CheckType type = CheckType.ALPHANUMERIC;
// static type setter.
public RuleChecker get() {
// it would even be better if you could use singletons here.
switch(type) {
case LENGTH:
return new LengthCheck();
case ALPHANUMERIC:
return new AlphanumericCheck();
case ALPHALENGTH:
return new AlphaAndLenghtCheckAdapter();
case NONE:
default:
return NoCheck();
}
}
}
// Almost same provider for your LoginRuleCheckerProvider. You could do something generic.
In your admin section you change "type" value, so your rules will change. It can affect a limited set of fields, thanks to the annotations. For instance : PasswordRuleCheckerProvider.setType(CheckType.LENGTH);. Will only affect fields with #Named('password').
You have to declare your fields and services like this :
public abstract class DynamicService {
protected void updateService() {
// Reinject with the new implementations the members.
App.getInjector().injectMembers(this);
}
}
public class PasswordCheckService extends DynamicService {
#Inject
#Named("password")
private RuleChecker passwordChecker;
public void changePasswordCheckType(CheckType type) {
PasswordRuleCheckerProvider.setType(type);
// Reinject, so you have your new implementation.
updateService();
}
// [...]
}
I want to avoid using tagged classes and big if-else blocks or switch statement and use polymorphism with a class hierarchy instead, which I believe is better practice.
For example, something like the below, where the choice of executed method is dependent only one one field of an object of type Actor.
switch(actor.getTagField())
{
case 1: actor.act1(); break;
case 2: actor.act2(); break;
[...]
}
would become
actor.act();
and the act method would be overridden in subclasses of Actor.
However, the most obvious way to decide at runtime which subclass to instantiate looks awfully similar to the original:
Actor newActor(int type)
{
switch(type)
{
case 1: return new Actor1();
case 2: return new Actor2();
[...]
}
}
so it seems like nothing has really been gained; the logic has just been moved.
What is a better way to do this? The only way I can come up with involved implementing a factory class for each subclass of Actor, but this seems rather cumbersome for such a simple problem.
Am I overthinking this? It just seems like there's no point making the original change if I just do pretty much the same thing elsewhere.
Question is "if" you need a factory. The factory is meant to manage the creation of instances an not so much the behavior of related instances.
Otherwise, you're just looking at basic inheritance. Something like..
class Actor{
public void act(){
System.out.println("I act..");
}
}
class StuntActor extends Actor {
public void act(){
System.out.println("I do fancy stunts..");
}
}
class VoiceActor extends Actor {
public void act(){
System.out.println("I make funny noises..");
}
}
To Use, you can just instantiate the type of actor you need directly.
Actor fred = new Actor();
Actor tom = new VoiceActor();
Actor sally = new StuntActor();
fred.act();
tom.act();
sally.act();
Output:
I act..
I make funny noises..
I do fancy stunts..
EDIT:
If you need to centralize the creation of the Actors..aka vis a Factory, you will not be able to get away from some kind of switching logic--in which case..i'll typically use an enumeration for readability:
public class Actor{
public enum Type{ REGULAR, VOICE, STUNT }
public static Actor Create(Actor.Type type){
switch(type) {
case VOICE:
return new VoiceActor();
case STUNT:
return new StuntActor();
case REGULAR:
default:
return new Actor();
}
}
public void act(){
System.out.println("I act..");
}
}
Usage:
Actor some_actor = Actor.Create(Actor.Type.VOICE);
some_actor.act();
Output:
I make funny noises..
Switch statements aren't pure evil. It's really duplication that you're looking to eliminate with better design. Often times you'll find the same switch statement show up in different (far away) places in your code - not necessarily doing the same thing, but switching on the same data. By introducing polymorphism, you pull those switches together as different methods of the same object.
This does two things, first it reduces several switches to one switch inside of a factory and it pulls together spread out logic that probably depends on similar data. That data will turn into member variables in your objects.
It's also worth noting that you don't always end up with a switch statement under the hood of your factory. Maybe you could scan the classpath at startup and build a HashMap of types that implement an interface. For example, consider an implementation of a socket protocol like SMTP. You could have objects named HeloCommand, MailFromCommand, etc... and find the right object to handle the message by matching the socket command to the class name.
I believe that you can do it with Abstract factory pattern...
This is a example:
abstract class Computer {
public abstract Parts getRAM();
public abstract Parts getProcessor();
public abstract Parts getMonitor();
}
class Parts {
public String specification;
public Parts(String specification) {
this.specification = specification;
}
public String getSpecification() {
return specification;
}
}
We have two class that extends Computer
class PC extends Computer {
public Parts getRAM() {
return new Parts("512 MB");
}
public Parts getProcessor() {
return new Parts("Celeron");
}
public Parts getMonitor() {
return new Parts("15 inches");
}
}
class Workstation extends Computer {
public Parts getRAM() {
return new Parts("1 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 3");
}
public Parts getMonitor() {
return new Parts("19 inches");
}
}
And finally we have,
public class ComputerType {
private Computer comp;
public static void main(String[] args) {
ComputerType type = new ComputerType();
Computer computer = type.getComputer("Workstation");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
}
public Computer getComputer(String computerType) {
if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
return comp;
}
}
I have enum say ErrorCodes that
public enum ErrorCodes {
INVALID_LOGIN(100),
INVALID_PASSWORD(101),
SESSION_EXPIRED(102) ...;
private int errorCode;
private ErrorCodes(int error){
this.errorCode = error;
} //setter and getter and other codes
}
now I check my exception error codes with this error codes. I don't want to write if this do this, if this do this. How I can solve this problem (writing 10+ if blocks)
Is there any design patter to that situation ?
Thanks
Either you do it with a if-statement or a switch, or you just implement the logic in question into the ErrorCode somehow.
In an OO fashion it all depends on how you want the application or system react to the error code. Lets say you just want it to output somekind of dialog:
public doSomethingWithError() {
ErrorCodes e = getError();
// the source of error, or originator, returns the enum
switch(e) {
case ErrorCodes.INVALID_LOGIN:
prompt('Invalid Login');
case ErrorCodes.INVALID_PASSWORD:
prompt('Invalid password');
// and so on
}
}
We could instead create an ErrorHandler class that does this instead:
// We'll implement this using OO instead
public doSomethingWithError() {
ErrorHandler e = getError();
// the originator now returns an ErrorHandler object instead
e.handleMessage();
}
// We will need the following abstract class:
public abstract class ErrorHandler {
// Lets say we have a prompter class that prompts the message
private Prompter prompter = new Prompter();
public final void handleMessage() {
String message = this.getMessage();
prompter.prompt(message);
}
// This needs to be implemented in subclasses because
// handleMessage() method is using it.
public abstract String getMessage();
}
// And you'll have the following implementations, e.g.
// for invalid logins:
public final class InvalidLoginHandler() {
public final String getMessage() {
return "Invalid login";
}
}
// E.g. for invalid password:
public final class InvalidPasswordHandler() {
public final String getMessage() {
return "Invalid password";
}
}
The former solution is easy to implement, but becomes difficult to maintain as the code grows larger. The latter solution is more complex, (aka. Template Method pattern following the Open-Closed Principle) but enables you to add more methods into the ErrorHandler when you need it (such as restoring resources or whatever). You can also implement this with the Strategy pattern.
You won't get away completely with the conditional statements, but in the latter the conditional is pushed to the part of the code where the error is originated. That way you won't have double maintenance on conditional statements both at the originator and the error handling code.
EDIT:
See this answer by Michael Borgwardt and this answer by oksayt for how to implement methods on Java Enums if you want to do that instead.
Java enums are very powerful and allow per-instance method implementations:
public enum ErrorCode {
INVALID_LOGIN {
public void handleError() {
// do something
}
},
INVALID_PASSWORD {
public void handleError() {
// do something else
}
},
SESSION_EXPIRED {
public void handleError() {
// do something else again
}
};
public abstract void handleError();
}
Then you can simply call errorCode.handleError();. However, it is questionable whether an ErrorCode enum is really the right place for that logic.
As pointed out by Spoike, using polymorphism to pick the right error handling method is an option. This approach basically defers the 10+ if blocks to the JVM's virtual method lookup, by defining a class hierarchy.
But before going for a full-blown class hierarchy, also consider using enum methods. This option works well if what you plan to do in each case is fairly similar.
For example, if you want to return a different error message for each ErrorCode, you can simply do this:
// Note singular name for enum
public enum ErrorCode {
INVALID_LOGIN(100, "Your login is invalid"),
INVALID_PASSWORD(101, "Your password is invalid"),
SESSION_EXPIRED(102, "Your session has expired");
private final int code;
private final String
private ErrorCode(int code, String message){
this.code = code;
this.message = message;
}
public String getMessage() {
return message;
}
}
Then your error handling code becomes just:
ErrorCode errorCode = getErrorCode();
prompt(errorCode.getMessage());
One drawback of this approach is that if you want to add additional cases, you'll need to modify the enum itself, whereas with a class hierarchy you can add new cases without modifying existing code.
I believe the best you can do is implementing the strategy pattern. This way you won't have to change existing classes when adding new enums but will still be able to extend them. (Open-Closed-Principle).
Search for Strategy Pattern and Open Closed Principle.
You can create a map of error codes(Integer) against enum types
Edit
In this solution, once the map is prepared, you can look up an error code in the map and thus will not require if..else look ups.
E.g.
Map<Integer, ErrorCodes> errorMap = new HashMap<Integer, ErrorCodes>();
for (ErrorCodes error : ErrorCodes.values()) {
errorMap.put(error.getCode(), error);
}
Now when you want to check an error code coming from your aplpication, all you need to do is,
ErrorCodes error = errorMap.get(erro_code_from_application);
Thus removing the need for all the if..else.
You just need to set up the map in a way that adding error codes doesn't require changes in other code. Preparation of the map is one time activity and can be linked to a database, property file etc during the initialization of your application
In my opinion there is nothing wrong with ErrorCodes as enums and a switch statement to dispatch error handling. Enums and switch fit together really well.
However, maybe you find the following insteresting (kind of over-design), see an Example
or "Double dispatching" on Wikipedia.
Assumed requirements:
Error-handling should be encapsulated in an own class
Error-handling should be replacable
Type safety: Whenever an error is added, you are forced to add error handling at each error-handler implementation. It is not possible to "forget" an error in one (of maybe many) switch statments.
The code:
//Inteface for type-safe error handler
interface ErrorHandler {
void handleInvalidLoginError(InvalidLoginError error);
void handleInvalidPasswordError(InvalidLoginError error);
//One method must be added for each kind error. No chance to "forget" one.
}
//The error hierachy
public class AbstractError(Exception) {
private int code;
abstract public void handle(ErrorHandler);
}
public class InvalidLoginError(AbstractError) {
private String additionalStuff;
public void handle(ErrorHandler handler) {
handler.handleInvalidLoginError(this);
}
public String getAdditionalStuff();
}
public class InvalidPasswordError(AbstractError) {
private int code;
public void handle(ErrorHandler handler) {
handler.handleInvalidPasswordError(this);
}
}
//Test class
public class Test {
public void test() {
//Create an error handler instance.
ErrorHandler handler = new LoggingErrorHandler();
try {
doSomething();//throws AbstractError
}
catch (AbstractError e) {
e.handle(handler);
}
}
}