适配器模式

  • 两个类所做的事相同或相似,但是具有不同的接口.
  • 想使用一个已存在的类,但是其方法名与你要求的不同.
  • 必要时.
1
2
3
4
5
6
7
8
9
package adapter;

/**
* Created by hero on 17-2-19.
*/
public abstract class Player {
public abstract void attack();
}

1
2
3
4
5
6
7
8
9
10
11
package adapter;

/**
* Created by hero on 17-2-19.
*/
public class Forward extends Player {
public void attack() {
System.out.println("attack");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package adapter;

/**
* Created by hero on 17-2-19.
*/
public class PlayerAdapter extends Player {
private ForeignPlayer foreignPlayer;

public PlayerAdapter(ForeignPlayer foreignPlayer) {
this.foreignPlayer = foreignPlayer;
}

/** 适配 */
public void attack() {
foreignPlayer.进攻();
}
}

1
2
3
4
5
6
7
8
9
10
11
package adapter;

/**
* Created by hero on 17-2-19.
*/
public class ForeignPlayer {
public void 进攻() {
System.out.println("进攻");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package adapter;

/**
* Created by hero on 17-2-19.
*/
public class Main {
public static void main(String[] args) {
Player meixi = new Forward();

ForeignPlayer yaoming = new ForeignPlayer();
Player foreigner = new PlayerAdapter(yaoming);

meixi.attack();
foreigner.attack();
}
}