Adapter pattern
1. 定義?http://en.wikipedia.org/wiki/Adapter_pattern
An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. The adapter design pattern is used when you want two different classes with incompatible interfaces to work together. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.
2. 分類?http://en.wikipedia.org/wiki/Adapter_pattern
There are two types of adapter patterns:
Object Adapter pattern
In this type of adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped?object.
Class Adapter pattern
This type of adapter uses multiple?polymorphic interfaces?to achieve its goal. The adapter is created by implementing or inheriting both the interface that is expected and the interface that is pre-existing. It is typical for the expected interface to be created as a pure?interface?class, especially in?languages?such as?Java?that do not support?multiple inheritance.
??
?
3. 實例?http://blog.chinaunix.net/uid-29140694-id-4138579.html
? ?1. 類適配器
public interface Target {/*** 源角色也包含的方法*/public void operation1();/*** 原角色不包含的方法*/public void operation2(); }/*** 原角色實現類*/ public class Adaptee {public void operation1(){System.out.println("operation-1");} }/*** 適配器角色*/ public class Adapter extends Adaptee implements Target{@Overridepublic void operation2() {System.out.println("operation-2");} }? 2. 對象適配器
/*** 抽象目標接口*/ public interface Target {/*** 購買游戲道具*/public void buyGameProps(); } /*** 被適配對象 */ public class Rmb {/*** 金額屬性*/public int money;/*** 構造方法* @param money*/public Rmb(int money){this.money = money;}public int getMoney() {return money;}public void setMoney(int money) {this.money = money;}} /*** QQ幣實現類(適配器角色)*/ public class QQCoin implements Target{/*** 人民幣實體對象*/public Rmb rmbImpl;/*** QQ幣數量*/public int count;/*** 構造方法* @param rmb*/public QQCoin(Rmb rmb){this.count = rmb.getMoney() * 10;}/*** 具體實現方法*/@Overridepublic void buyGameProps() {System.out.println("您購買了 " + count + " 個道具!");}}/*** 測試Main方法*/ public class TestMain {public static void main(String [] args){Rmb rmb = new Rmb(5);QQCoin coin = new QQCoin(rmb);coin.buyGameProps();} }對象適配器的優點:
(1)適配器模式可以理解成是在原有基礎上的封裝,不需要對原有程序進行改動,即可實現特定功能。
(2)對象適配器可以服務于多個源角色,便于程序的擴展。
?
?
轉載于:https://www.cnblogs.com/davidwang456/p/3844925.html
總結
以上是生活随笔為你收集整理的Adapter pattern的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Decorator pattern
- 下一篇: command pattern