I have one Antivirus visitor that has two states (scanning and disinfecting) and visits computers and a Name visitor that visits with viruses and assigns them random names generated from several arrays and Random.nextInt().
To implement the visitor pattern, you first need to decide what objects will be the visitees and provide setters and getters for any state changes that need to be performed by the visitor. Then you have to add an acceptVisitor(Visitor v) method to each visitee class that tells the visitor v to visit it. You should create a visitor interface that has methods for visiting each class of visitee and implement this in each of your visitors. In each visitor, you must implement the methods in the visitor interface and then can perform actions on the visitee.
Antivirus seemed like a natural place for the visitor pattern because it allowed me to simplify my project considerably. Previously I had an instance of antivirus that was 'owned' by each computer, but the visitor allowed me to pull out all that code and replace it with the acceptVisitor methods.
I used the singleton pattern in my project to ensure that only one instance my Antvirus visitor and Network class would be created because there was no need for multiple instances of them. The singleton is a very short pattern that creates an instance of the class if none exists and then returns that instance, or if it already exists, just returns it.
No comments:
Post a Comment