设计模式之适配器模式

概述

将一个类的接口转化为客户希望的另外的一个接口,使得原本由于接口不兼容而不能一起工作的那些类一起工作。

结构

  • 目标接口:当前业务所期待的接口
  • 适配者类:需要适配的类或适配者类。
  • 适配器类:通过继承或者引用适配者的对象,把适配者接口转化为目标接口。
//目标接口
interface SdCard{
	String sdread();
	void sdwrite(String msg);
}
interface TfCard{
	String tfread();
	void tfwrite(String msg);
}
//适配者
class TfCardImpl implements TfCard{
	public String tfread(){
		System.out.println("read tfcard");
	}
	public void tfwrite(String msg){
		System.out.println("write tfcard:"+msg);
	}
}

类适配器(采用继承的方式实现)

public SdAdapterTF extends TfCardImpl implements SdCard{
	public String sdread(){
		tfread();
	}
	public void sdwrite(String msg){
		tfwrite(msg);
	}
}

对象适配器(采用对象组合的方式实现)

public SdAdapterTF implements SdCard{
	private TfCard tfcard;
	public SdAdapterTf(TfCard tfcard){
		this.tfcard=tfcard;
	} 
	public String sdread(){
		tfcard.tfread();
	}
	public void sdwrite(String msg){
		tfcard.tfwrite(msg);
	}
}

jdk中的源码

在这里插入图片描述
StreamDecoder对构造方法的字节流进行了封装,并通过该类实现了字节流和字符流之间的解码转化.

接口适配器

接口中定义了多个抽象方法,定义该适配器的子类时,子类只实现其中的部分抽象方法。
它适用于一个接口不想使用其所有的方法的情况。因此也称为单接口适配器模式。

servlet和GenericServlet

public interface Servlet {
    void init(ServletConfig var1) throws ServletException;

    ServletConfig getServletConfig();

    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

    String getServletInfo();

    void destroy();
}
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
	 private static final long serialVersionUID = 1L;
    private transient ServletConfig config;
    
    public GenericServlet() {
    }

    public void destroy() {
    }

    public ServletConfig getServletConfig() {
        return this.config;
    }

    public String getServletInfo() {
        return "";
    }

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
    public void init() throws ServletException {
    }

    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值