结构型模式:结构型对象模式不是对接口或实现进行组合的.而是描述了如何对一些对象进行组合,从而实现新功能的一些方法.
adapter适合:将一个类的接口转换成客户所需要的另一个接口,使原本由于接口不兼容,不能一块工作的类多能一块工作.
使用情况:1、你想使用一个已经存在的类,而它的接口不符合你的要求。
2、你想创建一个可以复用的类,该类与其它的类或者接口协同工作。
代码:
package structure.adapter;
/**
* A interface
*/
public interface Shape {
public void Draw();
public void Border();
}
package structure.adapter;
/**
* The Adaptee in this sample
*/
public class Text {
private String content;
public Text() {
}
public void SetContent(String str) {
content = str;
}
public String GetContent() {
return content;
}
}
package structure.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());
}
}
package structure.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());
}
}