kishanvshah007/SOEN-6471-Winter-2014-ProjectMilestone-4 — pull request #1 by ruixiangTanConcordia (2014-04-07 19:02:59+00:00)
Title: Multiple if statements - chain of instanceof expressions - refactoring used Visitor Pattern

Multiple if statements, chain of “instanceof” expressions

Location: NotificationDisplayFactory Class in notifications Package
![visitor](https://cloud.githubusercontent.com/assets/6843606/2635595/1f6c9dba-be87-11e3-92c4-7e3c284abdec.jpg)

Problem: Chains of if statements and all of whose conditions are “instanceof” expressions. Such constructions usually indicate a failure of object-oriented design, which dictates that such type-based dispatch should be done via polymorphic method calls rather than explicit chains of type tests.

Solution: Visitor pattern (https://en.wikipedia.org/wiki/Visitor_pattern)
Originally, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. (Wikipedia) However, this pattern suits our case due to its major characteristic: “double dispatch”. In our case, statement “notification instanceof XXXNotification” is the first dispatch decided at run time. According to the TYPE of notification object, the program has different “return new XXXNotificationFrame()”, that can be considered the second dispatch. After refactoring, if we need to ADD a new type of “notification” or new behaviors, we won’t break the present code.

Mechanics: The visitor pattern looks complicated, but since the actual class structure highly match this pattern and due to writing space limitation, we will briefly go through it.

(1)	rename interface “UINotification” to “INotificationElement”, and ADD a new empty method “accept(INotificationElementVisitor visitor)” in this interface
(2)	Since Class AlertNotification, UpdateCheckNotification…already implement “UINotification”, we just need to implement the NEW “accept(INotificationElementVisitor visitor) { visitor.visit(this);}” method in each derived class.
(3)	Create a new interface called “INotificationElementVisitor” with following empty method: visit(AlertNotification alertNotification); visit(UpdateCheckNotification updateCheckNotification)…
(4)	Create a new class called “NotificationElementVisitor” and implement the new interface “INotificationElementVisitor”, different visit(XXXNotification XXX) with different “return new XXXNotificationFrame()”

Finally, the code snippets we saw, all if statement will gone:
notification.accept (new NotificationElementVisitor (frame));