What is the usage of the IVisitable interface in Visitor Pattern?

时间:2016-10-20 12:58:37

标签: java design-patterns

Im really trying to understand the importance of this interface, but beside helping us to write more quickly, the methods in the concrete classes (by only implementing the methods) I just can't find the need to use it.

The definition is this

an abstraction which declares the accept operation. This is the entry point which enables an object to be "visited" by the visitor object. Each object from a collection should implement this abstraction in order to be able to be visited

." Its clear, but still you can manualy write those accept methods in every single class(which is lot of unnecessary work I agree) but still beside that you can get a class to be visitable, without the IVisitable interface...

//IVisitable.java
package Visitor;

/**
*
* @author dragan
*/
public interface IVisitable {                 
    public void accept (Visitor v); 
}

// Bgirl.java

public class Bgirl implements  IVisitable{

    int _br_godina;

    public Bgirl(int g) {
        br_godina = g;
    }

    public int getBr_godina() {
        return _br_godina;
    }

    public void accept (Visitor v){        
        v.visit(this);            
    }

}

// Main.java

package Visitor;

/**
*
* @author dragan
*/
public class Main {

    public static void main(String[] args) {

        Bgirl terra = new Bgirl(5);  

        System.out.println(terra.getBr_godina());

        VisitorImplement v = new VisitorImplement();              

    }  
}

// VisitorImplement.java

package Visitor;

/**
 *
 * @author dragan
 */
public class VisitorImplement implements Visitor{

    @Override
    public void visit(Bgirl prva) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

      prva._br_godina = 3;

    }

//    @Override
//    public void visit(Bboy prvi) {
//       // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
//        System.out.println("BBOY VISIT");
//    
//    }
//    


}

1 个答案:

答案 0 :(得分:0)

查看您的main()方法:您可以直接拨打terra._br_godina = 3,因此无需使用任何访问者。

如果您不了解terra的具体类型,甚至不知道应该调用哪种方法来满足您的愿望,那么访问者就非常有用。你只拥有一个抽象类型或界面,例如Girl(或IVisitable)。因此,为了证明访问者模式的有用性,您的main()方法应该是这样的:

public static void main(String[] args) {
    IVisitable terra = new Bgirl(5);
    // Want to set _br_godina of terra to 3 but do not and cannot know
    // which method should be called
    // Let's create a visitor and let him visit her,
    // he knows how to set _br_godina of her to 3
    VisitorImplement v = new VisitorImplement();
    terra.accept(v); // luckily, every girl accepts the "accept()"
}