Achieve closure by using Visitor

Using Visitor to decouple ordering stuff

When I and teammate design class, we always apply OCP and fight not to make the design smells.
We prefer use interface to obtain it but in current project, we faced with a new problem, it made our design violates the OCP.
The book Principles, Pattern and Practices [Martin] provides an approach that uses a Data-Driven way to achieve closure. It works well but seem not to be nice. The author of the book also recommends an alternate solution that uses Visitor pattern. So, in this blog, I’ll show you the way it is.
Problem:
Suppose that we have an interface IItemDetailInformation

interface IItemDetailInformation

{

string SequenceOrder {get; set;}

// other properties

}

and now have 3 implementation classes: AllItemDetailInformation, CategoryDetailInformation, ProductDetailInformation.
Now, Our requirement is defined. If we have a List<IItemDetailInformation>, it must be sorted in following order:

AllItemDetailInformation is in the top of list.
– Order by SequenceOrder (a decimal that be formated in 10 characters) in ascendant sequence.
– If SequenceOrder are equal, CategoryDetailInformation is before UserDetailInformation.

Solution:
Create an Visitor interface

interface IOrderVisitor

{

ActorDetailComparerInfo Visit(IActorDetailInformation actorDetailInfo);

}

So we have: AllItemOrderVisitor, CategoryOrderVisitor, ProductOrderVisitor.
Now, we define class ActorDetailComparerInfo, used to store order information.

class ItemDetailComparerInfo : IComparable

{

int TypeOrder;

string SequenceOrder;

public int CompareTo(ItemDetailComparerInfo obj)

{

return ComparatorUtility.Compare(this, obj,

new string{“SequenceOrder“, “TypeOrder”});

}

}

Now, we create class ItemDetailInformationComparer to decouple the ordering stuff and IItemDetailInformation.
class ItemDetailInformationComparer : IComparer

{

int CompareTo(object x, object y)

{

IOrderVisitor xOV = (x as IItemDetailInformation).OrderVisitor;

IOrderVisitor yOV = (y as IItemDetailInformation).OrderVisitor;

return xOV.Visit(x).CompareTo(yOV.Visit(y));

}

}

Final work is very simple:

List itemList = GetItemList();

itemList.Sort(new ItemDetailInformationComparer());

Your feedbacks are very important!
Nguyen Minh Dung

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: