CSharp example of visitor pattern for ElseIf condition

Jan 30, 2013 00:00 · 362 words · 2 minute read Programming Design pattern

We can use the Visitor design pattern to get round the elseif or switch case conditions and push our method to the single responsible behavior.

This design pattern can apply if the conditions are different in types and not values.

Example

We have a Factory method that decide of the the passing class type.Class one and two are abstracted in the ICondition interface.

public class ElseIf {
	public string Factory(ICondition condition) {
		string status=string.Empty;
		if(condition.GetType()==typeof(One)) {
			status = "This is class one type";
		} else if(condition.GetType()==typeof(Two)) {
			status = "This is class two type";
		}
			return status;
	}
}

IVisitor interface

Making the visitor interface that contains our factory overloads

IVisitor

public interface IVisitor {
	void Visit(One one);
	void Visit(Two two);
}

Implement the IVisitor interface

Implement it to the class that you wish to contain your business logic.

Impelementing IVisitor

public class GetStatus:IVisitor {
	public string status = string.Empty;
	public void Visit(One one) {
		status = "This is class one type";
	}
	public void Visit(Two two) {
		status = "This is class two type";
	}
}

Super type

Make a super type class for your overloads and ask it to implement from Icondition interface.

super type

public class SuperType : ICondition { }

Update interface

Add Accept method to your ICondition interface .

ICondition

public interface ICondition {
	void Accept(IVisitor visitor);
}

and ask your types to implement this method

implementation

public class SuperType : ICondition {
	private ICondition _condition;
	public void Accept(IVisitor visitor) {
		_condition.Accept(visitor);
	}
}

public class One:ICondition {
	public void Accept(IVisitor visitor) {
		visitor.Visit(this);
	}
}

Call it !

Now we can remove our elseif conditions and replace it visitor pattern.

visitor pattern

public string Factory(ICondition condition) {
	SuperType superType = new SuperType();
	superType._condition = condition;
	GetStatus getStatus=new GetStatus();
	superType.Accept(getStatus);
	return getStatus.status;
}

We are making objects from our supportive class. Set the passing type and then passing the class that contains our business rules into the Accept method.

We can simply add more logic to class one and two or making more business class to use the real usage of this pattern.

Download

Feel free to download the source code of this example from my GitHub.