工厂模式---多端应用切换

工厂模式实现多端应用切换

在这里插入图片描述
准备html页面

desktop的html

在这里插入代<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>这是PC端界面</h1>
</body>
</html>码片

mobile的html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>这是手机端界面</h1>
</body>
</html>

DesktopDevice类

package com.imooc.device;

public class DesktopDevice implements Device{
	public String getIndex() {
		return "/desktop/index.html";
	}
	
	public String getDescription() {
		return "/desktop/desc.html";
	}

}

MobileDevice类

package com.imooc.device;

public class MobileDevice implements Device {
	public String getIndex() {
		return "/mobile/index.html";
	}
	
	public String getDescription() {
		return "/mobile/desc.html";
	}
}

IndexServlet类

package com.imooc.servlet;

import java.io.IOException;

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 com.imooc.device.Device;
import com.imooc.device.DeviceFactory;

/**
 * Servlet implementation class indexServlet
 */
@WebServlet("/index.html")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Device d=DeviceFactory.getDevice(request);
		request.getRequestDispatcher(d.getIndex()).forward(request, response);
	}

}

接口类

package com.imooc.device;

public interface Device {
	public String getIndex() ;
	
	public String getDescription() ;
	
}

DeviceFactory工厂类

package com.imooc.device;

import javax.servlet.http.HttpServletRequest;

public class DeviceFactory {

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

结果:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值