GOF设计模式之适配器(Adapter)模式与代理模式(Proxy pattern)
适配器(Adapter)模式
将一个类的接口转换成客户希望的另外一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
需要被适配的类
1 | /** |
适配器
1 | /** |
接口
1 | public interface Target { |
测试
1 | public class Client { |
结果
可以完成需求功能
代理模式(Proxy pattern)
通过代理,控制对对象的访问。
静态代理
接口
1 | public interface Star { |
真实对象
1 | public class RealStar implements Star{ |
代理对象
1 | public class ProxyStar implements Star{ |
测试
1 | public class Client { |
结果
ProxyStar.confer()
ProxyStar.signContract()
ProxyStar.bookTicket()
RealStar(本人唱歌).sing()
ProxyStar.collectMoney()
动态代理
类接口和RealStar方法与上方一致
实现InvocationHandler接口
1 | public class StarHandler implements InvocationHandler{ |
测试
1 | public class Client { |
结果
RealStar(本人唱歌).sing()