代理模式

为其他对象提供一种代理以控制对这个对象的访问.

1
2
3
4
5
6
7
8
9
10
11
package proxy;

/**
* Created by hero on 17-2-17.
*/
public interface Policy {
void giveFlowers();
void giveTickets();
void drinkMoreWater();
}

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
package proxy;

/**
* Created by hero on 17-2-17.
*/
public class Pursuer implements Policy {
private SchoolGirl girl;

public Pursuer(SchoolGirl girl) {
this.girl = girl;
}

public void giveFlowers() {
System.out.println("give " + girl.getName() + " flowers.");
}

public void giveTickets() {
System.out.println("give " + girl.getName() + " tickets.");
}

public void drinkMoreWater() {
System.out.println("persuade " + girl.getName() + " drink more water.");
}
}

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
package proxy;

/**
* Created by hero on 17-2-17.
*/
public class Proxy implements Policy {
private Pursuer pursuer;

public Proxy(SchoolGirl girl) {
this.pursuer = new Pursuer(girl); //school美眉与真正追求她的gg不认识.
}

public void giveFlowers() {
pursuer.giveFlowers();
}

public void giveTickets() {
pursuer.giveTickets();
}

public void drinkMoreWater() {
pursuer.drinkMoreWater();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package proxy;

/**
* Created by hero on 17-2-17.
*/
public class SchoolGirl {
private String name;

public SchoolGirl(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package proxy;

/**
* Created by hero on 17-2-17.
*/
public class Main {
public static void main(String[] args) {
SchoolGirl lucy = new SchoolGirl("lucy");
Proxy daili = new Proxy(lucy);

daili.giveFlowers();
daili.giveTickets();
daili.drinkMoreWater();
}
}

代理模式UML