Design Pattern in jive)
Keywords: Jive, design pattern.
Abstract:
Jive is an open-source Forum project, which is our common BBs. It adopts the JSP technology of sun. Compared with the huge architecture of J2EE, its entire design concept is very
Refined, suitable for small and medium websites and building their own forum systems. This article will take a look at the design pattern applied in jive ).
Body:
This article does not explain the design pattern in detail. It just uses jive to look at the application of the design pattern in a real project and its overall design idea. Therefore, before reading this article, we assume that you
Has a perceptual understanding of its specific application and implementation methods, and is eager to understand its ideas, and has used jive. this article will discuss this issue together. why choose jive instead of a new example to start over? There are two reasons:
1. Many of us are familiar with something like BBS, and we are very clear about some basic functions of BBs. What do we think if we design such a web BBS as a designer, let's look at how others achieve it. Only by comparing them can we understand the shortcomings of our own design and the advantages of others can we make progress faster. 2. jive is not very complex and includes a complete implementation solution. There are good documents from the bottom layer to the top layer, from the back end to the front end, these can help us better understand it. the jive version we use here uses its developer as the officially released version 1.0. Its latest version is 1.21. It has made a few changes to its structure, mainly adding support for JSP tags, this technology is beyond our scope of discussion and will be available for further study. the design patterns used in jive involve three types of design patterns: creation, structure, and behavior. This gives you a comprehensive understanding of the design patterns. first, let's design it by ourselves. Using the object-oriented thinking, we can easily know that the entire system mainly needs these objects:
1. Forum-a forum, that is, a layout.
2. Thread-a clue, that is, all the replies on the same topic.
3. Message: a message, that is, a post sent by a user.
(In the future, we will use "Post)
4. User: a user in the discussion board.
Well, everything we need is there, and the relationship between them is very complicated. How can we organize them?
Is it easy to expand in line with our ideas? I think everyone has their own ideas. "I can do this ",
"I can design it like this." Let's take a look at how jive works. below is the overall structure:
| ~~~~~~~~~~~~~~~~~~ |
| Skin designer |
| __________________ |
|
| Use
\/
| ~~~~~~~~~~~~~~~~~ |
| Interfaces of various objects |
| _________________ |
|
| Implemented
\/
| ~~~~~~~~~~~~ |
| Permission control |
| ____________ |
|
| Control
\/
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| Various objects for database operations |
| _________________________ |
|
| Connection fetch
\/
| ~~~~~~~~~~~~~~~~ |
| Database connection pool |
| ________________ |
(Figure 1)
The following shows the general inheritance of the class:
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| Interface a |
| ___________________________________ |
|
| Implements |
|
| ~~~~~~~~~~~~~~~~~ |
| Proxy a |
| _________________ |
|
|
| ~~~~~~~~~~~~~~~~~~ |
| Database a |
| __________________ |
(Figure 2)
Now, if you have a good understanding of the design pattern, you can see some familiar things from the pseudo names written above. please give me some explanations. the figure above indicates the inheritance relationship of the class, generation
For the four objects mentioned above, interface a represents an interface named A. It is believed that everyone is familiar with interfaces and interfaces play an important role in Java. proxy A indicates a class named proxya, which implements the interface. database A indicates a class named dBA and implements interface. however, the design pattern is not reflected in it. The design pattern is about how to better organize the logical relationship between objects, how can we better expand existing things without making great changes, not just class inheritance. another thing to note is that the general principle of the design pattern is interface programming, rather than the specific implementation, A lot of specific programming is required to truly complete the system.
Next, let's look at the three types of design patterns that jive uses.
1. creational patterns)
This type of design pattern represents the object creation process and the relationship between the object used by the user.
1. In jive, a level of forumfactory is added to the Forum to implement some control over the forum, such as creating a new forum and deleting a forum. this class is actually the entrance of the entire system. everything done in JSP starts from getting an instance of this class. its subclass has the following relationship with it:
| ~~~~~~~~~~~~~~~~~ |
| Forumfactory | Abstract
| _________________ |
|
| Extends |
|
| ~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~ |
| Forumfactoryproxy | dbforumfactory |
| ____________________ | _________________ |
(Figure 3)
Let's take a look at the process of getting a forumfactory instance:
Factoryforum factory = forumfactory. getinstance (Aauthorization); then the forumfactory instance is obtained. This end user (skin designer) uses the forumfactoryproxy sub-class instance of forumfactory, as mentioned later), but in fact, the actual work is dbforumfactory or an instance of a specified class. The related code is as follows:
Below:
From forumfactory. java Private Static string classname = "com. coolservlets. forum. database. dbforumfaacloud "; // a specific subclass of the system default forumfactory. private Static forumfactory factory = NULL; forumfactory. getinstance () string classnameprop = propertymanager. getproperty ("forumfactory. classname ") // You can select another specific subclass through the preparation file. if (classnameprop! = NULL) {classname = classnameprop;} Try {// load the class and create an instance. class C = Class. forname (classname); factory = (forumfactory) C. newinstance ();} catch (exception e) {system. err. println ("failed to load forumfactory class" + classname + ". jive cannot function normally. "); E. printstacktrace (); return NULL ;}
It uses Abstract Factory design patterns. you can use a series of related object interfaces without specifying specific classes. that is to say, the JSP written by the skin designer should not contain statements such as new dbforumfactory. in jive, authorizationfactory also uses this design mode.
2. A good idea in jive is that the content and title of the post can be filtered. For example, HTML can be filtered to filter some dirty words, additional code can be highlighted, and links can be converted. if I want to implement such a function, there are several methods: (1) In message. getbody () getsubject () for control, (2) Get in thread? Message conversion. The problem that needs to be considered is that these filtering operations must be easily added and deleted. No? The design method used by the goal is different, jive is doing this: Take the layout as the main, and regard these filters as the attributes of saddle ting. The filter is only valid for the layout to which it belongs, therefore, jive uses (2). This is not the main one. What is important? How can we organize these filters? Let's first look at the requirement: Can we dynamically add and delete the filters. The function is similar. What is the display of the posts? It seems that there is only one target-prototype design mode.
The specific implementation of jive.
| ~~~~~~~~~~~~~~~~~~~~ |
| Forummessage |
| ____________________ |
|
| Implements
|
| ~~~~~~~~~~~~~~~~ | Prototype | ~~~~~~~~~~~~~~~~~~~~~ |
| Forumthread | -----------> | forummessagefilter |
| ---------------- | --------------------- |
| Getmessage () o | clone () |
| ______________ | _ | _____________________ |
|/|
| ~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~ |
| Afilter. Clone () | highlightcode | HTML |
| ________________ | --------------- | ------------- | ......
| Clone () o |
| ___________ | ___ | ___________ | _ |
|
| ~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~ |
| Returns an instance. |
| _______________ |
(Figure 4)
A little simplified. When using jive, these filters are stored in the database and attributes can be set dynamically, which is more convenient. Let's look at some code:
From: dbforumthread. java public forummessage getmessage (INT messageid) throws forummessagenotfoundexception {forummessage message = factory. getmessage (messageid); // apply filters to message. message = forum. applyfilters (Message); // It is implemented through Forum, because filter is the attribute of Forum, // thread can only be accessed through the Forum interface. return message;} from: dbforum. java public forummessage applyfilters (forummessage message) {for (INT I = 0; I <filters. length; I ++) {message = filters [I]. clone (Message);} // multiple Filters may be generated and operated in sequence. return message ;}
2. Structural Patterns)
This type of mode focuses on how to organize a large structure between classes and objects, and mainly uses inheritance to organize interfaces or implementations.
1. Let's continue to think about the differences between users. There are guest users who can let them have a look, but they cannot post them. Formal users can post them and view their personal information, the layout manager (called the moderator) should be able to control the posts, such as adding appropriate marks, earning the essence area, or even deleting the posts. The system manager should have higher permissions, such as opening a new layout, delete a user. how can this function be implemented? We know that all the actual operations in jive are implemented by the classes in the database directory. If you add permission control to the database layer, this layer will not only be bloated, but will also be well written, if you want to modify it, there are many places to be modified and it is prone to errors. Therefore, you can add a layer above this layer for separate permission control. in this way, we can separate "shouldn't do it" and "how to do it" to facilitate future modification. in fact, this is also an object-an object should not bear too much responsibility. this method is called the proxy mode in the design mode. it is like the relationship between the manufacturer and the agent. (Of course, this metaphor is not suitable in jive ). the purpose of proxy is to provide another object with a proxy to control its access. the proxy mode always runs through Jive and is required for almost all objects involved. its structure 2 is shown in. as we already know, forumfactory is the beginning of the entire system. let's take a look at the forumfactory code:
From forumfactory. Java forumfactory. getinstance (): forumfactoryproxy proxy = new forumfactoryproxy (factory, authorization, factory. getpermissions (authorization); Return proxy;
The preceding factory is an instance of dbforumfactory. Here, this instance is encapsulated with forumfactoryproxy. finally, an instance of forumfactoryproxy is returned. that is to say, the forumfactory used by the JSP skin designer is actually forumfactoryproxy. next, let's take a look at what happened in forumfactoryproxy. The small part is used as an example:
The factory in its constructor is an instance of dbforumfactory, which is used for specific work. authorization can be considered as an authenticated current user (the actual browser user), and forumpermissions can be considered as the current user's permission.
Public Forum createforum (string name, string description) throws unauthorizedexception {// check the permission here. If you have the system administrator permission, you can perform corresponding operations, // otherwise, an exception is thrown. if (permissions. get (forumpermissions. system_admin) {Forum newforum = factory. createforum (name, description); return New forumproxy (newforum, authorization, permissions);} else {Throw new unauthorizedexception () ;}} Public Forum getforum (int id) throws forumno Tfoundexception, unauthorizedexception {forum Forum = factory. getforum (ID); forumpermissions = forum. getpermissions (authorization); // create a new permissions object with the combination of the // permissions of this object and temppermissions. forumpermissions newpermissions = new forumpermissions (permissions, forumpermissions); // check and see if the user has read permissions. I F Not, throw an // an unauthorizedexception. If (! (Newpermissions. get (forumpermissions. read) | newpermissions. get (forumpermissions. forum_admin) | newpermissions. get (forumpermissions. system_admin) {Throw new unauthorizedexception ();} // as described above. // The Forum obtained here is a dbforum instance. Like forumfactory, // returns an encapsulated proxy object to control the permissions of forum. return new forumproxy (Forum, authorization, newpermissions );}
All other objects are similar.
3. behavioral patterns)
This type of pattern focuses on algorithms and task allocation between objects. It describes not only the design pattern of objects or classes, but also the communication pattern between objects.
1. Let's see how to get some threads from a forum. of course, the database is involved here. First, we should design the simplest database table, table name: thread, field threadid int, forumid Int. We don't care about other content. for example, in Forum, getthreads () is used to return all threads of the current forum. then you can do this:
Public forumthread [] getthreads ()
{
1. query from the database and retrieve all threadids,
2. Construct a forumthread object based on threadid,
3. An array is returned.
}
This is the easiest way to do this, but is it okay? I have to check the requirements. For example, if I want to sort by time, I have to modify this method. That is to say, I need to modify the dbforum object. Why not take the thread operation out separately? The advantage of this is that the function is independent, making dbforum simpler, in line with the principle of not putting too much responsibility on objects mentioned above. maybe you will say that if you want to modify it, don't you have to modify it? Where is the same? That's right, but it's only limited to a small system. If the system is large, simple queries in dbforum may not be the same as some programmers with complicated queries, this involves a lot of changes, but after separation, only a few changes can be done. let's look back at the problem. Here we will return a group of forumthread objects, and there may be some successive relationships between them. How can we do this? The iterator design mode is an appropriate choice. the iterator mode provides a method to access a large group of objects in a row without the need to know their representations, such as how they are sorted. let's take a look at the specific implementation of jive. since Java already has such an interface, iterator interface, you only need to implement this interface.
From dbforum: Public iterator threads () {return New dbforumiterator (this, factory);} from dbforumiterator: (modified) public class dbforumiterator implements iterator {public dbforumiterator (...) {...} public Boolean hasnext () // whether there are other elements {...} public object next () // get the next element {...}...} in JSP, you can access iterator threads = aforum. threads (); While (threads. hasnext () {forumthread thread = (forumthread) threads. next (); do some operations .}
We can see that some specific details of threads are encapsulated by using iterator to provide a unified interface. in jive, this design pattern is also used in many ways. It is required to display multiple users, multiple pages, multiple clues, and multiple posts.
Summary:
We have discussed the application of the design model in jive. Of course, it is very simple, superficial, and one-sided, but we can finally understand the design model. in fact, the design pattern draws on the experience of many predecessors, sums up some important and repeated patterns in the design, gives a system name, and gives corresponding explanations and comments, this work was first done by four software masters who wrote a book-design pattern: Elements of reusable object-oriented software. Later, they were called gof (Gang of Four ). the design patterns may be consciously and unconsciously used in our actual projects, such as the factory method, abstract, Singleton, and iterator modes? Clearly, there may be some unreasonable aspects of the design, in a State that follows the feeling, I believe that many experienced designers did not come into contact with the design model, once the contact, there will be an unexpected idea. Ha, it turns out to be like this. learning the design pattern can help us design well. We can use it directly under the same problem and background. Sometimes we don't know which one to choose, it is also a process of progress that requires a deeper analysis, comprehensive trade-offs, and a deeper understanding of the design model. for me, I have just come into contact with the design model and had a rough understanding. I took the liberty to write this article, which is a bit of experience and a challenge for myself. Some mistakes made in the middle, please correct me. Thank you.
To the files in documentation in jive2.1.1.