NBA之适配器模式

108 阅读1分钟

Design Pattern:

Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces.

模式: 适配器是用来兼容两个不同类型的接口,属于结构模式

故事场景:现在骑士VS勇士,教练说:如果勇士落后1分的话,就让杜兰特最后来个两分的暴扣,如果落后2分的话,就让库里来个3分远投

public interface Player {

    public void play(int score);
}

public class Durant implements Player{
    @Override
    public void play(int score) {
        System.out.println("暴扣"+score+"分");
    }
}

public class Curry implements Player{
    @Override
    public void play(int score) {
        System.out.println("远投"+score+"分");
    }
}
public class Adapter {

    Player player = null;

    public void play(int type){

        if (type == 2){
            player = new Durant();
            player.play(2);
        }else if (type == 3){
            player = new Curry();
            player.play(3);
        }
    }
}
public class AdapterDemo {

    public static void main(String[] args) {

        Adapter adapter = new Adapter();
        adapter.play(3);
        adapter.play(2);
    }
}