Visitor Pattern
This commit is contained in:
23
design-pattern/src/Visitor/Application.java
Normal file
23
design-pattern/src/Visitor/Application.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package Visitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
|
||||
ArrayList<Visitable> visitables = new ArrayList<Visitable>();
|
||||
visitables.add(new VisitableA(1));
|
||||
visitables.add(new VisitableA(2));
|
||||
visitables.add(new VisitableA(3));
|
||||
visitables.add(new VisitableA(4));
|
||||
visitables.add(new VisitableA(5));
|
||||
|
||||
Visitor visitor = new VisitorA();
|
||||
|
||||
for (Visitable visitable: visitables) {
|
||||
visitable.accept(visitor);
|
||||
}
|
||||
|
||||
System.out.println(((VisitorA)visitor).getAgeSum());
|
||||
}
|
||||
}
|
||||
5
design-pattern/src/Visitor/Visitable.java
Normal file
5
design-pattern/src/Visitor/Visitable.java
Normal file
@@ -0,0 +1,5 @@
|
||||
package Visitor;
|
||||
|
||||
public interface Visitable {
|
||||
void accept(Visitor visitor);
|
||||
}
|
||||
23
design-pattern/src/Visitor/VisitableA.java
Normal file
23
design-pattern/src/Visitor/VisitableA.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package Visitor;
|
||||
|
||||
public class VisitableA implements Visitable{
|
||||
|
||||
private int age;
|
||||
|
||||
public VisitableA(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Visitor visitor) {
|
||||
visitor.visit(this);
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
||||
2
design-pattern/src/Visitor/Visitor
Normal file
2
design-pattern/src/Visitor/Visitor
Normal file
@@ -0,0 +1,2 @@
|
||||
Visitor Pattern
|
||||
- 객체에서 처리 분리하기
|
||||
5
design-pattern/src/Visitor/Visitor.java
Normal file
5
design-pattern/src/Visitor/Visitor.java
Normal file
@@ -0,0 +1,5 @@
|
||||
package Visitor;
|
||||
|
||||
public interface Visitor {
|
||||
void visit(Visitable visitable);
|
||||
}
|
||||
25
design-pattern/src/Visitor/VisitorA.java
Normal file
25
design-pattern/src/Visitor/VisitorA.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package Visitor;
|
||||
|
||||
public class VisitorA implements Visitor{
|
||||
|
||||
private int ageSum;
|
||||
|
||||
public VisitorA() {
|
||||
ageSum = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(Visitable visitable) {
|
||||
if(visitable instanceof VisitableA) {
|
||||
|
||||
ageSum += ((VisitableA) visitable).getAge();
|
||||
|
||||
} else {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public int getAgeSum() {
|
||||
return ageSum;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user