Press "Enter" to skip to content

Java设计模式—适配器模式(adapter pattern)

现在的手机很多都取消了3.5mm的耳机接口,只留下了一个type-c接口。但是我现在只有一个3.5mm圆孔接口的耳机,我不得不通过一个转接线使得3.5mm的耳机变成type-c接口。

//Type-C插座期望Type-C插头
class TypeCSocket {
    void connectWith(TypeCPlug plug){
        plug.connectTypeC();
    }
}
//Type-C插头的接口
Interface TypeCPlug {
    void connectTypeC();
}
//已有的3.5mm插头
class ThreeDotFivePlug {
    void connectThreeDotFive() { 
        System.out.println("Success to connect !");
    }
}
//使用类适配器方式进行适配
class Adapter1 extends threeDotFivePlug implements TypeCPlug {
    void connectTypeC() {
        connectThreeDotFive();
    }
}
//使用对象适配器方式进行适配
class Adapter2 implements TypeCPlug {
    ThreeDotFivePlug earphones = new ThreeDotFivePlug();
    void connectTypeC() {
        earphones.connectThreeDotFive();
    }
}
//使用
public class Test {
    public static void main(String[] args) {
        TypeCSocket socket = new TypeCSocket();
        TypeCPlug plug1 = new Adapter1();
        TypeCPlug plug2 = new Adapter2();
        socket.connectWith(plug1); //output: Success to connect !
        socket.connectWith(plug2); //output: Success to connect !
    }
}       

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax