一.什么是代理?
代理就是在一个类的内部维护了一个对象的引用,使用这个对象引用来完成相应的功能。
代理和组合和继承一样仅仅是一种设计模式。
二.代理和组合以及继承的区别
代理既能完成组合的将一个类至于另外一个类中,同时还能像继承一样暴露其所有的方法,并在原来的方法上进行增加。
看一个例子:
我们现在需要一个汽车类,但是汽车的零部件太多,我们需要对其进行一个拆分。
那我们可以设定出一个发动机类,然后我们在汽车类中去代理这个发动机类。
代码如下:发动机类:
package com.cjm.reusable_class; public class Engine { private int v; private char f; public void start() { System.out.println("引擎发动!"); } public void addspeed() { v++; } public void removespeed() { v--; } public void turnleft() { System.out.println("发动机左转"); } public void turnrigth() { System.out.println("发动机右转"); } }
汽车类:
package com.cjm.reusable_class; /** * 在汽车类中去代理发动机类 * * @author 小明 * */ public class Car { private Engine e = new Engine();// 将引擎对象放置到汽车类中 public void start() { e.start(); System.out.println("汽车开动"); } public void addspeed() { e.addspeed(); System.out.println("汽车加速,并且滴滴滴"); } public void removespeed() { e.removespeed(); System.out.println("汽车减速,并且滴滴滴"); } public void turnleft() { System.out.println("汽车在打左转向灯,并且使"); e.turnleft(); } public void turnrigth() { System.out.println("汽车在打右转向灯,并且使"); } public static void main(String[] args) { Car car = new Car(); car.start(); car.addspeed(); car.turnleft(); } }
在汽车类中我们可以直接调用了发动机的方法,同样我们也可以获得汽车的字段。
这样的设计模式就是代理,相比于继承和组合这更加的简洁和直观。