Adapter适配器模式

    技术2022-05-11  87

    我有一台笔记本电脑,但是我想接着电源用,交流电是220v,我电脑是19v,我总不能直接就插上去用吧,我需要一种装置可以让我19v的电脑用上220v的交流电,厂家给我配了变压器,用术语讲就是适配器。

    适配器模式有两种实现方式,一种是继承,另一种是委托。

    先看继承方式:

    /** * Banner.java<br> * 原有类,此类相当于交流电压220v * @author cool * */public class Banner { private String s; public Banner(String s) {  this.s=s; } /**  * 将字符串放在小括号内输出,减弱的意思  */ public String showWithParen() {  return "("+s+")"; } /**  * 将字符串前后都加星号输出,加强的意思  */ public String showWithAster() {  return "*"+s+"*"; }}

    /** * Print.java<br> * 要使用的接口,相当于直流电12v电压 * @author cool * */public interface Print { /**  * 减弱输入  */ public abstract String printWeak(); /**  * 加强输出  */ public abstract String printStrong();}

    /** * PrintBanner.java<br> * 变压器,就是一个适配器 * @author cool * */public class PrintBanner extends Banner implements Print { public PrintBanner(String s) {  super(s); } /**  * 加强输出  */ public String printStrong() {  return super.showWithAster(); } /**  * 减弱输入  */ public String printWeak() {  return super.showWithParen(); }}

    import static org.junit.Assert.*;

    import org.junit.*;

    /** * 测试用例 * @author cool * */public class PrintTest { private Print p; @Before public void setUp() throws Exception {  p=new PrintBanner("hello"); }

     @After public void tearDown() throws Exception { }

     @Test public void testPrintWeak() {  assertEquals("AssertionError","(hello)",p.printWeak()); }

     @Test public void testPrintStrong() {  assertEquals("AssertionError","*hello*",p.printStrong()); }

    }

     

    下面是委托,其实适配器就是使用引用或称聚合:

    /** * Banner.java<br> * 原有类,此类相当于交流电压220v * @author cool * */public class Banner { private String s; public Banner(String s) {  this.s=s; } /**  * 将字符串放在小括号内输出,减弱的意思  */ public String showWithParen() {  return "("+s+")"; } /**  * 将字符串前后都加星号输出,加强的意思  */ public String showWithAster() {  return "*"+s+"*"; }}

    /** * Print.java<br> * 改为抽象类,相当于直流电12v电压 * @author cool * */public abstract class Print { /**  * 减弱输入  */ public abstract String printWeak(); /**  * 加强输出  */ public abstract String printStrong();}

    /** * PrintBanner.java<br> * 变压器,就是一个适配器 * @author cool * */public class PrintBanner extends Print { private Banner banner; public PrintBanner(String s) {  banner=new Banner(s); } /**  * 加强输出  */ public String printStrong() {  return banner.showWithAster(); } /**  * 减弱输入  */ public String printWeak() {  return banner.showWithParen(); }}

    import static org.junit.Assert.*;

    import org.junit.*;

    /** * 测试用例 * @author cool * */public class PrintTest { private Print p; @Before public void setUp() throws Exception {  p=new PrintBanner("hello"); }

     @After public void tearDown() throws Exception { }

     @Test public void testPrintWeak() {  assertEquals("AssertionError","(hello)",p.printWeak()); }

     @Test public void testPrintStrong() {  assertEquals("AssertionError","*hello*",p.printStrong()); }

    }


    最新回复(0)