您的位置:首页 > 编程语言 > Java开发

java代理

2015-09-30 09:59 351 查看
java并没有提供对代理的直接支持。这是继承与组合之间的中庸之道。

示例:飞机的控制模块

public class PlaneControls{
void up (int distance){}
void down(int distance){}
void left(int distance){}
void right(int distance){}
void forward(int distance){}
}
构造飞机的一种方式是基础控制模块。

public class Plane extends PlaneControls{
private String name;
Public Plane(String name){this.name = name;)
public static void main(String[] args){
Plane p =new Plane("歼-31");
p.forward(1000);
}
}

虽然通过继承可以实现飞机的这些功能,但是Plane并非真正的PlaneControls,这样总感觉不是很合理,然而代理可以解决这一问题。

public class PlaneDemo{
private String name;
private PlaneControls controls = new PlaneControls();//定义另一个类的引用
public void PlaneDemo(String name){
this.name = name;
}
public void up (int distance){
controls.up(distance);
}
public void down (int distance){
controls.down(distance);
}
public void left (int distance){
controls.left(distance);
}
public void right(int distance){
controls.right(distance);
}
public void forward(int distance){
controls.forward(distance);
}
代理是继承与组合的结合,在新类中定义另一个类的引用,通过引用调用方法(controls.up(distance);)从而实现新类也有此功能。我们使用带来可以拥有更多的控制了,因为我们可以选择只提供在成员对象中的方法的某个子集。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: