读书人

Java设计形式之代理模式

发布时间: 2012-08-31 12:55:03 作者: rapoo

Java设计模式之代理模式

PROXY?(Object Structural)?
Purpose?
Allows for object level access control by acting as a pass through?
entity or a placeholder object.?
Use When?
1 The object being represented is external to the system.?
2 Objects need to be created on demand.?
3 Access control for the original object is required.?
4 Added functionality is required when an object is accessed.?
Example?
Ledger applications often provide a way for users to reconcile?
their bank statements with their ledger data on demand, automating?
much of the process. The actual operation of communicating?
with a third party is a relatively expensive operation that should be?
limited. By using a proxy to represent the communications object?
we can limit the number of times or the intervals the communication?
is invoked. In addition, we can wrap the complex instantiation?
of the communication object inside the proxy class, decoupling?
calling code from the implementation details.?
Java代码?

  1. package?javaPattern.proxy;??
  2. ??
  3. public?interface?Subject?{??
  4. ????public?void?request();??
  5. }??
  6. class?RealSubject?implements?Subject{??
  7. ??
  8. ????@Override??
  9. ????public?void?request()?{??
  10. ????????System.out.println("实际类的方法");??
  11. ??????????
  12. ????}??
  13. ??????
  14. }??
  15. class?Proxy?implements?Subject{??
  16. ????private?Subject?real;??
  17. ????public?Proxy(Subject?real){??
  18. ????????this.real?=?real;??
  19. ????}??
  20. ????@Override??
  21. ????public?void?request()?{??
  22. ????????System.out.println("代理以下方法");??
  23. ????????real.request();??
  24. ??????????
  25. ????}??
  26. ??????
  27. }??
  28. class?Client{??
  29. ????public?static?void?main(String[]?args)?{??
  30. ????????Proxy?proxy?=?new?Proxy(new?RealSubject());??
  31. ????????proxy.request();??
  32. ????}??
  33. } ?

读书人网 >软件开发

热点推荐