写在前头:希望你了解到的不仅是模式,而学会用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; } 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()); } }
|