首先设计一个目标类,然后设计一个适配器类,再来一个被适配器类,最后是主类。
如果适配器类继承了目标类,组合了被适配器类,那么这种称为对象适配器模式。
如果适配器类继承了被适配器类,实现了目标接口,那么这种称为类适配器模式。
下面是对象适配器的具体代码
目标类:
package com.freshbin.pattern.adapter.myexample.target;
/**
* LOL游戏
*
* @author freshbin
* @date 2019-1-5 20:11:41
*/
public class LOLGame {
public void winGame() {
System.out.println("五人抱团推爆地方水晶!");
}
}
被适配器类:
package com.freshbin.pattern.adapter.myexample.adaptee;
/**
* 王者荣耀游戏
*
* @author freshbin
* @date 2019-1-5 20:15:53
*/
public class GloryOfKingGame {
public void winGame() {
System.out.println("躺泉水喷对面喷对面就完事了!");
}
}
适配器类:
package com.freshbin.pattern.adapter.myexample.adapter;
import com.freshbin.pattern.adapter.myexample.adaptee.GloryOfKingGame;
import com.freshbin.pattern.adapter.myexample.target.LOLGame;
/**
* 王者荣耀游戏适配器
*
* @author freshbin
* @date 2019-1-5 20:15:08
*/
public class GloryOfKingGameAdapter extends LOLGame {
private GloryOfKingGame gameAdaptee;
public GloryOfKingGameAdapter(GloryOfKingGame gameAdaptee) {
this.gameAdaptee = gameAdaptee;
}
public void winGame() {
gameAdaptee.winGame();
}
}
再来一个类适配器模式
一个目标接口:
package com.freshbin.pattern.adapter.myexample.target;
/**
* LOL游戏接口
*
* @author freshbin
* @date 2019-1-5 20:11:41
*/
public interface LOLGameInterface {
public void winGame();
}
一个被适配器类
package com.freshbin.pattern.adapter.myexample.adaptee;
/**
* dota游戏
*
* @author freshbin
* @date 2019-1-5 20:28:18
*/
public class DotaGame {
public void winGame() {
System.out.println("我也没玩过这游戏,估计就是冲冲冲就完事了吧!");
}
}
一个适配器类
package com.freshbin.pattern.adapter.myexample.adapter;
import com.freshbin.pattern.adapter.myexample.adaptee.DotaGame;
import com.freshbin.pattern.adapter.myexample.target.LOLGameInterface;
/**
* dota游戏适配器
*
* @author freshbin
* @date 2019-1-5 20:15:08
*/
public class DotaGameAdapter extends DotaGame implements LOLGameInterface {
public DotaGameAdapter() {
}
public void winGame() {
super.winGame();
}
}
最后是主类
package com.freshbin.pattern.adapter.myexample;
import com.freshbin.pattern.adapter.myexample.adaptee.GloryOfKingGame;
import com.freshbin.pattern.adapter.myexample.adapter.DotaGameAdapter;
import com.freshbin.pattern.adapter.myexample.adapter.GloryOfKingGameAdapter;
import com.freshbin.pattern.adapter.myexample.target.LOLGame;
import com.freshbin.pattern.adapter.myexample.target.LOLGameInterface;
/**
* 适配器模式
*
* @author freshbin
* @date 2019-1-5 20:08:01
*/
public class AdapterMain {
public static void main(String[] args) {
GloryOfKingGame gofGame = new GloryOfKingGame();
LOLGame game = new GloryOfKingGameAdapter(gofGame);
game.winGame();
LOLGameInterface game2 = new DotaGameAdapter();
game2.winGame();
}
}
效果图: