设计模式-适配器模式(五)

  • 适配器模式:
    简单将就是将A转换成B,比如:美国电器 110V,中国 220V,就要有一个适配器将 110V 转化为 220V.JDBC等.
    优点:提高了类的复用
    缺点:过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现,一个系统如果太多出现这种情况,无异于一场灾难,所以适配器不是在详细设计时添加的,而是解决正在服役的项目的问题。

java8接口可以用 default关键字,也就是接口能添加默认方法,很多时候缺 省适配器模式 也就可以退出历史舞台了

代码示例:
先上类图:


TextShapeObject.png
  • 定义一个被适配的对象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;
    }
}
  • 定义一个接口类
package com.byedbl.adapter;

/**
 *  A interface
 */
public interface Shape  {
    void draw();
    void border();
}
  • 为了把Text类适配成有接口类Shape方法该怎么办?
    有两种方法,
    方法一:通过类继承
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接口的功能
方法二:通过实现接口

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

实现接口也要实现Text的方法,虽然示例只是代理一下,但是还是要保留Text应有的功能,不然就不是一个Text了.

你可能感兴趣的:(设计模式-适配器模式(五))