JIVE design mode
(Source: http://www.cn.ibm.com/)
(Design Pattern)
Hoe
May 2001
Summary:
JIVE is an open source forum project, which is the BBS we are using, using Sun's JSP technology, compared to J2EE this huge architecture, its entire design ideas are very refined, suitable for small and medium-sized websites, establish Your own forum system. This article we will take a look at the Design Pattern approved.
With regard to design patterns, this article does not explain in detail, just combined with jive to see the application of design patterns in an actual project and its overall design idea. So before reading this article, suppose you have a sensibility to design mode Understand, there are some questions about their specific applications and implementations, and eager to understand their thoughts, and use JIVE. This article will come to explore this problem. Why choose Jive instead of choosing a new example to start? By following two reasons : 1, many of us is more familiar with the BBS, very clearly some of the basic functions of BBS, if you want to design such a web bbs as designers, what else, look, then see how others are implemented, there are Comparison can understand the shortcomings of ourselves, see the advantages of others to make faster. 2, JIVE is not very complicated, including a complete implementation, from the bottom to the top, all from the back end to the front end, Have a good document, these can help us understand it.
Here we have used its developers as a 1.0 version of the official release, its latest version of 1.21, has a small amount of change in its structure, mainly adding JSP TAG support, this technology does not belong to our discussion scope, There will be a chance to learn together.
The design patterns used in JIVE, the three types of design patterns - creation, structural, behavior - all involved, which can also be more comprehensive understanding of design mode. Let's first design, use it The idea of objects, it can be easily known that the entire system mainly needs these objects:
Forum - A discussion area is a layout. Thread - a clue, that is, all the repayment of the same topic. Message - a message, a note sent by a user. (In the future we Use "Post" called this name) User - one user, that is, the user of the discussion area.
Ok, what we need is all in, and the relationship between them is very complicated. How can they organize their ideas and easily expand? I think everyone has their own ideas, "I can so Do "," I can design like this ", let's take a look at how Jive is doing. The following is its overall structure:
| ~~~~~~~~~~~~~~~~~~ |
| SKIN Designer |
| __________________ |
| | |
| | | Use
/ /
| ~~~~~~~~~~~~~~~~~ |
| Interface of various objects |
| __________________ |
| | |
| | Implemented
/ /
| ~~~~~~~~~~~~ |
| Permission Control |
| ____________ |
| | |
| | | Control
/ /
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Various objects for the database |
| _____________________________ |
| | |
| | Take connection
/ /
| ~~~~~~~~~~~~~~~~ |
| Database connection pool |
| _________________ |
(figure 1)
Below is a probably inheritance of the class:
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INTERFACE A |
| __________________________________ |
| | |
| imports |
| | |
| ~~~~~~~~~~~~~~~~~ | || Proxy A |
| _________________ | |
|
|
| ~~~~~~~~~~~~~~~~~~ |
| Database A |
| __________________ |
(figure 2)
I saw this here. If you have a knowledge of the design pattern, you can see some familiar things from the pseudo name written above. Please let me do some explanations. The above figure shows the inheritance relationship of the class, A represents the four objects mentioned above, Interface A represents an interface named A, I believe that everyone is not strange to the interface, and the interface has an important role in Java. Proxy a indicates a class named Proxya, implementing A Interface. Database A represents a class named DBA, implements a interface. But the design pattern does not reflect it, the design mode is to express how to better organize the logical relationship between objects, how to better Expanding existing things without having to make a lot of changes, not just the inheritance of the class.
It is also necessary to explain that the general principle of design patterns is for interface programming, not to care about its specific implementation, which is a shelf, but also requires many specific programming to real complete the system.
Below, we look at the three types of design patterns, and which are used.
1. Creating the type of design mode of Creational Patterns, which is to be expressed as the creation process of the object and the relationship between the objects used by the user.
The top of the Forum is added to the Forum, and ForumFactory has implemented some controls for Forum, such as creating a new discussion area, deleting a discussion area, etc. This class is actually the entrance of the entire system, what is done in JSP Everything begins with an example of this class. Some subclasses and its relationships are as follows:
| ~~~~~~~~~~~~~~~~~ |
| ForumFactory | Abstract
| __________________ |
| | |
| Extends |
| | |
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ForumFactoryProxy | | DBFORumFactory |
| ____________________ | | _________________ |
(Figure 3) Let's take a look at the process of getting a ForumFactory instance: factoryforum factory = forumfactory.getInstance (AAUTHHORIZATION); gets the formFactory instance, this end user (SKIN Designer) is used is its subclass forumfactoryProxy Example, (which involves another mode, will be mentioned later), but actually actually working is the instance of DBForumFactory or a specified class, the relevant code is as follows:
From forumfactory.java
Private static string classname = "com.coolservlets.forum.database.dbforumfaactory";
/ / The system default forumfactory's specific subclass.
Private static forumfactory factory = null;
ForumFactory.GetInstance ()
String classnameprop = PropertyManager.getProperty ("forumfactory.classname)
// You can choose other specific subclasses by formulating files.
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 the Abstract Factory design mode. Give the user an interface to use a series of related objects without the need to specify its specific classes. That is to say, New DBForumFactory should not appear in the JSP written by Skin designers. The statement of the class. The AuthorizationFactory in Jive also uses this design pattern. It is a very good idea in jive, which is to filter the content and title of the post, such as filtering HTML filtering some swearing, highlighting the additional code, Conversion link, etc. If I want to achieve such functions, there are several ways: (1) Control in Message.getBody () getSubject (), (2) Conversion after Message in Thread. Still The problem that needs to be considered is that these filtrations must be able to easily add deletion. The design methods used in the objective goals are different. JIVE is doing this: dominated by layout, regarding these filters as Ansiting Attributes, the filter is only valid for the layout of it, so uses (2) in JIVE, this is not the main, what is important to organize these filters. Let's take a look at the needs: You can dynamically add deletion, Similar, the post display shows how it is created, how to express it. It seems that only one - prototype design mode. Take a look at the specific implementation of JIVE.
| ~~~~~~~~~~~~~~~~~~~~ |
| Forummessage |
| ____________________ |
|
| Implements
|
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ForuMthread | -----------> | ForumMessageFilter |
| ----------------------------------------- |
GetMessage () o | | Clone () |
| ______________ | _ | | _____________________ |
| / |
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Afilter.clone () | | HIGHLIGHTCODE | | HTML |
| ________________ | | --------------- | | ------------- | ......
| clone () o | | Clone () O |
| ___________ | ___ | | ___________ | _ |
| | |
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Return an instance | | Return an instance |
| _______________ | | _______________ |
(Figure 4) The picture is a little simplified. When used, it is time to exist in the database, which can dynamically set attributes, more convenient. Take some code:
From: dbforumthread.javapublic forummessage getMessage (int MessageID)
Throws forummessagenotfoundexception
{
ForumMessage message = factory.getMessage (MessageID);
// apply filters to message.
Message = forum.applyfilters (message);
// Implement through Forum, because Filter is the properties of Forum,
// Thread can only be accessed by the interface of the Forum.
Return Message;
}
From: dbforum.java
Public forumMessage Applyfilters (forumMessage message) {
For (int i = 0; i Message = filters [i] .clone (Message); } // There may be multiple filters to operate in turn. Return Message; } Second, Structure Modal Patterns This type of mode care class and objects have organized a large structure. Mainly use inheritance to organize interfaces or implementations. Let's think about it, there should be differences between users. You can let him take a look, but you can't send a post, official user can send a post, check your personal information, layout manager (call managers The moderator should be able to control the post, such as adding appropriate markers, income essence, or even deleting posts, etc., and system managers should have higher permissions, such as open new layouts, delete users, etc. . How do we know this feature? We know that all actual operations in the jive are implemented by classes in the Database directory. If the permissions are added to the database, this layer is not only bloated, but also written If you want to change, there is a lot of places that you need to modify, and it is easy to make mistakes, so you can add one layer above this layer, permission control. This will put "don't do" and "how to do" segmentation. Come, beneficial to the future modification. In fact, this is also an idea of an iconic object - an object does not bear too much responsibility. This method is called Proxy (proxy) mode in design mode. It is better than the manufacturer and agent relationship. (Of course, this metaphor is not appropriate in jive). The purpose of Proxy is to provide an agent to another object to control access to it. The Proxy mode has always been through the JIVE, and the object involved is required. As shown in Figure 2. From the previous side already known, ForumFactory is the beginning of the entire system. Let's take a look at the finalumFactory code: From forumfactory.java FORUMFACTORY.GETInstance () final: ForumFactoryProxy Proxy = New ForumFactoryProxy ( Factory, Authorization, Factory.GetPermissions (Authorization) ); Return Proxy; The previous Factory is the instance of dbforumfactory. This instance is also encapsulated in the ForumFactoryProxy. Finally returned an instance of ForumFactoryProxy. That is to say, the ForumFactory used by JSP Skin is actually ForumFactoryProxy. WarmFactoryProxy. What happened in ForumFactoryProxy? Things, that a small fragment example: Factory in its constructor is an instance of DBforumFactory, which is made by it. Authorization can be considered an authenticated current user (referring to the actual browser user), and ForumPerMissions can be considered to be the current user's permissions. Public Forum Createforum (String Name, String Description "throws unauthorizedException { // This is checked here, with system administrator privileges, it can be performed accordingly. / / Otherwise, throw an exception. 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 forumnotfoundexception, UnauthorizedException { Forum forum = factory.getforum (ID); Forumpermissions forumpermissions = forum.getPermission (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. If not, throw an // an unauthorizedException. IF (! Newpermissions.Get (forumpermissions.read) || Newpermissions.Get (forumpermissions.forum_admin) || Newpermissions.get (forumpermissions.system_admin) )) { Throw new unauthorizedException (); } //. / / The forum here is a DBFORUM example, just like ForumFactory, / / Return to a packaged proxy object to control the Forum permission control. Return New ForumProxy (Forum, Authorization, Newpermissions); } All other objects are similar. It will not be described again here. Third, the mode of behavioral pattern (Behavioral Patterns) is concerned about the task assignment between the algorithm and the object. It describes not only the design mode of the object or class, and there is a communication mode between them. 1. Take a look at how to get some Thread from a Forum. Of course, this should be involved in the database, first design a simple database table, table name: thread, field threadid int, forumid int, other content we don't care. Then For example, a method in Forum, getThreads () to return all the thread of the current forum. Then you can do this: Public foruMthread [] getthreads () { 1. Query from the database, remove all ThreadID, 2, construct the ForuMThread object according to ThreadID, 3. Return to an array. } This is the most simple, but it's not good. It's good to see the demand. For example, I will have to modify this method according to time, that is, I need to modify the DBFORUM object. So why not take the Thread this operation separately Take it out? This kind of advantage is to function independence, making DBFORUM simpler, complying with the principle of liability for the responsibility of the object we mentioned before. Maybe you will say, if you want to modify, don't you have to modify it? Where is the same, this is right, but it is limited to a small system. If the system is big, it may be a simple query in dbForum and some more complex queries, it is not a person, which is involved There is more ways to change, but after separation, you can do it. You can do it. You can take a look at the problem. Here you have to return a group of FORUMTHREAD objects, and there may be some ancestive relationship between them. How to do this? Itrator design mode is a suitable option. Itrator mode provides a method of continuously accessing a large group of objects, without having to know what form of performance, such as what way is sorted, etc. Well, Take a look at the specific implementation of JIVE. Since Java itself has such an interface, the Iterator interface, so as long as this interface is available. From dbforum: Public iterator threads () { Return New DBForumiterator (this, factory); } From dbforumiterator: (made a change) Public class dbforumiterator imports itrator { Public dbForumiterator (...) { ... } Public Boolean Hasnext () // Is there elevation { ... } Public Object next () // Get the next element { ... } ... } Then the JSP can be accessed like this: Iterator threads = Aform.Threads (); While (threads.hasnext ()) { ForuMthread thread = (forumnread) threads.next (); Do some operations. } It can be seen from it. By encapsulation of Threads by using iterator, providing a unified interface. This design pattern in jive is also used, multiple users display, multiple layouts display, multiple clues, more A post requires it to be implemented. Summary: The above, we discussed the application of design patterns in jive, of course, is just very simple, very superficial, and very faced, but finally, it can have some understanding of design patterns. In fact, design mode is to absorb most people's experience Summary some important and repeated modes in the design, give a system naming, give appropriate interpretation and evaluation, this work is first made by the 4 software masters, they write a book - Design Pattern: Elements of Reusable Object-Oriented Software, later, people called GOF (Gang of Four). For design patterns, you may consciously use it in our actual project, such as Factory Method mode, Abstract Mode, Singleton mode, Iterator mode, etc., but the concept is not clear, the design may be less reasonable. Place, in a state of following, I believe many experienced designers, there is no touch design mode, once after contact, there will be an idea that I suddenly realizes, ha, learning design mode, can Good to help us design, in the same problem, the same background, you can use it directly, sometimes it doesn't know which kind of choice, you need to analyze the problem, and perform comprehensive weight, design The model also has a more profound understanding to get good results, which is also a progress process. For the author, I have just contacted the design model. I have a little shallow understanding. I will take the way to write this one. It is also a bit of my own experience. It is also a challenge to myself, some mistakes in the middle, please refer to, thank you. Reference literature: Design Pattern: Elements of Reusable Object-Oriented Software, JIVE Source Code