|
Visitor Design Pattern |
|
2. Visitor Design Pattern
The design pattern provides additional
functionality to a class. The Visitor pattern
allows us to create an external class to act on
data in other classes. This is useful in those
conditions if a fair number of instances are available of small number of classes and we
have to perform some operations on all or on
most of those classes.
Lets take an example that demonstrates that
how the classes implement the Visitor interface.
In the following example we are taking the two
interfaces one is Visitor interface and the other
is Colddrink interface and then we implement
to these interfaces into our classes.
import java.util.*;
interface Visitor {
public void visit(Colddrink cld_drnk);
}
interface Colddrink {
public String Order();
}
class Pepsi implements Colddrink {
final String name = “Pepsi”;
public String Order() {
return name;
}
}
class CocaCola implements Colddrink {
final String name = “Coke”;
public String Order() {
return name;
}
}
class Pickup implements Visitor {
private String name;
private final String method = “Pick and
Go”;
public void visit(Colddrink cld_drnk) {
name = cld_drnk.Order();
}
public String toString() {
return name + “ “ + method;
}
} |
|
class Drinkthere implements Visitor {
private String name;
private final String method = “Take the
drink over there”;
public void visit(Colddrink cld_drnk) {
name = cld_drnk.Order();
}
public String toString() {
return name + “ “ + method;
}
}
class GetByDelivery implements Visitor {
private String name;
private final String method = “Get it by
delivery”;
public void visit(Colddrink cld_drnk) {
name = cld_drnk.Order();
}
public String toString() {
return name + “ “ + method;
}
}
class Drink {
public Colddrink getDrink() {
switch ((int)(Math.random()*3)){
case 0: return new Pepsi();
case 1: return new CocaCola();
default: return null;
}
}
public Visitor howto() {
switch ((int)(Math.random()*3)){
case 0: return new Pickup();
case 1: return new Drinkthere();
case 2: return new GetByDelivery();
default: return null;
}
}
}
class TestVisitors {
public static void main(String[] args) {
List colddrinkList = new ArrayList();
colddrinkList.add(new Pepsi());
colddrinkList.add(new CocaCola());
Iterator it = colddrinkList.iterator();
|
|
Mar 2008 | Java Jazz Up | 38 |
|
|
|
View All Topics |
All Pages of this Issue |
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
Download PDF |
|
|
|
|
|
|
|
|
|