JAVA设计模式之【适配器模式】

适配器模式    当不需要实现一个接口所提供的所有方法时,可先设计一个抽象类该接口,并为接口每个方法提供一个默认实现    该抽象类的子类可以选择性地覆盖父类的某些方法来实现需求    角色        适配者接口            通常在接口中声明了大量的方法        缺省适配器类            可以用空方法的形式实现接口中声明的方法        具体业务类            缺省适配器类的子类

1.机器人接口

package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public interface Robot {
    public void cry();
    public void move();
}

2.鸟类与鸟类适配器

package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class Bird {
    public void tweedle()
    {
        System.out.println("鸟儿叽叽叫!");
    }

    public void fly()
    {
        System.out.println("鸟儿快快飞!");
    }
}
package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class BirdAdapter extends Bird implements Robot{
    public void move() {
        System.out.print("机器人模仿:");
        super.fly();
    }

    public void cry() {
        System.out.print("机器人模仿:");
        super.tweedle();
    }

}

3.狗类与狗类适配器

package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class Dog
{
    public void wang()
    {
        System.out.println("小狗汪汪汪!");
    }

    public void run()
    {
        System.out.println("小狗跑跑跑!");
    }
}
package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class DogAdapter extends Dog implements Robot{
    public void cry() {
        System.out.println("机器人模仿:");
        super.wang();
    }

    public void move() {
        System.out.println("机器人模仿:");
        super.run();
    }
}

4.客户端

package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class Client
{
    public static void main(String args[])
    {
        Robot robot= new BirdAdapter();
        robot.cry();
        robot.move();
    }
}

执行结果
机器人模仿:鸟儿叽叽叫!
机器人模仿:鸟儿快快飞!

继续进行

5.创建机器鸟类继承鸟类适配器

package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class RobotBird extends BirdAdapter{
    public void cry() {
        System.out.println("我是机器鸟:叽叽叽");
    }
}

说明,它继承适配器之后,就没必要实现所有的机器接口了。只需要根据使用情况,覆盖适配器中的方法。

修改客户端

package Adapter;

/**
 * Created by e550 on 2016/10/3.
 */
public class Client
{
    public static void main(String args[])
    {
        Robot robot= new RobotBird();
        robot.cry();
        robot.move();
    }
}

执行结果

我是机器鸟:叽叽叽
机器人模仿:鸟儿快快飞!



本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5929238.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值