在这里,我们将给大家分享关于Java-基于Web的DesignPatterns应用程序的知识,让您更了解基于java的web应用程序设计的本质,同时也会涉及到如何更有效地18Javadesignpat
在这里,我们将给大家分享关于Java-基于Web的Design Patterns应用程序的知识,让您更了解基于java的web应用程序设计的本质,同时也会涉及到如何更有效地18 Java design pattern questions.、com.intellij.uiDesigner.designSurface.ListenerNavigateButton的实例源码、Design Patterns - Adapter Pattern(译)、Design Patterns - Bridge Pattern(译)的内容。
本文目录一览:- Java-基于Web的Design Patterns应用程序(基于java的web应用程序设计)
- 18 Java design pattern questions.
- com.intellij.uiDesigner.designSurface.ListenerNavigateButton的实例源码
- Design Patterns - Adapter Pattern(译)
- Design Patterns - Bridge Pattern(译)
Java-基于Web的Design Patterns应用程序(基于java的web应用程序设计)
我正在设计一个简单的基于Web的应用程序。我是这个基于Web的领域的新手,我需要您提供有关设计模式的建议,例如如何在Servlet之间分配职责,创建新Servlet的标准等。
实际上,我主页上的实体很少,而与每个实体相对应,我们几乎没有添加,编辑和删除等选项。早些时候,我为每个选项使用一个Servlet,例如Servlet1用于添加实体1,Servlet2用于编辑实体1,依此类推,这样我们最终拥有大量的Servlet。
现在,我们正在更改设计。我的问题是,如何正确选择如何选择servlet的责任。每个实体是否应该有一个Servlet,它将处理所有选项并将请求转发到服务层。还是应该为整个页面设置一个servlet,它将处理整个页面请求,然后将其转发到相应的服务层?同样,请求对象是否应该转发到服务层。
答案1
小编典典有点像样的Web应用程序由多种设计模式组成。我只会提到最重要的那些。
模型视图控制器模式
你要使用的核心(架构)设计模式是Model-View-Controller模式。该控制器是由一个Servlet其中(在)直接创造来表示/使用特定的模型和视图基于该请求。该模型将由Javabean类表示。在包含动作(行为)的业务模型和包含数据(信息)的数据模型中,这通常可以进一步划分。该视图是由具有对(直接访问JSP文件来表示数据)模型由EL(表达式语言)。
然后,根据操作和事件的处理方式而有所不同。最受欢迎的是:
基于请求(动作)的MVC:这是最简单的实现。(业务)模型直接与HttpServletRequest
和HttpServletResponse
对象一起使用。你必须自己(主要)收集,转换和验证请求参数。该视图可以用普通的HTML / CSS / JS
表示,并且不会在请求中保持状态。这就是Spring MVC,Struts
和Stripes
的工作方式。
基于组件的MVC:这很难实现。但是最终你得到了一个更简单的模型和视图,其中所有“原始” Servlet API都被完全抽象了。你不需要自己收集,转换和验证请求参数。所述控制器执行此任务,并设置在所收集的,转换后的和验证请求参数模型。你需要做的就是定义直接与模型属性一起使用的操作方法。该视图是通过“组件”在JSP标记库或依次产生HTML / CSS / JS的XML元素的风味表示。视图的状态在会话中维护后续请求。这对于服务器端转换,验证和值更改事件特别有用。这就是JSF,Wicket和Play的方式!作品。
附带说明,业余学习本地的MVC框架是一个非常不错的学习方法,只要你出于个人/私人目的保留它,我建议你这样做。但是一旦你成为专业人士,那么强烈建议你选择一个现有的框架,而不要重塑自己的框架。学习现有的和完善的框架所需的时间要比自己开发和维护一个健壮的框架花费的时间少。
在下面的详细说明中,我将自己限制为基于请求的MVC,因为它更易于实现。
前控制器模式(调解器模式)
首先,Controller部分应实现Front Controller模式(这是一种专门的Mediator模式)。它应该仅由一个servlet组成,该servlet提供所有请求的集中入口点。它应该创建模型基于由请求,如PATHINFO或servletpath,该方法和/或特定的参数可用信息。该商业模式被称为Action
在下面的HttpServlet
例子。
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Action action = ActionFactory.getAction(request); String view = action.execute(request, response); if (view.equals(request.getPathInfo().substring(1)) { request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response); } else { response.sendRedirect(view); // We''d like to fire redirect in case of a view change as result of the action (PRG pattern). } } catch (Exception e) { throw new ServletException("Executing action failed.", e); }}
执行该操作应返回一些标识符以定位视图。最简单的方法是将其用作JSP
的文件名。将此servlet
映射到特定url-pattern的web.xml
,例如/pages/*,*.do
甚至*.html
。
在前缀模式,例如情况下,/pages/*
你可以然后调用URL就像http://example.com/pages/register,http://example.com/pages/login
等,提供/WEB-INF/register.jsp,/WEB-INF/login.jsp
使用适当的GET和POST行为。然后,如上例所示,可以使用部件register,login
等等request.getPathInfo()
。
当你使用后缀模式,比如*.do,*.html等
等,那么你可以然后调用URL的喜欢http://example.com/register.do,http://example.com/login.do
,等你应该改变此答案中的代码示例(也包括ActionFactory
)来提取register
和login
部分request.getServletPath()
。
策略模式
本Action应遵循的策略模式。需要将其定义为抽象/接口类型,该类型应基于抽象方法的传入参数来完成工作(这与Command模式不同,其中抽象/接口类型应基于在实现的创建过程中传入的参数)。
public interface Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
你可能希望Exception使用像这样的自定义异常进行更具体的说明ActionException。这只是一个基本的启动示例,其余的全由你决定。
这是一个LoginAction(如其名称所示)登录用户的示例。该User本身又一个数据模型。该视图是知道的存在User。
public class LoginAction implements Action { public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = userDAO.find(username, password); if (user != null) { request.getSession().setAttribute("user", user); // Login user. return "home"; // Redirect to home page. } else { request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope. return "login"; // Go back to redisplay login form with error. } }}
工厂方法模式
本ActionFactory应遵循工厂方法模式。基本上,它应该提供一种创建方法,该方法返回抽象/接口类型的具体实现。在这种情况下,它应该Action根据请求提供的信息返回接口的实现。例如,方法和pathinfo(pathinfo是请求URL中上下文和servlet路径之后的部分,不包括查询字符串)。
public static Action getAction(HttpServletRequest request) { return actions.get(request.getMethod() + request.getPathInfo());}
该actions反过来应该是一些静态/应用程序范围Map
actions.put("POST/register", new RegisterAction());actions.put("POST/login", new LoginAction());actions.put("GET/logout", new LogoutAction());// ...
或可基于类路径中的属性/ XML配置文件进行配置:(伪)
for (Entry entry : configuration) { actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());}
或动态地基于对类路径的扫描来实现实现特定接口和/或注释的类:(伪)
for (ClassFile classFile : classpath) { if (classFile.isInstanceOf(Action.class)) { actions.put(classFile.getAnnotation("mapping"), classFile.newInstance()); }}
请记住,在Action没有映射的情况下创建“不执行任何操作” 。让它例如直接返回request.getPathInfo().substring(1)then
。
其他图案
这些是到目前为止的重要模式。
要更进一步,你可以使用Facade模式创建一个Context类,该类依次包装请求和响应对象,并提供几个委托给请求和响应对象的便捷方法,并将其作为参数传递给该Action#execute()方法。这增加了一个额外的抽象层以隐藏原始Servlet API。然后,你基本上应该在每个实现中都以零 import javax.servlet.*
声明结束Action。用JSF术语,这是FacesContext和ExternalContext类的作用。你可以在此答案中找到一个具体示例。
然后是一种情况下的状态模式,你想添加一个额外的抽象层来拆分收集请求参数,转换请求,验证请求,更新模型值和执行操作的任务。用JSF术语,这LifeCycle就是这样做的。
然后,有一个Composite模式用于你要创建基于组件的视图,该视图可以随模型一起附加,并且其行为取决于基于请求的生命周期的状态。用JSF术语UIComponent表示。
通过这种方式,你可以逐步向基于组件的框架发展。
18 Java design pattern questions.
1. When to use Strategy Design Pattern in Java?Strategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules. This pattern follow open closed design principle and quite useful in Java. One example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface , which is a strategy interface and defines strategy for comparing objects. Because of this pattern, we don''t need to modify sort() method (closed for modification) to compare any object, at same time we can implement Comparator interface to define new comparing strategy (open for extension).
2. What is Observer design pattern in Java? When do you use Observer pattern in Java?
This is one of the most common Java design pattern interview question. Observer pattern is based upon notification, there are two kinds of object Subject and Observer. Whenever there is change on subject''s state observer will receive notification. See What is Observer design pattern in Java with real life example for more details.
3. Difference between Strategy and State design Pattern in Java?
This is an interesting Java design pattern interview questions as both Strategy and State pattern has same structure. If you look at UML class diagram for both pattern they look exactly same, but there intent is totally different. State design pattern is used to define and mange state of object, while Strategy pattern is used to define a set of interchangeable algorithm and let''s client to choose one of them. So Strategy pattern is a client driven pattern while Object can manage there state itself.
4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular java design pattern question which is common because of its heavy usage in java.io package. BufferedReader and BufferedWriter are good example of decorator pattern in Java. See How to use Decorator pattern in Java fore more details.
5. When to use Composite design Pattern in Java? Have you used previously in your project?
This design pattern question is asked on Java interview not just to check familiarity with Composite pattern but also, whether candidate has real life experience or not. Composite pattern is also a core Java design pattern, which allows you to treat both whole and part object to treat in similar way. Client code, which deals with Composite or individual object doesn''t differentiate on them, it is possible because Composite class also implement same interface as there individual part. One of the good example of Composite pattern from JDK is JPanel class, which is both Component and Container. When paint() method is called on JPanel , it internally called paint() method of individual components and let them draw themselves. On second part of this design pattern interview question, be truthful, if you have used then say yes, otherwise say that you are familiar with concept and used it by your own. By the way always remember, giving an example from your project creates better impression.
6. What is Singleton pattern in Java?
Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole application. java.lang.Runtime is good example of Singleton pattern in Java. There are lot''s of follow up questions on Singleton pattern see 10 Java singleton interview question answers for those followups
7. Can you write thread-safe Singleton in Java?
There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using double checked locking, by using static Singleton instance initialized during class loading. By the way using Java enum to create thread-safe singleton is most simple way. See Why Enum singleton is better in Java for more details.
8. When to use Template method design Pattern in Java? Template pattern is another popular core Java design pattern interview question. I have seen it appear many times in real life project itself. Template pattern outlines an algorithm in form of template method and let subclass implement individual steps. Key point to mention, while answering this question is that template method should be final, so that subclass can not override and change steps of algorithm, but same time individual step should be abstract, so that child classes can implement them.
9. What is Factory pattern in Java? What is advantage of using static factory method to create object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java interviews.Factory pattern used to create object by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to introduce new objects etc. See What is Factory pattern in Java and benefits for more details.
10. Difference between Decorator and Proxy pattern in Java? Another tricky Java design pattern question and trick here is that both Decorator and Proxy implements interface of the object they decorate or encapsulate. As I said, many Java design pattern can have similar or exactly same structure but they differ in there intent. Decorator pattern is used to implement functionality on already created object, while Proxy pattern is used for controlling access to object. One more difference between Decorator and Proxy design pattern is that, Decorator doesn''t create object, instead it get object in it''s constructor, while Proxy actually creates objects.
11. When to use Setter and Constructor Injection in Dependency Injection pattern?
Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory dependency of an object, without which it can not work. This question is related to Dependency Injection design pattern and mostly asked in context of Spring framework, which is now become an standard for developing Java application. Since Spring provides IOC container, it also gives you way to specify dependencies either by using setter methods or constructors. You can also take a look my previous post on same topic.
12. What is difference between Factory and Abstract factory in Java
see here to answer this Java design pattern interview question.
13. When to use Adapter pattern in Java? Have you used it before in your project?
Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter pattern can also be used to encapsulate third party code, so that your application only depends upon Adapter, which can adapt itself when third party code changes or you moved to a different third party library. By the way this Java design pattern question can also be asked by providing actual scenario.
14. Can you write code to implement producer consumer design pattern in Java?
Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple way. if you are working in Java 5 then its better to use Concurrency util to implement producer consumer pattern instead of plain old wait and notify in Java . Here is a good example of implementing producer consumer problem using BlockingQueue in Java .
15. What is Open closed design principle in Java?
Open closed design principle is one of the SOLID principle defined by Robert C. Martin, popularly known as Uncle Bob. This principle advices that a code should be open for extension but close for modification. At first this may look conflicting but once you explore power of polymorphism, you will start finding patterns which can provide stability and flexibility of this principle. One of the key example of this is State and Strategy design pattern, where Context class is closed for modification and new functionality is provided by writing new code by implementing new state of strategy. See this article to know more about Open closed principle.
16. What is Builder design pattern in Java? When do you use Builder pattern ?
Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews because of its specific use when you need to build an object which requires multiple properties some optional and some mandatory. See When to use Builder pattern in Java for more details
17. Can you give an example of SOLID design principles in Java?
There are lots of SOLID design pattern which forms acronym SOLID, read this list of SOLID design principles for Java programmer to answer this Java interview question.
18. What is difference between Abstraction and Encapsulation in Java?
I have already covered answer of this Java interview question in my previous post as Difference between encapsulation and abstraction in Java . See there to answer this question.
This was my list of 10 popular design pattern interview question in Jav a. I have not included MVC (Model View Controller) design pattern because that is more specific to J2EE and Servlet JSP interview , but if you are going for any Java interview which demands experience in J2EE than you must prepare MVC design pattern. That''s all on Java design pattern interview question and answers. Please let us know if you have any other interesting question on Java design pattern.
com.intellij.uiDesigner.designSurface.ListenerNavigateButton的实例源码
protected void actionPerformed(final GuiEditor editor,final List<RadComponent> selection,final AnActionEvent e) { ListenerNavigateButton.showNavigatePopup(selection.get(0),true); }
protected void actionPerformed(final GuiEditor editor,true); }
protected void actionPerformed(final GuiEditor editor,true); }
Design Patterns - Adapter Pattern(译)
原文链接
译者:smallclover
个人翻译,水平有限,如有错误欢迎指出,谢谢!
设计模式-适配器模式
适配器模式作为桥梁,连接两个不兼容的接口。这种类型的设计模式来源于结构型模式,它具有结合两个相互独立的接口的能力。
这个模式涉及到单个类,该类负责接入独立的、不兼容的接口。一个现实生活的例子,比如说读卡器,它可能会在记忆卡和笔记本电脑之间扮演一个适配者的角色。首先把记忆卡插到读卡器上,在把读卡器插入笔记本上,然后我们就可以从笔记本读取记忆卡上的数据。
我们通过以下的例子来展示适配器模式。一个音频播放器设备只能播放mp3文件;而另一个比较先进的音乐播放器可以播放vlc和mp4文件。
实现
我们有一个MediaPlayer
接口和一个实现该接口的实体类AudioPlayer
,这个AudioPlayer
默认播放mp3格式的音频。
我们还有另外一个接口 AdvancedMediaPalyer
和实现该接口的实体类
这些实体类可以播放vlc和mp4格式的音频。
我们希望AudioPlayer
也可以播放其他格式的文件。为了实现这个目标,我们创建了一个适配器类MediaAdapter
,该类实现了接口MediaPlayer
,并且使用AdvancedMediaPlayer
的对象来播放需要的格式。
AudioPlayer
使用适配器类 MediaAdapter
,通过它来播放所期望的音频类型,不需要知道实际是哪个类播放这个期望的音频类型。AdapterPatternDemo
,我们的demo类将使用AudioPlayer
类来播放各种格式的音频。
第一步
创建MediaPlayer
和AdvancedMediaPlayer
接口。
MediaPlayer.java
public interface MediaPlayer {
public void play(String audioType, String fileName);
}
AdvancedMediaPlayer.java
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
第二步
创建实体类实现AdvancedMediaPlayer
接口。
VlcPlayer.java
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: "+ fileName);
}
@Override
public void playMp4(String fileName) {
//什么
}
}
Mp4Player.java
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//什么也不做
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: "+ fileName);
}
}
第三步
创建一个适配器类实现MediaPlayer
接口
MediaAdapter.java
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new VlcPlayer();
}else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}
else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
第四步
创建实体类实现MediaPlayer
接口。
AudioPlayer.java
public class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
//内置支持播放MP3类型的音乐
if(audioType.equalsIgnoreCase("mp3")){
System.out.println("Playing mp3 file. Name: " + fileName);
}
//mediaAdapter 提供播放其他格式音频文件的支持
else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
}
else{
System.out.println("Invalid media. " + audioType + " format not supported");
}
}
}
第五步
使用AudioPlayer
播放不同种类的音频格式。
AdapterPatternDemo.java
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
}
}
第六步
校验输出。
Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
Playing vlc file. Name: far far away.vlc
Invalid media. avi format not supported
Design Patterns - Bridge Pattern(译)
原文链接
译者:smallclover
个人翻译,水平有限,如有错误欢迎指出,谢谢!
设计模式-桥模式
我们使用桥来解耦(decouple )一个抽象以及该抽象的实现。使用桥之后抽象和实现可以相互独立的改变。这种类型的设计模式来源于结构型模式,它可以通过使用桥结构来解耦抽象类及其实现类。
这种模式涉及一个接口,它扮演一个桥的角色,使得具体类的功能独立与接口。这两种类型的类可以在不影响对方的情况下改变自身结构。
我们通过下面的例子来演示桥模式的使用。画一个圆使用不同的颜色,相同的抽象类方法,不同的桥的具体实现者。
实现
我们有一个DrawAPI接口,它扮演一个桥的实现化者的角色,然后会有具体的类RedCircle和GreenCircle实现接口DrawAPI。抽象类Shape将持有DrawAPI对象。BridgePatternDemo,我们的demo类将使用Shape类画两个不同颜色的圆。
译者注:bridge implementer 这里翻译为桥的实现化者,它不同于具体的实现,如:继承,实现。这里的实现是指对桥这种概念的具体化,实现化。
第一步
创建一个桥的实现化者接口DrawAPI
DrawAPI.java
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
第二步
创建具体的类实现DrawApI接口
RedCircle.java
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
}
}
GreenCircle.java
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]");
}
}
第三步
创建一个抽象类 Shape,该类持有一个DrawAPI接口的引用。
Shape.java
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
第四步
创建一个具体类实现抽象类Shape。
Circle.java
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
第五步
使用Shape和DrawAPI类画两个不同颜色的圆。
BridgePatternDemo.java
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}
第六步
校验输出。
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]
关于Java-基于Web的Design Patterns应用程序和基于java的web应用程序设计的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于18 Java design pattern questions.、com.intellij.uiDesigner.designSurface.ListenerNavigateButton的实例源码、Design Patterns - Adapter Pattern(译)、Design Patterns - Bridge Pattern(译)的相关知识,请在本站寻找。
本文标签: