- 適配器模式:
簡(jiǎn)單將就是將A轉(zhuǎn)換成B,比如:美國(guó)電器 110V,中國(guó) 220V紧阔,就要有一個(gè)適配器將 110V 轉(zhuǎn)化為 220V.JDBC等.
優(yōu)點(diǎn):提高了類的復(fù)用
缺點(diǎn):過(guò)多地使用適配器,會(huì)讓系統(tǒng)非常零亂壁拉,不易整體進(jìn)行把握泊柬。比如仅醇,明明看到調(diào)用的是 A 接口,其實(shí)內(nèi)部被適配成了 B 接口的實(shí)現(xiàn)昼钻,一個(gè)系統(tǒng)如果太多出現(xiàn)這種情況掸屡,無(wú)異于一場(chǎng)災(zāi)難,所以適配器不是在詳細(xì)設(shè)計(jì)時(shí)添加的,而是解決正在服役的項(xiàng)目的問(wèn)題换吧。
java8接口可以用 default關(guān)鍵字,也就是接口能添加默認(rèn)方法,很多時(shí)候缺 省適配器模式 也就可以退出歷史舞臺(tái)了
代碼示例:
先上類圖:
TextShapeObject.png
- 定義一個(gè)被適配的對(duì)象
Text
package com.byedbl.adapter;
/**
* The Adaptee in this sample
*/
public class Text {
private String content;
public Text() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
- 定義一個(gè)接口類
package com.byedbl.adapter;
/**
* A interface
*/
public interface Shape {
void draw();
void border();
}
- 為了把Text類適配成有接口類
Shape
方法該怎么辦?
有兩種方法,
方法一:通過(guò)類繼承
package com.byedbl.adapter;
/**
* The Class Adapter in this sample
*/
public class TextShapeClass extends Text implements Shape {
public TextShapeClass() {
}
public void draw() {
System.out.println("Draw a shap ! Impelement Shape interface !");
}
public void border() {
System.out.println("Set the border of the shap ! Impelement Shape interface !");
}
public static void main(String[] args) {
TextShapeClass myTextShapeClass = new TextShapeClass();
myTextShapeClass.draw();
myTextShapeClass.border();
myTextShapeClass.setContent("A test text !");
System.out.println("The content in Text Shape is :" + myTextShapeClass.getContent());
}
}
這樣TextShapeClass
既有Text
類的功能也有Shape
接口的功能
方法二:通過(guò)實(shí)現(xiàn)接口
package com.byedbl.adapter;
/**
* The Object Adapter in this sample
*/
public class TextShapeObject implements Shape {
private Text txt;
public TextShapeObject(Text t) {
txt = t;
}
public void draw() {
System.out.println("Draw a shap ! Impelement Shape interface !");
}
public void border() {
System.out.println("Set the border of the shap ! Impelement Shape interface !");
}
public void setContent(String str) {
txt.setContent(str);
}
public String getContent() {
return txt.getContent();
}
public static void main(String[] args) {
Text myText = new Text();
TextShapeObject myTextShapeObject = new TextShapeObject(myText);
myTextShapeObject.draw();
myTextShapeObject.border();
myTextShapeObject.setContent("A test text !");
System.out.println("The content in Text Shape is :" + myTextShapeObject.getContent());
}
}
實(shí)現(xiàn)接口也要實(shí)現(xiàn)Text的方法,雖然示例只是代理一下,但是還是要保留Text應(yīng)有的功能,不然就不是一個(gè)Text了.