工厂模式实现多端应用切换
准备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;
}
}
}
结果: