java代理

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);)从而实现新类也有此功能。我们使用带来可以拥有更多的控制了,因为我们可以选择只提供在成员对象中的方法的某个子集。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值