适配器模式

适配器模式主要是为了在不能改变现有类的情况下,将一个类转换成另一种类,让他可以适应一个通用的接口

public interface Printable {

    void printSth();

}



public class Printer implements Printable {

    @Override

    public void printSth() {

        System.out.println("I can print text");

    }

}



public class Photogragher {

    public void printPhoto(){

        System.out.println("I can print photogragh");

    }

}



public class PhotogragherAdapter implements Printable {

    private Photogragher p = null;

    

    public PhotogragherAdapter(Photogragher p) {

        this.p = p;

    }

    

    @Override

    public void printSth() {

        p.printPhoto();

    }

}



public class Client {

    public static void test(Printable p) {

        p.printSth();

    }

    

    public static void main(String[] args) {

        Printable printer = new Printer();

        Photogragher photogragher = new Photogragher();

        PhotogragherAdapter adapter = new PhotogragherAdapter(photogragher);

        test(printer);

        test(adapter);

    }

}

此处的目的就是在不修改Photogragher类的前提下让Photographer也能适用于 Clinet.test() 方法

你可能感兴趣的:(适配器模式)