Use of application objects in the database cache content navigation column

  Abstract: The application object in the database cache content navigation column 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> when preparing database-driven web pages, some stored in the database content rarely changes, such as columns title, category names, and so on, show that the contents of the cache instead of the best frequent Reading database application can be used jsp pages or other object caching methods, as follows: 
<%
  TreeMap list = (TreeMap) application.getAttribute ( "kejie"); / / Reading cache contents 
  If (list == null) (/ / If the content has not cache, the cache 
  List = new TreeMap (); 
  Application.setAttribute ( "kejie" list); / / cache 
  / / Reading database, object data Add TreeMap 
  Rst = db.executeQuery ( "select type_parent_id, parent_name_cn from type_parent order by parent_order_id"); 
  While (Rst.next ()) ( 
  List.put (Rst.getString ( "type_parent_id"), Rst.getString ( "parent_name_cn")); 
  ) 
  ) 
  <table Width="666" border="0"> <tr> <td width="386" valign="top"> Set entries = list.entrySet (); 
  Iterator iter = entries.iterator (); 

  While (iter.hasNext ()) (/ / cache read and display the contents 

  Map.Entry entry = (Map.Entry) iter.next (); 
  String key = (String) entry.getKey (); 
  String value = (String) entry.getValue (); 
  Out.print (""); 
  Out.print (value); 
  Out.print (""); 
  Out.println ( ""); 

  ) 

  %> </ Td> <td width="270"> </ td> </ tr> </ table> 

  </ Td> </ tr> <tr> 

  ↑ Back 

Design Patterns of Command

  Abstract: Model of Command 

  Command mode is the most Let me puzzled a model, I read a lot of code, only vaguely understand the feeling about principle, I think the most important thing is to understand design principles have been constructed, such才对programming guide their actual role . Command mode is not really a very specific, many provisions of the model, it is this flexibility, some people confuse. 

  Many Command Command definition of the model code are directed at the graphical interface, it is actually the menu command, we have a drop-down menu to select a command, and will then perform some action. 

  These orders will be packaged as a category, then users (call) of this type to operate, and this is Command mode, in other words, have users (call) is the direct transfer of these orders, such as the menu open Documentation (call), open the file directly at the code, use Command mode, which is an intermediate between the increase, this will be directly related to Yuduan, isolation between the two are basically no the relations. 

  Clearly the benefits of this package is in line with the characteristics of reducing coupling, Command will conduct package is the typical pattern Factory is to create a package model, 
  From the Command Mode, I also found design a "common problem": It seems like a simple issue will be complicated, like an increase in the different types of third party, of course, to do so robust maintainability of the code are reusable sexual. 

  How to use it? 
  Command mode code specific variety, because how packaging orders, different systems, different approaches. Below are examples of packages in the order of a Collection List, any object once it joins the List, in a packed closed black box, the object of the disappeared, only removed when will it be possible to distinguish between the fuzzy: 

  Typical of the need for a Command mode interface. Interfaces in a unified way, and this is "an order / request package targeting": 
  (Public interface Command 
  Public abstract void execute (); 
  ) 

  Different specific order / request of the code is to achieve Interface Command, the following three specific orders 
  Public class Engineer implements Command ( 

  Public void execute () ( 
  / / Do Engineer's command 
  ) 
  ) 
  Public class Programmer implements Command ( 

  Public void execute () ( 
  / / Do programmer's command 
  ) 
  ) 

  Public class Politician implements Command ( 

  Public void execute () ( 
  / / Do Politician's command 
  ) 
  ) 



  As is the usual practice, we will be able to directly call these three Command, but the use of Command mode, we have to package them up, throw went black box List: 


  (Public class producer 
  Public static List produceRequests () ( 
  List queue = new ArrayList (); 
  Queue.add (new DomesticEngineer ()); 
  Queue.add (new Politician ()); 
  Queue.add (new Programmer ()); 
  Return queue; 
  ) 

  ) 



  These three orders entered in the List, has lost its characteristic appearance, later removed, but also may not be able to tell who is who is the Engineer Programmer, see below how to call Command mode: 


  (Public class TestCommand 
  Public static void main (String [] args) ( 

  List queue = Producer.produceRequests (); 
  For (Iterator it queue.iterator = (); it.hasNext ();) 
  / / Retrieve List of Dongdong, other characteristics are not sure, a feature only guarantee is 100% correct, 
  / / Command Interface is at least a "son." Therefore, mandatory conversion to type Command Interface 

  ((Command) it.next ()). Execute (); 


  ) 
  ) 


  Therefore, only basic caller interface and dealing with substandard concrete realization of interactive, which also embody a principle-oriented programming interface, so that after the fourth increase in specific order, would not have to modify the caller TestCommand of the code. 

  Understand the above code of the core principles in use, they should each have their own methods, particularly in how to separate and specific orders call, a lot of method, the above code is the use of "off again from List" approach. only to demonstrate this approach. 


  Command mode of use of a good reason but also because it can achieve Undo function. Each specific commands can be executed just remember it moves, and restored if needed. 

  Command model widely used in interface design. Java Swing in the menu commands are using Command mode, as in the Java interface design there is a lack of performance, interface design specific code we have not discussed, the Internet has many such examples. 




  ↑ Back 

Java encryption algorithm

  Abstract: Java encryption algorithm 

  Java encryption algorithm 

  Author: Java_One Source: http://blog.csdn.net/Java_One 

  Import java.security .*; 
  (Public class MessageCheck 
  Public static void main (String [] args) ( 

  String info1 = "admin"; 
  / / String info1 = "Hello World!"; 
  String info2 = "Hello World!"; 

  Try ( 
  / / Generate MessageDigest example, the accounting method 
  / / MessageDigest md1 = MessageDigest.getInstance ( "SHA-1"); 
  MessageDigest md1 = MessageDigest.getInstance ( "MD5"); 
  / / Add a summary of the information to calculate 
  Md1.update (info1.getBytes ()) / / transform parameter to byte [] 
  / / Hash completed, a summary of return calculated (for MD5 is 16, SHA is 20) 
  Byte [] = digA md1.digest (); 
  / / 
  MessageDigest md2 = MessageDigest.getInstance ( "SHA-1"); 
  Md2.update (info2.getBytes ()); 
  Byte [] = digB md2.digest (); 

  / / Comparison of the two is the same information 
  If (md2.isEqual (digA, digB)) ( 
  System.out.println ( "two equal information, inspection normal!"); 
  System.out.println (hasString (digA) + "\ n" + hasString (digB)); 
  ) 
  Else ( 
  System.out.println ( "information does not equal two, Abstract not the same!"); 
  System.out.println (hasString (digA) + "\ n" + hasString (digB)); 
  ) 
  ) Catch (NoSuchAlgorithmException e) ( 
  System.out.println ( "illegal Abstract algorithm!"); 
  E.printStackTrace (); 
  ) 
  ) 

  Public static String hasString (byte [] b) ( 
  String has = "", tmp = ""; 
  For (int i = 0; i <b.length; i + +) ( 
  / / Hexadecimal form of the unsigned integer return an integer parameters that form the string 
  Tmp = (java.lang.Integer.toHexString (b [i] & 0XFF)); 
  If (tmp.length () == 1) 
  Has has + = "0" + tmp; 
  Else 
  Tmp = + has has; 
  If (i <b.length - 1) has has = + ":"; 
  ) 
  Return has.toUpperCase (); 
  ) 
  ) 




  ↑ Back 

The Adapter design pattern (adapter)

  Abstract: Model Adapter (adapter) 

  Definition: 
  Will be two incompatible types used to gather together, which in practice often. 

  Why? 
  We often encountered no relationship to the two categories combined use, the first solution is: to amend the interface in each category, but if we do not have the source code, or, we do not want an application to amend their respective access mouth.    How do? 

  Adapter used in the interface between the two to create a hybrid interface (mixed). 

  How to use it? 
  Implementation Adapter, In fact, the "think in Java," "renewable" in an already mentioned, there are two ways: portfolios (composition) and inheritance (inheritance). 


  We must assume that piling, there are two categories: square piles circular pile. 
  (Public class SquarePeg 
  Public void insert (String str) ( 
  System.out.println ( "SquarePeg insert ():"+ str); 
  ) 

  ) 

  (Public class RoundPeg 
  Public void insertIntohole (String msg) ( 
  System.out.println ( "RoundPeg insertIntoHole ():"+ msg); 
  ) 
  ) 

  Now have an application has been achieved SquarePeg inheritance, but also in achieving RoundPeg insert () action, 

  Public class PegAdapter extends SquarePeg ( 

  Private RoundPeg roundPeg; 

  Public PegAdapter (RoundPeg peg) (this.roundPeg = peg;) 

  Public void insert (String str) (roundPeg.insertIntoHole (str);) 

  ) 

  PegAdapter in, the use of combinations, RoundPeg object, then Heavy insert () method.    See here, if you some Java experience, it was found that frequent use of this model. 

  Above PegAdapter SquarePeg is inherited, if we need on both sides of the succession, inheritance and succession RoundPeg SquarePeg, because Java does not allow multiple inheritance in, but we can achieve (implements) 2 interface (interface) 

  (Public interface IRoundPeg 
  Public void insertIntoHole (String msg); 

  ) 

  (Public interface ISquarePeg 
  Public void insert (String str); 

  ) 

  Below are the new RoundPeg SquarePeg and, in addition to interface to achieve this distinction, and no different from the above. 
  Public class SquarePeg implements IRoundPeg ( 
  Public void insert (String str) ( 
  System.out.println ( "SquarePeg insert ():"+ str); 
  ) 

  ) 

  Public class RoundPeg implements ISquarePeg ( 
  Public void insertIntohole (String msg) ( 
  System.out.println ( "RoundPeg insertIntoHole ():"+ msg); 
  ) 
  ) 

  Below are the new PegAdapter, called the two-way adapter: 

  Public class PegAdapter implements IRoundPeg, ISquarePeg ( 

  Private RoundPeg roundPeg; 
  Private SquarePeg squarePeg; 

  / / Constructor public PegAdapter (RoundPeg peg) = (this.roundPeg peg;) 
  / / Constructor public PegAdapter (SquarePeg peg) (this.squarePeg = peg;) 

  Public void insert (String str) (roundPeg.insertIntoHole (str);) 

  ) 

  There is also a call Pluggable Adapters, can dynamically access in a few adapters.    Reflection use technology, the dynamic can be found in the category of Public method. 




  ↑ Back 

The design pattern Chain of Responsibility

  Abstract: The design pattern Chain of Responsibility 

  Chain of Responsibility definition 
  Chain of Responsibility (CoR) is using a series of categories (classes) to try and deal with a request request, and between these categories is a loose coupling, is the only common ground between them transfer request. Other words, a request to Type A deal with, if not dealt with, transmitted to the Class B treatment, if not dealt with, on the transfer to category C treatment, it is so like a chain (chain) as pass on. 

  How to use it? 
  While this section is how to use CoR, but also demonstrated what is CoR. 

  One Handler Interface: 

  (Public interface Handler 
  Public void handleRequest (); 
  ) 

  This is a case dealing with the request, if there are multiple request, such as asking for help or request formatted print requests: 

  The first to think of solutions: increase in the number of requests interface: 
  (Public interface Handler 
  Public void handleHelp (); 
  Public void handlePrint (); 
  Public void handleFormat (); 

  ) 

  Implementation is a specific interface Handler code: 
  Public class ConcreteHandler implements Handler ( 
  Private Handler successor; 

  Public ConcreteHandler (Handler successor) ( 
  This.successor = successor; 
  ) 

  Public void handleHelp () ( 
  / / Help specific handling of the request code … 
  ) 

  Public void handlePrint () ( 
  / / If it is to deal with the Print to print 
  Successor.handlePrint (); 
  ) 
  Public void handleFormat () ( 
  / / If it is to deal with the format to the Format 
  Successor.handleFormat (); 
  ) 

  ) 
  There are three concrete realization of this category, the above is handled help, and deal with handling Print Format This is probably the most commonly used programming ideas. 

  Although the ideas simple and clear, but there is a question of expansion, if we need to add a request request types, and the need to amend the interface to achieve each one. 

  The second programme: each request will be turned into an interface, we have the following code: 

  (Public interface HelpHandler 
  Public void handleHelp (); 
  ) 

  (Public interface PrintHandler 
  Public void handlePrint (); 
  ) 

  (Public interface FormatHandler 
  Public void handleFormat (); 
  ) 

  Public class ConcreteHandler 
  Implements HelpHandler, PrintHandler, FormatHandlet ( 
  Private HelpHandler helpSuccessor; 
  Private PrintHandler printSuccessor; 
  Private FormatHandler formatSuccessor; 

  Public ConcreteHandler (HelpHandler helpSuccessor, PrintHandler printSuccessor, FormatHandler formatSuccessor) 
  ( 
  This.helpSuccessor = helpSuccessor; 
  This.printSuccessor = printSuccessor; 
  This.formatSuccessor = formatSuccessor; 
  ) 

  Public void handleHelp () ( 
…….
  ) 

  Public void handlePrint () = (this.printSuccessor printSuccessor;) 

  Public void handleFormat () = (this.formatSuccessor formatSuccessor;) 

  ) 

  This approach in the new request at the request of circumstances, the only saving changes in the interface, the interface ConcreteHandler also needs to be revised.    And the code is obviously something beautiful. 

  Solution 3: Handler Interface uses only one parameter: 
  (Public interface Handler 
  Public void handleRequest (String request); 
  ) 
  Then Handler codes are as follows: 
  Public class ConcreteHandler implements Handler ( 
  Private Handler successor; 

  Public ConcreteHandler (Handler successor) ( 
  This.successor = successor; 
  ) 

  Public void handleRequest (String request) ( 
  If (request.equals ( "Help")) ( 
  / / Here is dealing with the specific code Help else) 
  / / Successor.handle transfer to a (request); 

  ) 
  ) 

  ) 


  Here is the first assumption String type of request, if not how do?    Of course, we can create a special category Request 


  Finally solution: Interface Handler code as follows: 
  (Public interface Handler 
  Public void handleRequest (Request request); 
  ) 
  Request class definition: 
  (Public class Request 
  Private String type; 

  Public Request (String type) (this.type = type;) 

  Public String getType () (return type;) 

  Public void execute () ( 
  / / Request specific acts of genuine code) 
  ) 
  Then Handler codes are as follows: 
  Public class ConcreteHandler implements Handler ( 
  Private Handler successor; 

  Public ConcreteHandler (Handler successor) ( 
  This.successor = successor; 
  ) 

  Public void handleRequest (Request request) ( 
  If (request instanceof HelpRequest) ( 
  / / Here is dealing with the specific code Help) else if (request instanceof PrintRequst) ( 
  Request.execute (); 
  ) Else 
  / / Successor.handle transfer to a (request); 

  ) 
  ) 

  ) 

  This solution is CoR, in a chain, there are corresponding responsibilities category, called Chain of Responsibility. 

  CoR advantages: 
  From the outside world because of their inability to foresee the request is a type, encountered each category if it can not handle the request as long as we can give up.    No doubt, this reduces the coupling between categories. 

  Deficiency is inefficient, because the completion of a request may have to traverse to be completed before the end, of course, can also use the concept of tree optimization.    In Java AWT1.0, in regard to the matters dealt with the mouse button is the use of CoR to Java.1.1 later, on the use of substitute CoR Observer 

  Expansion of the poor, because the CoR, there must be a unified interface Handler. Limitations on here. 



  ↑ Back 

Design Patterns of Proxy

  Abstract: Proxy Model 

  Understand and use the design model, we can cultivate good habits of object-oriented programming, but in practical applications, we can如鱼得水enjoy highly of fun. 

  Proxy is more use of a model, and more variety, covering applications from structure to the structure of the whole system, Proxy agent is the meaning, we may have concepts such as a proxy server, agent concept can be explained as follows: the starting point to Destinations between a middle layer, which means agents. 

  Design Patterns in the definition: provide a target for other agents to control the object of this visit. 

  Why use Proxy? 
  1. Licensing mechanism different levels of users on the same object with different access rights, such as Jive Forum system, the use of a licensing mechanism Proxy control, there are two kinds of people visit the Forum: registered users and visitors (non-registered users), in Jive on the adoption of similar ForumProxy such agents to control both users access to the Forum. 

  2. A client can not be directly manipulated to a certain object, but it is essential that the object and interactions. 
  For example two specific situations: 
  (1) If that object is a great picture is the need to take a long time to show up, then when the picture contained in the document, the use of the editor or browser to open this document, open the file must be very rapid , can not wait for complete processing of the picture, then the need to be a picture Proxy to substitute for real picture. 

  (2) If that object in a certain remote Internet servers directly operated the network speed of the object because the reasons may be quite slow, we could be using to replace the Proxy that object. 


  In general principle is that the big spending targets, only use it when creating this principle we can save a lot of valuable Java memory. Therefore, some people think that Java memory consuming resources, I think that that is what programmers have certain ideas relations. 

  How to use Proxy? 
  Jive system as an example to the Forum, visit the Forum There are many types of users: Forum users registered general manager system administrator tourists, ordinary users can register to speak Forum managers can manage his mandate as a forum for the system administrator can manage all matters, and management of these rights is the use of Proxy completed. 

  Jive Forum is the core interface, in the Forum on display in the main operation Forum, described the Forum as the Forum names of the access and changes made to delete editing posts. 

  ForumPermissions defined in a variety of user-level permissions: 

  Public class ForumPermissions implements Cacheable ( 
  / ** 
  * Permission to read object. 
  * / 
  Public static final int READ = 0; 

  / ** 
  * Permission to administer the entire sytem. 
  * / 
  Public static final int SYSTEM_ADMIN = 1; 

  / ** 
  * Permission to administer a particular forum. 
  * / 
  Public static final int FORUM_ADMIN = 2; 

  / ** 
  * Permission to administer a particular user. 
  * / 
  Public static final int USER_ADMIN = 3; 

  / ** 
  * Permission to administer a particular group. 
  * / 
  Public static final int GROUP_ADMIN = 4; 

  / ** 
  * Permission to moderate threads. 
  * / 
  Public static final int MODERATE_THREADS = 5; 

  / ** 
  * Permission to create a new thread. 
  * / 
  Public static final int Create_THREAD = 6; 

  / ** 
  * Permission to create a new message. 
  * / 
  Public static final int Create_MESSAGE = 7; 

  / ** 
  * Permission to moderate messages. 
  * / 
  Public static final int MODERATE_MESSAGES = 8; 

…..

  Public boolean isSystemOrForumAdmin () ( 
  Return (values [FORUM_ADMIN] | | values [SYSTEM_ADMIN]); 
  ) 

…..

  ) 


  Therefore, the Forum is in the competence of the various operations and ForumPermissions definition of a user-level relations, as the realization of Interface Forum: ForumProxy such relationship is linked to, for example, modify the name Forum, the Forum only managers or system Managers can modify the code as follows: 

  Public class ForumProxy implements Forum ( 

  Private ForumPermissions permissions; 
  Private Forum forum; 
  This.authorization = authorization; 

  Public ForumProxy (Forum forum, Authorization authorization, 
  ForumPermissions permissions) 
  ( 
  This.forum = forum; 
  This.authorization = authorization; 
  This.permissions = permissions; 
  ) 

…..

  Public void setName (String name) throws UnauthorizedException, 
ForumAlreadyExistsException
  ( 
  / / Is the only forum administrators or system can be amended if the name (permissions.isSystemOrForumAdmin ()) ( 
  Forum.setName (name); 
  ) 
  Else ( 
  Throw new UnauthorizedException (); 
  ) 
  ) 



  ) 



  DbForum Interface Forum and is the true realization, as an example to change the name Forum: 

  Public class DbForum implements Forum, Cacheable ( 


  Public void setName (String name) (throws ForumAlreadyExistsException 

….

  This.name = name; 
  / / Here will be truly a new name saved to the database saveToDb (); 

….
  ) 





  ) 


  All relate to revise the name of the Forum, other procedures must first be dealing with and ForumProxy from ForumProxy decide whether there is a certain authority to do the same thing, ForumProxy is a true "gateway", "security agent system." 

  In peacetime applications, must inevitably involve the authority or security system, whether you have the use of Proxy unconscious, you have the actual use of the Proxy. 

  We continue to discuss with Jive deep point, the following should be related to the factory model, and if you do not understand the factory model, I see another article: Design Model Factory 

  We already know, through the use of Forum ForumProxy, Jive Forum in the creation of a model is to use Factory, there is a general category ForumFactory abstract, in this abstract class, call ForumFactory through the getInstance () method, used here Singleton (also One design pattern, as on many articles, I do not write, read here), getInstance () returns the ForumFactoryProxy. 

  Why not return to ForumFactory, and the realization of ForumFactoryProxy ForumFactory return? 
  The reason is obvious, you need to determine whether agents authority to create a forum. 

  ForumFactoryProxy we see in the following code: 

  Public class ForumFactoryProxy extends ForumFactory ( 
  Protected ForumFactory factory; 
  Protected Authorization authorization; 
  Protected ForumPermissions permissions; 

  Public ForumFactoryProxy (Authorization authorization, ForumFactory factory, 
  ForumPermissions permissions) 
  ( 
  This.factory = factory; 
  This.authorization = authorization; 
  This.permissions = permissions; 
  ) 

  Public Forum createForum (String name, String description) 
  Throws UnauthorizedException, ForumAlreadyExistsException 
  ( 
  / / Only system administrators can create forum 
  If (permissions.get (ForumPermissions.SYSTEM_ADMIN)) ( 
  Forum newForum = factory.createForum (name, description); 
  Return new ForumProxy (newForum, authorization, permissions); 
  ) 
  Else ( 
  Throw new UnauthorizedException (); 
  ) 
  ) 



  CreateForum method is the return of ForumProxy, Proxy as a wall, and the only other procedures Proxy interactive operation. 

  Noting there are two Proxy: ForumProxy and ForumFactoryProxy. Behalf of the two different responsibilities: Use Forum and the creation of Forum; 
  As for why objects and will be used to create separate object, which is why the use of the Factory model reason: in order to "package" and "distributed", in other words, as far as possible, single function, and easy to maintain amended. 

  Jive system in other forums such as the creation and use of Posts, in accordance with the ideas from the Forum. 

  We discussed more than how to use a licensing mechanism Proxy visit Proxy users can also hide another called copy-on-write the optimization method. Copy of a huge and complex objects is a great operating expenses, if the copy process , none of the original targets have been revised, then the copy costs would not be necessary. agents with copies of this delay. 

  For example: We have a great Collection, such as specific hashtable, many clients will visit at the same time with it. One of the client to conduct continuous data acquisition, this time demanding that other clients can no longer add or delete hashtable Dongdong. 

  The most direct solution: the use of the lock collection, this particular client access to the lock, continuous data acquisition, and then release lock. 
  Public void foFetches (Hashtable ht) ( 
  Synchronized (ht) ( 
  / / Data acquisition for specific action .. 
  ) 

  ) 


  However, this approach may be locked Collection will be very long period of time, during this period of time, other clients will not be able to visit the Collection of. 

  The second solution is to clone the Collection, then let continuous data acquisition clone out against the operation that Collection. Premise of this proposal is that the Collection can clone, and must provide the depth clone method. Hashtable provides the its clone, but not the Key value and the target clone, the Clone special meaning to refer to the article. 
  Public void foFetches (Hashtable ht) ( 


  Hashttable newht = (Hashtable) ht.clone (); 

  ) 

  Another problem, as against the target of clone from operations, if the original parent by the other client operating modified, then out to clone the object of the operation will be meaningless. 

  Finally solution: we can modify and other clients after the completion of a clone, that is to say, this particular client first by calling a clone is the means to carry out a series of data acquisition operations. Fact not really a target copy, until other clients modify this object Collection. 

  Proxy use of this programme to achieve this is copy-on-write operations. 

  Proxy Application of a wide range of now popular distributed computing methods, such as RMI and Corba are Proxy mode applications. 





  ↑ Back 

Design Model Factory

  Abstract: Model Factory 

  Definition: to provide Create Object interface. 

  Why? 
  We factory model is the most commonly used model, the famous Jive Forum, the large-scale use of the factory model. 

  Why do I say that the factory model is the most commonly used, because the factory to create a model equivalent to the new object. Factory model is used to create the object. 

  For example, we have a category we want to create Sample Sample targets: 

  Sample sample = new Sample (); 

  If we want to do something before the sample in the creation of conditions, for example, assignment, etc., you can use the constructor function Sample: 

  Sample sample = new Sample (parameters); 

  If created when the sample is not such as to do such a simple thing assignment may be for a long period of the code, if the function is written into the structure, which obviously runs counter to the principles of object-oriented. Package (Encapsulation) and assigned (Delegation); 

  We need to create an example of responsibility and the responsibility of examples of the use of separate, making statements 

  Sample sample = new Sample (parameters); 

  Responsibility is simple: the use of this example Sample As for the task of creating Sample Factory to the factory model. 

  Also, if there is a succession Sample as MySample, according oriented programming interface, we need to abstract into a Sample interface. 

  Sample now is the interface, there are two sub-categories MySample and HisSample we need to instantiate them, as follows: 

  Sample mysample = new MySample (); 
  Sample hissample = new HisSample (); 

  Along with the deepening of the project, Sample may be "many sons by birth," we should be on the son of one of these examples, even worse, may need to revise the code before: Add son was unexpected examples. This is the traditional process can not be avoided. 

  But if you have a sense of beginning use of the factory model, there will be no trouble. 

  You will establish a specialized factory production Sample examples: 

  (Public class Factory 

  Public static Sample creator () ( 

….
  If (which == 1) 
  Return new MySample (); 
  Else if (which == 2) 
  Return new HisSample (); 

  ) 

  ) 




  Well, your procedures, if MySample examples of when. Use 

  Sample sample = Factory.creator (); 

  This, in the whole Sample is not related to the specific sub-category to package effects, it changes to reduce errors, this principle can be very popular to describe it: that the more concrete things done, the easier it is to Fan wrong. Each of these a specific work done minds of the people, on the contrary, the higher the official has done, the more abstract state of the general, the less possibility of error Fan. for procedures like we can realize the truth of life? Ha ha. 

  Well, Back, as the inevitable use of factory, then we understand what the factory model. 

  How to use it? 
  Factory model: simple Factory method (Factory Method) abstract factory (Abstract Factory). 


  On the cases, we use a simple plant. These models there is no obvious difference, in my concept, simple plant should be only one factory method, if we object creation methods becoming more complicated, and we may Factory to the cases into abstract categories, will be packaged in the common part of the abstract category, the use of different parts of sub-categories to achieve: 



  (Public abstract class Factory 

  Public abstract Sample creator (); 


  Public abstract Sample2 creator (); 

  ) 

  Public class SimpleFactory extends Factory ( 

  Public Sample creator () ( 
……
  ) 

  Public Sample2 creator () ( 
……
  ) 


  ) 

  Public class BombFactory extends Factory ( 

  Public Sample creator () ( 
……
  ) 

  Public Sample2 creator () ( 
……
  ) 



  ) 




  Only in the case of an interface Sample products, factory method and abstract factories can create multiple examples of interface products, such as Sample2 Sample3 
  FactoryMethod Often it is just a creation of a single example.    Abstract Factory Group to create a series of examples, these examples are related to each other. 

  For example 1 

  The chart is abstract factory plans: 


  In this map, there are two types of interface products and interface CPU interface RAM; at the same time there are two ways to create: MacProducer and PCProducer, these two methods have created createCPU () and createRAM (), to return to the example of target group is the CPU and RAM, which is different from the two categories of products interface, the surface is related to each other. Therefore it is abstract factory. 

  For example 2 

  We Jive the ForumFactory example: 

  (Public abstract class ForumFactory 

  Private static Object initLock = new Object (); 
  Private static String className = "com.jivesoftware.forum.database.DbForumFactory"; 
  Private static ForumFactory factory = null; 

  Public static ForumFactory getInstance (Authorization authorization) ( 
  / / If no valid authorization passed in, return null. 
  If (authorization == null) ( 
  Return null; 
  ) 
  / / Use the following single-mode if Singleton (factory == null) ( 
  Synchronized (initLock) ( 
  If (factory == null) ( 
……

  Try ( 
  / / Dynamic reprint of Class c = Class.forName (className); 
  Factory = (ForumFactory) c.newInstance (); 
  ) 
  Catch (Exception e) ( 
  Return null; 
  ) 
  ) 
  ) 
  ) 


  / / Now, returning to the proxy. Used to limit the authority of the forum visit return new ForumFactoryProxy (authorization, factory, 
  Factory.getPermissions (authorization)); 
  ) 

  / / Create genuine forum by way of inheritance forumfactory subclass to complete. 
  Public abstract Forum createForum (String name, String description) 
  Throws UnauthorizedException, ForumAlreadyExistsException; 

….


  ) 






  It is through the Jive Forum Posts database system, such as content stored data, if someone simply for the need to expand the file system storage forum posts, the factory method ForumFactory provides a dynamic interface: 

  Private static String className = "com.jivesoftware.forum.database.DbForumFactory"; 

  You can use to create their own development of the alternatives com.jivesoftware.forum.database.DbForumFactory forum can be. 

  In the above section of code sharing in a three models, in addition to the factory model, there are single-mode Singleton, as well as proxy mode, proxy model is largely used to authorized users on the forum's visit because there are two kinds of people visit forum: A is a registered user is a tourist guest, then it is not appropriate authority, and this authority is throughout the whole system, so the establishment of a proxy, similar to the concept of gateways, this can be achieved very good results. 

  Well. Simple description of the above, you should have the factory pattern impression of a simple, if you want to delve into the factory model, there are a lot of network information in English, but I also think that there is no need to study too, is the use of practice, the actual use of Many factory model variants, as long as you know that this probably thinking, I believe that in practice you will be creating the design of the factory model master! 




  ↑ Back 

Let JSP page does not cache

  Abstract: Let JSP page does not cache 

  </ Td> </ tr> <tr> <td width="417" height="35" valign="top" class="ArticleTeitle"> in front of the JSP pages: 

  1. 


  2. 
  <% Response.setHeader ( "Cache-Control", "no-cache ");%> 
  <% Response.setHeader ( "Pragma", "no-cache ");%> 
  <% Response.setDateHeader ( "Expires", -1);%> 

  3. 
  <% @ Page buffer = "none"%> 

  </ Td> <td width="267" valign="top" class="ArticleTeitle"> 
  </ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle"> 

  ↑ Back 

Agents Search java do

  Abstract: java do Acting Search 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="674" border="0"> <tr> <td width = " 269 "> </ td> <td width="395"> today, and occasionally see a foreign website every hour automatically released as a proxy server. 

  Thus, wrote programs to its website address of the proxy server to the preservation of local, and then once every hour. 

  Procedures are written using java, is the principle of grasping the content of the sites, and then analyze the code, stored in c: \ proxy.htm document. 

  Per hour run the java procedure is achieved through planned tasks, the effect was not that bad. 

  If more than one site can be downloaded from the proxy server, coupled with a proxy server to verify the validity of the comparison perfect. 

  If they have the server, it will also be released as per the proxy server. 

  Java source code as follows: </ td> </ tr> </ table>? 
  / ** 
  * Save the proxy server address to c: \ documents proxy.htm 
  * @ Web http://blog.csdn.net/cqq 
  * @ Author Ciqi strong 
  * @ Version 1.00 05/02/01 
  * / 
  Import java.net .*; 
  Import java.io. *; 
  Import java.util.regex .*; 
  Import java.util .*; 

  (Public class JavaProxy 

  Public static void main (String [] args) throws Exception ( 

  System.out.println ( "Acting is generated list … \ r \ n"); 
  JavaProxy ou = new JavaProxy (); 
  File f = new File ( "c: \ \ proxy.htm"); 
  BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (f))); 

  String str = ou.getProxy1 (); 
  Pattern p = Pattern.compile ( " 

  • ");

      String [] = p.split ss (str); 
      String strTmp = ""; 
      String str1 = ""; 

      If (ss.length> 1) ( 
      Bw.write ( "<table width=\"90%\" border=\"0\" align=\"center\" bgcolor=\"#F9F9F9\"> <tr> <td>"); 
      Bw.write ( "Last Modified:" + new Date (). ToLocaleString () + " 

    ");
      For (int i = 1; i    StrTmp [i] = ss. Substring (10, 12) / / Country 
      If (strTmp.equals ( "CN")) 
      StrTmp = "" + strTmp + ""; 
      Str1 = removeAllTag (ss [i]); 
      Bw.write ( "" + i + "" + strTmp + "" + + str1 " 
    ");

      ) 
      Bw.write ( "</ td> </ tr> </ table>"); 
      ) 
      Bw.close (); 
      System.out.println ( "complete"); 
      System.exit (0); 

      ) 


      Private String getProxy1 () ( 
      Int i = 0; 
      Try ( 
      URL url = new URL ( "http://www.cybersyndrome.net/pla.html"); 
      BufferedReader br = new BufferedReader (new InputStreamReader (url.openStream ())); 
      String s = ""; 
      StringBuffer sb = new StringBuffer (""); 
      While ((s = br.readLine ())!= null) ( 
      I + +; 
      If (i> 80 & & i <89) ( 
      Sb.append (s + "\ r \ n"); 
      ) 
      ) 
      Br.close (); 
      Return sb.toString (); 
      ) Catch (Exception e) ( 
      Return "error open url" + e.toString (); 
      ) 
      ) 

      Public static String removeAllTag (String src) ( 
      Return src.replaceAll ("<[^>]*>", ""); 
      ) 
      ) 


      Then javac JavaProxy.java 

      Java JavaProxy 

      Waiting for a good result.    </ Td> </ tr> <tr> 

      ↑ Back 

    Singleton pattern in Java Application

      Abstract: Singleton pattern in Java Application 

      </ Td> </ tr> <tr> <td width="513" height="35" valign="top" class="ArticleTeitle"> procedures frequently such a request, the entire program run by only one example use. 
      For example: the database connection pool, the system configuration parameters, the Java API Runtime, Calendar … 
      How to achieve this demand. 
      The code below 
      (Public class ConnectionPoolManager 
      Private static instance = null; 
      Private ConnectionPoolManager () ( 
      / / Do some initialize work 
      ) 

      Public static void getInstance () ( 
      If (instance == null) ( 
      Instance = new ConnectionPoolManager (); 
      ) 
      Return instance; 
      ) 

      Public Connection getConnection () ( 
      ) 
      ) 

      ConnectionPoolManager use 
      (Public class QueryFunctions 
      Public static Collection findStudentByName (String name) ( 
      ConnectPoolManager connectionPoolManager = ConnectionPoolManager.getInstance (); 
      Connection conn = connectionPoolManager.getConnection (); 
      / / Query database 
      ) 
      ) 

      1.instance is a private, assigned at the beginning of the null, only through external getInstance method he can be. 

      2. Constructor is private, this is very important, this is the only guarantee of their own can call, the other can not call this type constructor function. 

      3.getInstance methods: 
      If statement to ensure that only one instance of a ConnectionPoolManager exist only in the first when the call was established. 

      Below is another example: java.lang.Runtime the realization of the following: 
      (Public class Runtime 
      Private static Runtime currentRuntime = new Runtime (); 
      Public static Runtime getRuntime () ( 
      Return currentRuntime; 
      ) 

      / ** Don't let anyone else instantiate this class * / 
      / / Gouken 
      Private Runtime () () 
      ) Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document.getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> <td width="171" align="center" valign="top" class="ArticleTeitle"> 
      </ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle"> 

      ↑ Back 

    keep looking »