首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计方式之(二)Adapter模式

2013-09-28 
设计模式之(二)Adapter模式今天学习Adapter模式,An adapter helps two incompatible interfaces to work t

设计模式之(二)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();
}
}


热点排行