java - Visitor design pattern intent : misleading or I am missing something? -
in reference book "design patterns elements of reusable object-oriented software" gang of four, intent of visitor pattern explained follow :
represent operation performed on elements of object structure. visitor lets define new operation without changing classes of elements on operates.
another advantage read visitor pattern that:
add new operation without having source code of classes..
i made deep search in google, did not find example showing how that. let's take simple example :
public interface myinterface { public void mymethod(); } public class myclassa implements myinterface { /* (non-javadoc) * @see com.mycomp.tutorials.designpattern.behavorials.myinterface#mymethoda() */ public void mymethod() { system.out.println("mymethoda implemented in myclassa"); } } public class myclassb implements myinterface { /* (non-javadoc) * @see com.mycomp.tutorials.designpattern.behavorials.myinterface#mymethoda() */ public void mymethod() { system.out.println("mymethod implemented in myclassb"); } }
so how add new method mynewmethod()
hierarchy of classes without changing them, using visitor pattern?
let's have message class, , 2 subclasses email , sms.
you have many operations on these 2 classes, sendtooneperson()
, sendtoseveralpeople()
. don't want have these methods in email , sms class directly, because tightly couples them smtp/phone system. , able add other operations in futre, forward() or delete(), or whatever. first implementation use is
public void delete(message message) { if (message instanceof email) { deleteemail(email) message); } else if (message instanceof sms) { deletesms((sms) message); } }
but ugly: it's not object-oriented, , fail if there new voicemessage subclass appearing.
an alternative use visitor pattern.
public interface messagevisitor { void visitemail(email email); void visitsms(sms sms); } public abstract class message { public void accept(messagevisitor visitor); } public class email extends message { @override public void accept(messagevisitor visitor) { visitor.visitemail(this); } } public class sms extends message { @override public void accept(messagevisitor visitor) { visitor.visitsms(this); } }
this way, implement send(), need messagevisitor implementation can send email , send sms:
sendmessagevisitor visitor = new sendmessagevisitor(); message.accept(visitor);
and if introduce new delete() operation, don't have touch message classes @ all. need deletemessagevisitor:
deletemessagevisitor visitor = new deletemessagevisitor(); message.accept(visitor);
so, basically, it's bit if added polymorphic methods message classes not modifying message classes.
Comments
Post a Comment