-
Notifications
You must be signed in to change notification settings - Fork 2
/
ProxyCodingExercise.java
84 lines (70 loc) · 1.73 KB
/
ProxyCodingExercise.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Given a Person class, implement a ResponsiblePerson proxy that does the following:
- Allows person to drink unless they are younger than 18 ("too young")
- Allows person to drive unless they are younger than 16 ("too young")
- In case of driving while drinking, returns "dead"
*/
package structural.proxy.exercise;
class Person
{
private int age;
public Person(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String drink() { return "drinking"; }
public String drive() { return "driving"; }
public String drinkAndDrive() { return "driving while drunk"; }
}
class ResponsiblePerson
{
private Person person;
public ResponsiblePerson(Person person)
{
this.person = person;
}
public String drink()
{
if (person.getAge() <= 18) return "too young";
else return person.drink();
}
public String drive()
{
if (person.getAge() <= 16) return "too young";
else return person.drive();
}
public String drinkAndDrive()
{
return "dead";
}
public int getAge()
{
return person.getAge();
}
public void setAge(int age)
{
person.setAge(age);
}
}
class ProxyExercise
{
public static void main(String[] args) {
Person p = new Person(10);
ResponsiblePerson rp = new ResponsiblePerson(p);
System.out.println(rp.drink());
System.out.println(rp.drive());
System.out.println(rp.drinkAndDrive());
rp.setAge(20);
System.out.println(rp.drink());
System.out.println(rp.drive());
System.out.println(rp.drinkAndDrive());
}
}