设计模式---Adapter模式

来源:互联网 发布:双系统 安装 ubuntu 编辑:程序博客网 时间:2024/06/11 14:06

adapter模式:
1.隶属类型:结构模式

2.种类

两种:

Class adapter :extends+implements

Object adapter :aggregation+implements

(个人认为还有 implements+implements)

2.使用条件:
a.两个没有关系的类组合在一起使用,第一解决方案是:修改各自类的接口,
但是如果我们没有源代码,或者,我们不愿意为了一个应用而修改各自的接口。 怎么办?
使用Adapter,在这两种接口之间创建一个混合接口(混血儿).
b.需完成的类其他人已完成相似的,重用的同时需要继承新的属性

3:基本思想:连接两个接口,先继承一个,再用聚合,或者抽象出其借口,实现两个接口,再用这两个接口的聚合.
总之 extends+aggregation

4:示例:

a:
public interface Shape  {
//接口之一
    public void Draw();
    public void Border();
}


public class Text  {
//接口之二
    private String content;
    public Text() {
       
    }
    public void SetContent(String str) {
        content = str;
    }
    public String GetContent() {
        return content;
    }
}


public class TextShapeClass  extends Text implements Shape {
//Class adapter
//直接用继承,重用Text的method(extends),同时实现shape的功能(implements)
    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());
    }
}


public class TextShapeObject  implements Shape {
//Object adapter
//aggregation Text是接口的聚合对象,同时实现shape的功能(implements)

    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());
       
    }
}

原创粉丝点击