当前位置: 首页 > news >正文

设计模式(适配器模式)

设计模式(适配器模式)

第二章 设计模式之适配器模式(Adapter)

一、Adapter模式介绍

在这里插入图片描述
适配器模式位于实际情况和需求之间,填补两者之间的差距。

二、示例程序1(使用继承的适配器)

1.示例程序示意图

在这里插入图片描述
程序表示输入hello字符串,输出为(hello)或者*hello*的简单程序。
扮演适配器角色的是PrintBanner类。该类继承了Banner类并实现了“需求”–Print接口。

2.Banner类

package cn.pp.adapter.extend;public class Banner {private String str;public Banner(String str) {this.str = str;}public void showWithParen() {System.out.println("(" + str + ")");}public void showWithAster() {System.out.println("*" + str + "*");}
}

3.Print类

public interface Print {public void printWeak();public void printStrong();
}

4.PrintBannerAdapter类

public class PrintBannerAdapter extends Banner implements Print {public PrintBannerAdapter(String str) {super(str);}@Overridepublic void printWeak() {showWithParen();}@Overridepublic void printStrong() {showWithAster();}
}

5.Main类

   public static void main(String[] args) {Print print = new PrintBannerAdapter("我是适配器");print.printStrong();print.printWeak();}

二、示例程序2(使用委托的适配器)

1.示例程序示意图

在这里插入图片描述
如果类Print不是一个接口而是一个类,由于java不能多继承,所以只有采用委托的适配器模式。
PrintBanner类中的banner字段保存了Banner类的示例,通过构造函数注入。

2.Banner类

package cn.pp.adapter.extend;public class Banner {private String str;public Banner(String str) {this.str = str;}public void showWithParen() {System.out.println("(" + str + ")");}public void showWithAster() {System.out.println("*" + str + "*");}
}

3.Print类

public abstract class Print {public abstract  void printWeak();public abstract  void printStrong();
}

4.PrintBannerAdapter类

public class PrintBannerAdapter extends Print {private Banner banner;public PrintBannerAdapter(String str) {this.banner = new Banner(str);}@Overridepublic void printWeak() {banner.showWithParen();}@Overridepublic void printStrong() {banner.showWithAster();}
}

5.Main类

   public static void main(String[] args) {Print print = new PrintBannerAdapter("我是适配器");print.printStrong();print.printWeak();}
http://www.lryc.cn/news/8008.html

相关文章:

  • 在基于全志D1s的芒果派麻雀上运行国产开源rt-smart系统
  • 【代码随想录训练营】【Day15】第六章|二叉树|层序遍历|226.翻转二叉树|101.对称二叉树
  • 基于圆展开自适应三边测量算法的室内定位
  • 使用中断子系统实现对LED灯的控制
  • 《爆肝整理》保姆级系列教程python接口自动化(十五)--参数关联接口(详解)
  • 【JDK8】MyBatis源码导入Idea
  • 三层交换机DHCP中继
  • C++之RALL机制
  • 回溯算法章末总结
  • 【SpringBoot】为异步任务规划线程池
  • SAP ABAP 输出结果带有空格
  • Opengl ES之踩坑记
  • 设计模式第六讲:责任链模式和迭代器模式详解
  • K8s 架构简介(一)
  • xshell6运行报错:由于找不到mfc110u.dll、MSVCR110.dll无法继续执行代码
  • Baklib知识库管理平台,协助组织提升知识管理水平
  • 一文搞懂core-scheduling核心机制
  • IP地址在金融行业有哪些应用?
  • GT-suite v2016解决许可证过期问题(附新版liscense下载地址)
  • 小红书商业笔记与普通笔记区别是什么?小红书笔记有哪几种
  • DataWhale-统计学习方法打卡Task01
  • Java面试——Spring 事务
  • Python语言零基础入门教程(十九)
  • 重生之我是赏金猎人-SRC漏洞挖掘(一)-某SRC测试系统无脑Getshell
  • Sciter 结合 PReact 实现组件公共逻辑抽离
  • OpenTracing协议规范链接
  • 金三银四面试必看,自动化测试如何解决日志问题
  • 微信怎么开小店?【企业商家微信开店】
  • Java 中FastJson的使用【吃透FastJson】
  • Redis5.0集群搭建