适配器模式

维基百科


在设计模式中,适配器模式(英语:adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类能在一起工作,做法是将类自己的接口包裹在一个已存在的类中。


球员抽象类

public abstract class Player {

    protected String name;

    public Player(String name) {
        this.name = name;
    }

    public abstract void attack();
    public abstract void defense();

}

前锋

public class Forwards extends Player{
     

    public Forwards(String name) {
        super(name);
    }

    @Override
    public void attack() {
        System.out.println(super.name + "前锋进攻");
    }

    @Override
    public void defense() {
        System.out.println(super.name + "前锋防守");
    }
}

中锋

public class Center extends Player{
     
    public Center(String name) {
        super(name);
    }

    @Override
    public void attack() {
        System.out.println(super.name + "中锋进攻");
    }

    @Override
    public void defense() {
        System.out.println(super.name + "中锋防守");
    }
}

后卫

public class Guards extends Player{
     
    public Guards(String name) {
        super(name);
    }

    @Override
    public void attack() {
        System.out.println(super.name + "后卫进攻");
    }

    @Override
    public void defense() {
        System.out.println(super.name + "后卫防守");
    }
}

外籍球员

public class ForeignCenter extends Player{
     

    public ForeignCenter(String name) {
        super(name);
    }

    @Override
    public void attack() {
        System.out.println(name + "外籍中锋进攻");
    }

    public void defense() {
        System.out.println(name + "外籍中锋防守");
    }

}

翻译

public class Translator extends Player{
     

    //持有一个外籍球员对象
    private ForeignCenter foreignCenter = new ForeignCenter(name);

    public Translator(String name) {
        super(name);
    }

    @Override
    public void attack() {
        foreignCenter.attack();
    }

    @Override
    public void defense() {
        foreignCenter.defense();
    }
}

客户端

public class Client {

    public static void main(String[] args) {
        Player b = new Forwards("巴蒂尔");
        b.attack();

        Player m = new Guards("麦克格雷迪");
        m.attack();

        Player ym = new Translator("姚明");
        ym.attack();
        ym.defense();

    }

}

你可能感兴趣的:(java,设计模式,设计模式)