大话设计模式-----适配器模式

1、思想

通过适配类,将需要适配的类转换为与其他的类实现同样的接口,从而使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

2、何时使用该设计模式

想使用一个已经存在的类,但如果它的接口,但也就是它的方法和你的要求不相同时,就应该考虑用适配器模式。

3、举例说明适配器模式(篮球翻译适配器)

public interface Player{

    void attack();

    void defense();

}

//前锋

public class Forwards implents Player{

    public void attack(){

            System.out.println("前锋进攻”);

    }

    public void defense(){

            System.out.println("前锋防守”);

    }

}

//外籍中锋

public class ForeignCenter{

    public void 进攻(){

            System.out.println("外籍人员进攻”);

    }

    public void 防守(){

            System.out.println("外籍人员前锋防守”);

    }

}

//适配器

public class Translator implents Player{

    private ForeignCenter wjzf = new ForeignCenter();

    public void attack(){

              wjzf.进攻();

    }

    public void defense(){

               wjzf. 防守();

    }

}

4、代码结构图



猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/80791441