侧边栏壁纸
博主头像
Epoch

Java开发、Python爬虫、微服务、分布式、前端

  • 累计撰写 93 篇文章
  • 累计创建 110 个标签
  • 累计收到 8 条评论

目 录CONTENT

文章目录

运用简单工厂模式编写多端适配

Epoch
2021-02-07 / 0 评论 / 0 点赞 / 292 阅读 / 354 字 / 正在检测是否收录...

运用简单工厂模式编写多端适配

编写一个设备接口

package com.xmaven.device;

/**
 * @ClassName Device
 * @Description TODO
 * @Author Ambition
 * @Date 2021/2/7 15:03
 * @Version 1.0.0
 **/
public interface Device {

    public String getIndex();

    public String getDescription();

}

以桌面设备和手机设备为例

package com.xmaven.device;

/**
 * @ClassName DeskTopDevice
 * @Description TODO
 * @Author Ambition
 * @Date 2021/2/7 15:00
 * @Version 1.0.0
 **/
public class DeskTopDevice implements Device{

    @Override
    public String getIndex(){
        return "/desktop/index.html";
    }

    @Override
    public String getDescription(){
        return "/desktop/des.html";
    }

}
package com.xmaven.device;

/**
 * @ClassName MobileDevice
 * @Description TODO
 * @Author Ambition
 * @Date 2021/2/7 15:02
 * @Version 1.0.0
 **/
public class MobileDevice implements Device{

    @Override
    public String getIndex(){
        return "/mobile/index.html";
    }

    @Override
    public String getDescription(){
        return "/mobile/des.html";
    }

}

编写一个设备工厂类

package com.xmaven.device.factory;

import com.xmaven.device.DeskTopDevice;
import com.xmaven.device.Device;
import com.xmaven.device.MobileDevice;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName DeviceFactory
 * @Description TODO
 * @Author Ambition
 * @Date 2021/2/7 15:04
 * @Version 1.0.0
 **/
public class DeviceFactory {

    public static Device getDevice(HttpServletRequest request){
        String userAgent = request.getHeader("user-agent");
        System.out.println(userAgent);
        if (userAgent.contains("Windows NT")){
            return new DeskTopDevice();
        }else if (userAgent.contains("iPhone")||userAgent.contains("Android")){
            return new MobileDevice();
        }else {
            return null;
        }
    }
}

编写一个Servlet来进行测试

package com.xmaven.servlet;

import com.xmaven.device.Device;
import com.xmaven.device.factory.DeviceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName DeviceServlet
 * @Description TODO
 * @Author Ambition
 * @Date 2021/2/7 15:16
 * @Version 1.0.0
 **/
@WebServlet("/index.html")
public class DeviceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Device device = DeviceFactory.getDevice(req);
        req.getRequestDispatcher(device.getIndex()).forward(req,resp);
    }
}
0

评论区