Design Patterns in Java Jive-Jive

Source: Internet
Author: User
The design mode in Java Jive-Linux general technology-Linux programming and kernel information. The following is a detailed description. This article does not explain the design patterns in detail. It just uses Jive to look at the application of the design patterns in a real project and its overall design philosophy. therefore, before reading this article, we assume that you have a perceptual knowledge of the design model, have some questions about its specific application and implementation methods, and are eager to understand its ideas and use 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 know some basic functions of bbs. If we design such a web bbs as a designer, what do you think, and then let's look at how others achieve it. Only by comparing them can you understand the shortcomings of your own design, and you can see the advantages of others to 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:

Forum-a Forum, that is, a layout.
Thread-a clue, that is, all the replies on the same topic.
Message: a Message, that is, a Post published by a user)
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 to conform to our ideas and expand them easily? I think everyone has their own ideas. "I can do this" and "I can design this way." Let's take a look at how Jive works. the overall structure is as follows:
| ~~~~~~~~~~~~~~~~~~ |
| 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 shows the inheritance relationship of the class. A represents the four objects mentioned above, and Interface A represents an Interface named A. I believe everyone is familiar with the Interface, 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.

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, but the actual work is DbForumFactory or an instance of a specified class. The related code is as follows:

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 other specific sub-classes 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.

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 this function, there are several methods: (1) In Message. getBody () getSubject (), (2) Get the Message in the Thread and convert it. you also need to consider the problem that these filtering operations must be able to easily add and delete. the design methods used for non-negative goals are different. Jive focuses on layout and considers these filters as attributes of saddle ting, the filter is only valid for the layout to which it belongs. Therefore, Jive uses (2), which is not the main one. It is important to organize these filters. let's first take a look at the requirement: Dynamic addition and deletion are supported. The function is similar. The display of the post shows how it is created and how it is irrelevant. it seems that there is only one Prototype design pattern. let's take a look at 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 );

// Implement it 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 . Clone (message );
}

// There may be multiple filters to operate 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.

Let's continue to think about the differences between users. There are Guest users who can have a look at them, 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 almost all the objects involved are required. Its structure 2 is shown.
As we already know, ForumFactory is the beginning of the entire system. Let's take a look at the ForumFactory code: From ForumFactory. java

Last of 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
{
// The permission is checked 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 ForumNotFoundException,
UnauthorizedException
{
Forum forum = factory. getForum (ID );
ForumPermissions forumPermissions = forum. getPermissions (authorization );
// Create a new permissions object with the combination of
// 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 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, which is the same as ForumFactory,
// Return a 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 we 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 pattern is an appropriate choice. The Iterator Pattern provides a method to continuously access a large group of objects without knowing their representations, such as how they are sorted.
Let's take a look at the specific implementation of Jive. As Java already has such an interface and 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 ();
Perform 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 pattern may be consciously and unconsciously used in our actual project, such as the Factory Method pattern, Abstract pattern, Singleton pattern, Iterator pattern, etc, it's just that the concept is not non-clear, and there may be some unreasonable aspects of the design. I believe many experienced designers are not in touch with the design model, 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.