设计模式之(二)Adapter模式

今天学习Adapter模式,An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

现在通过例子说明:

假设有2个类 Play和Walk

public class Play {
public void playPhone() {
System.out.println("play iphone");
}
}

public class Walk {
public void walk() {
System.out.println("I walk on the street");
}
}

现在需要一个适配器,使一个人一边走路一边玩手机

可以使得适配器继承其中一个类,然后将另一个类作为该适配器类的成员变量。

public class WalkAdapter {
private Play play;
public WalkAdapter(Play play) {
this.play = play;
}
public void play() {
return play.playPhone();
}
}


还可以采用多继承,但是Java没有多继承,只能通过接口实现。设置两个接口,分别让两个类实现接口。

public interface IPlay {
public void playPhone();
}
public interface IWalk {
public void walk();
}

public class Play implements IPlay{
@Override
public void playPhone() {
System.out.println("play iphone");
}
}


public class Walk implements IWalk{
@Override
public void walk() {
System.out.println("I walk on the street");
}
}

然后让Adapter实现2个接口,同时让2个类的对象作为Adapter的成员变量。

public class Adapter implements IWalk, IPlay {
private Play play;
private Walk walk;
public Adapter(Play play, Walk walk) {
this.play = play;
this.walk = walk;
}
public void play() {
return play.playPhone();
}
public void walk() {
return walk.walk();
}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值