6.适配器设计模式
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了6.适配器设计模式,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1210字,纯文字阅读大概需要2分钟。
内容图文
public interface PinPlug{ void charge(); }
1.概述
适配器设计模式针对如下情况:-----客户需要用某个接口,但是能提供服务的接口没有实现那个接口。
- 客户端只能使用某种接口---客户端是台灯,接口是双孔插座
- 服务端----服务类是三孔插座
- 适配器类是服务类和客户端中间的一个桥接类---插线板
2.代码
适配器模式的分类:
- 类适配器----通过继承实现
- 对象适配器--通过组合实现
2.1类适配器
- 功能描述:为台灯充上电照明(台灯只能使用双孔插座)
-
public interface PinPlug{ void charge(); }
-
1.描述:与台灯配套的插座接口
-
public class ThreePinPlug{ public void specialcharge(){ System.out.println("三孔插座充电"); } }
- 2.描述:不能直接使用的三孔插座
-
public class PinPluginAdapter extends ThreePinPlug implements PinPlug{ public void charge(){ System.out.println("两孔桥接"); super.specialcharge(); } }
- 3.通过继承的方式创建一个把三孔转换为两空的类
-
public class Lamp { private PinPlug pinPlug; public Lamp(){ this.pinPlug=new PinPluginAdapter(); } public void Lignting() { if (pinPlug!=null) { pinPlug.charge(); System.out.println("照明"); }else{ System.out.println("没电"); } } public static void main(String[] args){ Lamp lamp=new Lamp(); lamp.Lignting(); } }
- 4.客户端:台灯
2.2对象适配器---组合的方式
-
public class PinPluginAdapter implements PinPlug{ ThreePinPlug threePinPlug=new ThreePinPlug(); public void charge(){ System.out.println("两孔桥接"); threePinPlug.specialcharge(); } }
3.分析
配器模式不适合在详细设计阶段使用它,它是一种补偿模式,专用来在系统后期扩展、修改时所用。
原文:http://www.cnblogs.com/yangyunnb/p/6478309.html
内容总结
以上是互联网集市为您收集整理的6.适配器设计模式全部内容,希望文章能够帮你解决6.适配器设计模式所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。