适配器设计模式(Adapter)


最易懂设计模式解析
模板方法设计模式
Mybatis代理设计模式
Mybatis多级代理

1. 认识适配器模式

1.1 模式定义

将某个类的接口转换成客户端期望的另一个接口表示。使得原本由于接口不兼容而不能一起工作的那些类能在一起工作。

1.2 解决何种问题

解决接口与接口实现类之间继承矛盾问题(在编程实现里面:当一个接口实现另一个接口的时候,有义务把接口中的方法都实现)。

1.3 模式特征

  • 使用抽象类分离了接口与接口实现。
  • 抽象类分摊接口中的方法。
  • 使得接口可以随意的选择接口中的方法来实现。

参考servlet规范中的genericServlet

2. 实例讲解

创建一个学生守则接口;

public interface 学生守则接口{
        // 不受实现类欢迎的实现方法
        public void 考试后家长签字();
        //受实现类欢迎的实现方法
        public void 每周免费看一次电影();
}

创建一个零食商贩(小学生干爹)

public abstract class 零食小商贩  implements 学生守则接口{
        @Override
        public void 考试后家长签字(){
                System.out.println("家长签字");
        }
}

创建一个小学类

public  class 小学生 extends 零食小商贩{
        @Override
        public void 每周去看一次电影(){
        System.out.println("去看电影");
        }
}

定义目标类,通过小学生类调用所需要的方法

public class TestMain{
        public static void main(String[] args){
        学生守则接口 target = new 小学生();
        target.考试后家长签字();
        target.每周免费看一次电影();
        }
}

抽象类实现接口的时候,对接口中的方法可以选择重写也可以选择不重写,不重写的方法由子类来完成。(目的降低接口开发的难度)

3. 适配器模式在servlet中的应用

下面直接看源码,发现GenericServlet是一个抽象类,它实现了Servlet接口,它把servlet一些不重要的方法(比较烦的方法)全部实现了,看下面destroy()、init()等大部分方法都是空实现。其service()是一个抽象方法,即把它处理请求的任务交给子类。子类必须实现该方法。

看下面GenericServlet的描述,简译就是,GenericServlet定义了一个通用的无关协议的Servlet。如果要在web应用中使用Http进行Servlet通信,请扩展HttpServlet。

package javax.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.ResourceBundle;

/**
 *
 * Defines a generic, protocol-independent
 * servlet. To write an HTTP servlet for use on the
 * Web, extend {@link javax.servlet.http.HttpServlet} instead.
 *
 * 

GenericServlet implements the Servlet * and ServletConfig interfaces. GenericServlet * may be directly extended by a servlet, although it's more common to extend * a protocol-specific subclass such as HttpServlet. * *

GenericServlet makes writing servlets * easier. It provides simple versions of the lifecycle methods * init and destroy and of the methods * in the ServletConfig interface. GenericServlet * also implements the log method, declared in the * ServletContext interface. * *

To write a generic servlet, you need only * override the abstract service method. * * * @author Various */ public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable { private static final String LSTRING_FILE = "javax.servlet.LocalStrings"; private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE); private transient ServletConfig config; /** * * Does nothing. All of the servlet initialization * is done by one of the init methods. * */ public GenericServlet() { } /** * Called by the servlet container to indicate to a servlet that the * servlet is being taken out of service. See {@link Servlet#destroy}. * * */ public void destroy() { } /** * Returns a String containing the value of the named * initialization parameter, or null if the parameter does * not exist. See {@link ServletConfig#getInitParameter}. * *

This method is supplied for convenience. It gets the * value of the named parameter from the servlet's * ServletConfig object. * * @param name a String specifying the name * of the initialization parameter * * @return String a String containing the value * of the initialization parameter * */ public String getInitParameter(String name) { ServletConfig sc = getServletConfig(); if (sc == null) { throw new IllegalStateException( lStrings.getString("err.servlet_config_not_initialized")); } return sc.getInitParameter(name); } /** * Returns the names of the servlet's initialization parameters * as an Enumeration of String objects, * or an empty Enumeration if the servlet has no * initialization parameters. See {@link * ServletConfig#getInitParameterNames}. * *

This method is supplied for convenience. It gets the * parameter names from the servlet's ServletConfig object. * * * @return Enumeration an enumeration of String * objects containing the names of * the servlet's initialization parameters */ public Enumeration getInitParameterNames() { ServletConfig sc = getServletConfig(); if (sc == null) { throw new IllegalStateException( lStrings.getString("err.servlet_config_not_initialized")); } return sc.getInitParameterNames(); } /** * Returns this servlet's {@link ServletConfig} object. * * @return ServletConfig the ServletConfig object * that initialized this servlet */ public ServletConfig getServletConfig() { return config; } /** * Returns a reference to the {@link ServletContext} in which this servlet * is running. See {@link ServletConfig#getServletContext}. * *

This method is supplied for convenience. It gets the * context from the servlet's ServletConfig object. * * * @return ServletContext the ServletContext object * passed to this servlet by the init * method */ public ServletContext getServletContext() { ServletConfig sc = getServletConfig(); if (sc == null) { throw new IllegalStateException( lStrings.getString("err.servlet_config_not_initialized")); } return sc.getServletContext(); } /** * Returns information about the servlet, such as * author, version, and copyright. * By default, this method returns an empty string. Override this method * to have it return a meaningful value. See {@link * Servlet#getServletInfo}. * * * @return String information about this servlet, by default an * empty string */ public String getServletInfo() { return ""; } /** * Called by the servlet container to indicate to a servlet that the * servlet is being placed into service. See {@link Servlet#init}. * *

This implementation stores the {@link ServletConfig} * object it receives from the servlet container for later use. * When overriding this form of the method, call * super.init(config). * * @param config the ServletConfig object * that contains configutation * information for this servlet * * @exception ServletException if an exception occurs that * interrupts the servlet's normal * operation * * @see UnavailableException */ public void init(ServletConfig config) throws ServletException { this.config = config; this.init(); } /** * A convenience method which can be overridden so that there's no need * to call super.init(config). * *

Instead of overriding {@link #init(ServletConfig)}, simply override * this method and it will be called by * GenericServlet.init(ServletConfig config). * The ServletConfig object can still be retrieved via {@link * #getServletConfig}. * * @exception ServletException if an exception occurs that * interrupts the servlet's * normal operation */ public void init() throws ServletException { } /** * Writes the specified message to a servlet log file, prepended by the * servlet's name. See {@link ServletContext#log(String)}. * * @param msg a String specifying * the message to be written to the log file */ public void log(String msg) { getServletContext().log(getServletName() + ": "+ msg); } /** * Writes an explanatory message and a stack trace * for a given Throwable exception * to the servlet log file, prepended by the servlet's name. * See {@link ServletContext#log(String, Throwable)}. * * * @param message a String that describes * the error or exception * * @param t the java.lang.Throwable error * or exception */ public void log(String message, Throwable t) { getServletContext().log(getServletName() + ": " + message, t); } /** * Called by the servlet container to allow the servlet to respond to * a request. See {@link Servlet#service}. * *

This method is declared abstract so subclasses, such as * HttpServlet, must override it. * * @param req the ServletRequest object * that contains the client's request * * @param res the ServletResponse object * that will contain the servlet's response * * @exception ServletException if an exception occurs that * interferes with the servlet's * normal operation occurred * * @exception IOException if an input or output * exception occurs */ public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; /** * Returns the name of this servlet instance. * See {@link ServletConfig#getServletName}. * * @return the name of this servlet instance */ public String getServletName() { ServletConfig sc = getServletConfig(); if (sc == null) { throw new IllegalStateException( lStrings.getString("err.servlet_config_not_initialized")); } return sc.getServletName(); } }

模仿上面写一个
建一个servlet类叫MyGenericServlet,实现servlet接口,实现里面的方法,留service()方法由他的子类来实现。

public abstract class MyGenericServlet implements Servlet{
    @Override
    public void destroy() { 
        // TODO Auto-generated method stub
    }

    @Override
    public ServletConfig getServletConfig() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void init(ServletConfig arg0) throws ServletException {
        
    }
}

创建一个OneServlet类

/**
 * Servlet implementation class OneServlet
 */
public class OneServlet extends MyGenericServlet {

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
        System.out.println("oneServlet is run..");
        
    }

}

可以测试localhost:8080/.../...

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