设计模式之适配器模式
来源:互联网 发布:js json数组 某一个key 编辑:程序博客网 时间:2024/06/15 13:31
现实生活中一些适配器例子
例题:用火鸡冒充鸭子
适配器模式原理:
适配器模式:将一个类的接口转换成另一种接口.让原本接口不兼容的类可以兼容.
从用户的角度看不到被适配者,是解耦的
用户调用适配器转化出来的目标接口方法
适配器再调用被适配者的相关接口方法
用户收到反馈结果,感觉只是和目标接口交互
对象适配器
public class Turkey2DuckAdapter implements Duck{ private Turkey turkey; public Turkey2DuckAdapter(Turkey turkey) { this.turkey=turkey; } @Override public void quack() { turkey.gobble(); } @Override public void fly() { for (int i = 0; i < 3; i++) { turkey.fly(); } }}
类适配器
类适配器:通过多重继承目标接口和被适配者类方式来实现适配
多重继承,其中继承的目标接口部分达到适配目的,而继承被适配者类的部分达
到通过调用被适配者类里的方法来实现目标接口的功能
public class Turkey2DuckClassAdapter extends WildTurkey implements Duck{ @Override public void quack() { super.gobble(); } @Override public void fly() { for (int i = 0; i < 3; i++) { super.fly(); } }}
对象适配器与类适配器差异
实际应用:从java枚举器到迭代器的适配
public class Enumeration2Iteration implements Iterator<Object>{ private Enumeration<Object> enumeration; @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public Object next() { return enumeration.nextElement(); } @Override public void remove() { throw new UnsupportedOperationException(); }}
实际应用2:Java的SynchronizedMap
/** * @serial include */ private static class SynchronizedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final Map<K,V> m; // Backing Map final Object mutex; // Object on which to synchronize SynchronizedMap(Map<K,V> m) { this.m = Objects.requireNonNull(m); mutex = this; } SynchronizedMap(Map<K,V> m, Object mutex) { this.m = m; this.mutex = mutex; } public int size() { synchronized (mutex) {return m.size();} } public boolean isEmpty() { synchronized (mutex) {return m.isEmpty();} } public boolean containsKey(Object key) { synchronized (mutex) {return m.containsKey(key);} } public boolean containsValue(Object value) { synchronized (mutex) {return m.containsValue(value);}
code Address
http://download.csdn.net/detail/kaikai_sk/9873278
阅读全文
0 0
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器
- 设计模式 之 适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之--适配器模式.
- mongodb启动时报错ERROR: child process failed, exited with error number 1
- HDU
- Swift
- CentOS6.5下安装Redis2.8.7
- [勇者闯LeetCode] 191. Number of 1 Bits
- 设计模式之适配器模式
- 代码整洁之道-第六章-对象和数据结构-page87
- [LeetCode]611. Valid Triangle Number
- Spring注解@Resource和@Autowired区别对比
- Mysql常用技巧
- Swift
- Kotlin与dagger2
- iOS纯代码实现界面建立、跳转、导航栏(无storyboard、无nib)(Objective-C)
- Swift