设计模式——适配器模式
适配器模式也叫做包装模式;就是把内部结构包装(适配)成用户期待的格式,使得可以兼容使用
通过继承方式使用适配器模式
/** * @author maikec * @date 2019/5/9 */public interface Print {/** * 打印带括号的消息 */void printParen();/** * 打印带*号的消息 */void printAster(); }/** * 实际使用中的类 * @author maikec * @date 2019/5/9 */public class Banner {private final String msg;public Banner(String msg){this.msg = msg; }public void showWithParen(){ System.out.println( "(" + msg + ")" ); }public void showWithAster(){ System.out.println( "*" + msg + "*" ); } }/** * @author maikec * @date 2019/5/9 */public class PrintBannerAdapter extends Banner implements Print {public PrintBannerAdapter(String msg) {super( msg ); } @Overridepublic void printParen() { showWithParen(); } @Overridepublic void printAster() { showWithAster(); } }/** * @author maikec * @date 2019/5/9 */public class AdapterExtendDemo {public static void main(String[] args) { Print print = new PrintBannerAdapter( "hello adapter" ); print.printAster( ); print.printParen(); } }
通过引用使用适配器模式
/** * 需求 * @author maikec * @date 2019/5/9 */public abstract class Print {/** * 打印带括号的消息 */public abstract void printParen();/** * 打印带*号的消息 */public abstract void printAster();public void i(){ } }/** * 实际使用中的类 * @author maikec * @date 2019/5/9 */public class Banner {private final String msg;public Banner(String msg){this.msg = msg; }public void showWithParen(){ System.out.println( "(" + msg + ")" ); }public void showWithAster(){ System.out.println( "*" + msg + "*" ); } }/** * @author maikec * @date 2019/5/9 */public class PrintBannerAdapter extends Print {private Banner banner;public PrintBannerAdapter(Banner banner){this.banner = banner; } @Overridepublic void printParen() { banner.showWithParen(); } @Overridepublic void printAster() { banner.showWithAster(); } }/** * @author maikec * @date 2019/5/9 */public class AdapterReferenceDemo {public static void main(String[] args) { Print print = new PrintBannerAdapter( new Banner( "Hello Adapter" ) ); print.printAster(); print.printParen(); } }
附录
zh.wikipedia.org/wiki/适配器模式 维基关于适配器模式
github.com/maikec/patt… 个人GitHub设计模式案例
声明
引用该文档请注明出处
赞 (0)