Hongbo

Oct 11, 2023

浅谈代理模式

写在前头:希望你了解到的不仅是模式,而学会用OOP的眼光分析问题,解决问题

关键字:控制

描述: 通过实现相同接口(保证行为相同),通过组合方式,对被代理者实现控制

原则: 单一职责

区别: 代理模式强调在非功能性方面的控制,装饰模式强调加强同一类功能

示例: 买票,代理点,远程访问

代码实现:

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
//票的接口
public interface Ticket {
public double showFee();
}

//真正的对象
public class RealTrainTicket implements Ticket {
//实际价格
private double fee=10;
//返回实际价格
@Override
public double showFee() {
return this.fee;
}
}

//代理对象
public class ProxyTrainTicket implements Ticket {
//被代理的对象
private Ticket tt;
public ProxyTrainTicket() {
this.tt= new RealTrainTicket();
}
//经过代理之后的价格
@Override
public double showFee() {
return this.tt.showFee()*1.2;
}

//test
public static void main(String[] args) {
Ticket realtrainticket= new RealTrainTicket();
System.out.println("RealTrainTicket's fee is "+realtrainticket.showFee());
System.out.println();

Ticket proxytrainticket= new ProxyTrainTicket();
System.out.println("proxytrainticket's fee is "+ proxytrainticket.showFee());
}
}
OLDER > < NEWER