IT Pioneer Senior Consultant Grid Liu
Grid Liu serves as a senior consultant in the Pioneer, responsible for J2EE technology consultant consulting and training. Summary Keywords: Design Mode Creating Mode Simple Factory Method Abstract Factory 1 Create mode 1.1 Creating an object to create an object in object-oriented language, using Class constructor, generate an object (instance instance instance of this class). For example, the new example of the Java language, such as the instance of a Customet class, Customer Object = New Customer (); and each object has a constructor (can be a default constructor), it is responsible for the creation of the object, (Some The language also has a destructor, responsible for the release of objects, however Java uses garbage collector completion object recycling) 1.2 Why do you need to create a model? We already know that in the Java language to create objects, but what you need to create mode, The following reasons are: n Due to the principle of design patterns, the interface is programmed, rather than implementation, because the interface is used in the interface (interface), but the interface There are generally multiple implementation classes, so there is an example of how to choose which implementation created, as shown below: Therefore, our traditional creation of objects is not conducive to expand, modify. Such as Interface Object = New Implementtion1 (); so that once we modified to other implementations, you need to modify the code more, so you need to add creating objects. N Names must be constructor, name limited to construct the function itself unable to describe the object returned, and the use of the right factory method can make the class easier, the resulting code is easy to read. n Each time you created a new object returns a new object every time you create, but you need only one instance in the actual project, or to use Cache to repeatedly use the object you have created. n Each return type is a type of specific object constructor returned, both of which are specific types. The use of factory models can return sub-type. N Re-use the process of creating an object. We know, some objects are quite complicated, which refers to the Object after New, must be used after a series of assignments. Thus we need the process of operations such as assignment. 1.3 Creating a model purpose purpose purpose mode is the instantiation process of an abstract object. It can help a system independently created, who creates, and what is created. It can be changed to a stand-alone behavior set that was previously transferred to a hard-coded manner that was previously passed through new class (). Therefore, these behaviors can be reused, combined, and the process of creating objects is easy to modify, maintain, and expand.
1.4 Creative Mode Considerations When you create an object in the actual system, you need to consider the following: n Dynamic determination which objects created (determine the implementation class that created an interface) N, who creates these objects (Yes External object, or itself, or static class inheritage) n Dynamic decisive how to create objects (new object also uses cache or copy an object) n Decide how to combine or represent these objects () 1.5 Create mode category N Create mode of the Class Creation Mode class uses inheritance, delays the creation of the class to the subclass, enabling the client's creation mode of the information N object to get the creation mode of the object, and the creation of the object is to create the creation process of the object. The delegation gives another object, which dynamically determines which specific class instances will be obtained, and how these classes are created and combined 2 Simple factory model 2.1 intention N simple factory is created by a factory object Which product class is found. The simple factory is the simplest mode (I think there is also a template method mode), the most easily understood mode, which introduces the use of traditional way to create an object's disadvantage, so create an object through externalization behavior, so we pass a method, It is responsible for the creation of objects. Therefore, this traditional creation process customer object = new customer object () is changed to Customer Object = CreateObject (); public customer createObject () {Return New New need ();} This way we create an object in the system to use a function To do it, once the system changes, we only need to modify this function. In actual projects, it is impossible to use this type of creating objects, and we should consider that we can package this selection to implement the business logic to this function when there are multiple implementations in an interface. 2.2 Structure and Participant Simple Factory mode is an example of which specific product classes can be created by a factory class. N Factory (CREATOR) Role: This role is the core of factory method model, which contains products in accordance with certain business logic. The factory class creates a product object under the direct call of the client, which is often implemented by a specific Java class. N Abstract Product (Product) Role: The class that serves this role is the parent class of the object created by the factory method mode, or the interface they share. Abstract product roles can be implemented with a Java interface or Java abstract class. N Specrete Product Role: Any object created by the factory method mode is an instance of this role. The specific product role is implemented by a specific Java class. 2.3 Sample 2.3.1 XML parser 2.3.1.1 Overview JAXP is used to use the programming interface written in Java Language (Java API for XML Processing) for XML document processing. JAXP supports DOM, SAX, XSLT and other standards.
In order to enhance the flexibility in JAXP, Sun's Specification Developers specially designed a PlugGability Layer for JAXP. Under the support of PLUGGABILITY LAYER, JAXP can implement the DOM API, SAX API's various XML parsers (for example Apache Xerces) The benefits of Pluggability Layer are: We only need to be familiar with the definition of the JAXP's programming interface, without having to know more about the specific XML parsers used. For example, in a Java program, the XML parser Apache Crimson is called via JAXP to process the XML document, if we want to use other XML parsers (such as apache Xerces) to increase the performance of the program, then the original program code may not Need to change, you can use the configuration directly. This is actually like our JDBC driver, Sun offers some interfaces, and then there are various manufacturers to implement. Therefore, Sun defines an interface DocumentBuilderFactory that uses the DOM mode. It actually uses the factory method model to be introduced. It is mainly responsible for creating some DOM classes. Here we introduce itself. Therefore, different DOM parsers have different implementations, such as Apache Xerces or Oracle, etc. Therefore, our developers should face a problem to create these implementations, here is a simple factory method. You must first obtain a DocumentBuilderFactory prior analysis target, and then use it to generate other objects such as DocumentBuilder the like, which process is as follows: try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = factory.newDocumentBuilder (); document = builder.parse (New file (SAXPARSEEXCEPTION SPE) {} This here we know DocumentBuilderFactory Factory = documentbuilderfactory.newinstance (); is created by simple factory, in fact it is completed by FactoryFinder Created 2.3.1.2 Implementation Source Code We can implement the source code through the FactoryFinder as follows: It first obtains the parser class name by configuring the information, and then instantiates this class. The following configuration: javax.xml.parsers.DocumentBuilderFactory = org.apache.xerces.jaxp.DocumentBuilderFactoryImpl try {Class spiClass = Class.forName (className); return spiClass.newInstance ();} catch (ClassNotFoundException x) {} } So if we need to replace the XML parser, simply modify this configuration information, you can complete, without the need to modify the source code. This actually reflects the advantages of interface-oriented programming.
2.4 Implementation Method 2.4.1 Implementation of Factory Method Generally Contains Selection of Conditions in a factory class to generate which class: public class create {public static product factory (int i) {if (i == 1) {Return New constreteProduct1 ();} else if (i == 2) {Return New ConcreteProduct2 ();}}} This code is full of IF ELSE is difficult to maintain, which does not conform to Open-Closed principles, so in practical applications When there is a simple factory mode, there will be no one. The parameters and specific implementations are generally configured as the implementation of our XML parser, which is configured by parameter javax.xml.parsers.DocumentBuilderFactory. If you use Apache, set org.apache.xerces.jaxp.DocumentBuilderFactoryImpl, You can only modify this configuration if you modify other parsers.
We know that in two ways can be created in two ways according to a Class's name, string classname = fromconfiggetClassName (); / / here Class ClassInstance = Class.Forname (ClassName) .NewInstance (ClassName) here ); Or by the following String ClassName = fromConfiggetClassName (); // Here, Class ClassInstance = getClass (). GetClassLoader (). LoadClass (ClassName) .newinstance (); This generally configured to Java according to parameters Properties Or in the XML file, as the action in Sun PetStore is based on the client's request URLPath, generate the corresponding action, actually in Struts, configuring information
The three roles of the above structure will have various mergers such as plant roles and product roles, abstract products and specific products. This is described in "Java and Mode". 2.4.3 Caches About the product In our above examples, every time you create a new object, however, cache is often used in actual applications, such as the creation of Struts an action, it makes only only An example, of course, this creation cannot use Singleton mode, as this will implement those methods for each class, so they use a cache, first judge, if an instance already exists, if not created. The following Struts source protected Action processActionCreate (HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException {// Acquire the Action instance we will be using (if there is one) String className = mapping.getType (); Action instance = null; synchronized (actions) {// return any existing Action instance of this class instance = (Action) actions.get (className); if (instance = null!) {return (instance);} // Create and return a new Action instance Try {instance = (action) RequestUtils.ApplicationInstance (classname); instance.setservlet (this.servlet); Actions.put (classname, instance);} catch (throwable t) {return (null) } Return (Instance);} Note: If I can use a simple factory in one system, you can use another factory to cache, which uses more than two simple factory methods, so It is necessary to abstract the factory, thus introducing the following mode - factory method mode. 3 Factory Method 3.1 Intensive Define the interface to create an object, which allows the subclass to instantize which class. FactoryMethod will delegate instantiated work to subclasses. This sentence is taken from "design mode", but I think it is actually using it primarily because it is abstract, using multiple factories (achieving different strategies) to create products. If you understand the simple factory, you can think that he is an abstraction of the simple factory.
Abstract plants, can have different factories to achieve. Note: I understand that the definition of the factory method is class mode. He uses inheritance to complete the creation. If you are familiar with Templeate Method mode, it is easy to understand to this way, we define an abstract method, this method to complete the creation of the product, There is a template method, it is a skeleton calling abstraction method, how to achieve this abstract method, so it is realized, using different products. The structure is as follows: Simple code: public abstract class appliction {// This method is factory method, implemented by subclavab implement public abstract document createdocument (); // template method, using factory method Pubic void newDocument () {/ / Using the factory method, obtain DOC, and actually have subclasses, // Here you can see that the creation of the object is implemented by inheritance, it is static, compiled, is determined // rather than through the object's delegation Therefore, it belongs to the class creation mode Document Doc = createdocument (); doc.open (); .................... doc.save ();}} specific Factory implements factory methods: public class myappliaction extends Applic class myappliaction extends Appliction {public document create () {return new myDocument ();}}, but I feel, this way is gradually reduced. 3.2 Structure and Participant CREATOR Dependence Its sub-class defined factory method, thereby returning the corresponding concreteproduct. • Product ° Define Factory Method Creating an Object of Objects • ConcreteProduct ° Implementation Product Declared Interface • Creator ° Declaration Returns the object of the product. At the same time, Creator is possible to define the default implementation of the factory method that returns the default ConcreteProduct. ° Mixel Call Factory Method Creating Product Objects • Concretecreator Overwrite Factory Method, Returns an instance of ConcreteProduct. 3.3 In any case where I think learning mode is used, you must understand the intention, structure, usability of a pattern. Only in this way can you use it in a practical project, the details of the specific implementation can read the information, only when you understand the mode, you will naturally apply mode. • The class cannot predict the type of the created object. In this case, there are many instances in J2EE specification. Everyone knows that because Sun's specification is actually some interface, then uses individual manufacturers to implement, so it is instantiated, I don't know how to instantiate those specific implementations at all. Therefore, their factories are also abstract, realized by specific manufacturers, and the example of us is this situation. • Class makes its subclass to determine the object created. This is because we have multiple specific factories to create the same product, just because they have different strategies, so they need to abstract the plant, which is generally appearing in our actual project.
· The class assigns responsibilities to one of several auxiliary subclasses, and the specific information of the assignees will be localized. This is the example of our above, which is a special case of the Template Method mode. 3.4 Sample Code We introduce DocumentBuilderFactory in simple factory mode to create, in the process of parsing with DOM, is the use of DocuMNTBuilder to return to Document to obtain, their information. DocuemntBuilderFactory but it does not know the specific implementation class DocumntBuilder, so DocuemntBuilderFactory public abstract class DocumentBuilderFactory {public abstract DocumentBuilder newDocumentBuilder () throws ParserConfigurationException;} public class DocumentBuilderFactoryImpl extends DocumentBuilderFactory {public DocumentBuilder newDocumentBuilder () throws ParserConfigurationException {try {return new DocumentBuilderImpl (this, attributes);} catch (SAXEXCEPTION SE) {Throw new ParserConfigurationException (se.getMessage ());}}} Please review the process of using JAXP using simple factories and factory methods. 3.5 Discussion Time During discussion 3.5.1 Creating the object to create object n Use the parameterized mode to obtain object n Use the category variable method to create object n Use the balance category to create objects 3.5.1.1 Create an object using a parameterized manner This is also the way we use in a simple factory. Through a variable information, we decide which specific object created, generally use configuration information to reach no modification of the source code.
public abstract class Application {public abstract Document CreateDocument (int select); public void NewDocument () {int select; Document doc = CreateDocument (select); doc.Open (); doc.Save (); doc.Close ();} } public class MyApplication extends Application {public Document CreateDocument (int select) {if (select == 1) return new TextDocument (); if (select == 2) return new DocDocument (); return null;}} 3.5.1.2 use Category variables are subject to this way, it is strict, not to create a mode, because it does not create an object, and use the outer into the object, listed here, for your reference. public abstract class Application {protected Document doc; // a variable public Application () {} public abstract Document CreateDocument (); public void NewDocument () {doc = CreateDocument (); doc.Open (); doc.Save (); doc.Close ();}} public class MyApplication extends Application {public MyApplication () {} public Document CreateDocument () {return doc; // and returns new objects, but not outside of the successor}} public class ExampleFactory3 {public static Void main (string [] args) {myApplication app = new myapplication (); app.doc = new textDocument (); // passed object App.NewDocument ();}} 3.5.1.3 Use Balance mode to create an object This if there is one Products, there is a corresponding factory class, there is a lot of this example in the design mode, which is the disadvantage to increase the number of factory categories. If it is not special, it is not used. 4 Builder Mode 4.1 Introduction of Builder Mode (Considering from the perspective of reconstruction) The Builder mode is to separate the assembly process of constructing complex objects and its creation part with the product object. Note: It is a decoupling assembly process and creates a specific part. Process implementation uses Director, which only cares about the process of assembling components, and does not care about the creation of each particular part. BUILDER is defining the interface of the creation of components and then implements different parts by the specific creator Concretebuilder.
Since use is a Builder interface in Director, you can reuse the creation process because different Concretebuilders, although the creation of parts is different, but the assembly process is the same. We assume that each car has 4 wheels, an engine and other components, if not used, in accordance with the general method, in the constructor, 4 wheels, 1 engine, and then assembled. The following is as an example: public class polo {// In the constructor, the part is created, and then the component wheel OBJ1 = NEW wheel (); // is used to assemble the component this. Wheel S.Add (obj1); wheel obj2 = new wheel (); this. Wheel S.Add (Obj2); // 省 省 省 其他 两 个 车 ... ...; Automotive engine objnessan = new car engine (); this. Car engine = objnessan; ...............} This is how we didn't use the Builder, so that the constructor is complicated. Because it is responsible for creating specific components such as (4 wheels, and an engine), then need to be assembled into product polo. If we add a type of HONGDA of a car, although they are different, the specific components are different, but the assembly process is the same as the abstraction of the components (4 wheels and an engine). Such a violation of OO's idea is reused, so we put the process of assembling, and create parts, from the construction of the product, in fact, it is to simplify the product constructor, encapsulate objects, and reuse. So our externalization is responsible for creating car parts and assembly processes, because the components created are different, such as POLO's wheels and HONGDAs, but their assembly process is the same, so we define, several methods will be Specific subclass implementation, and a specific method, it is responsible for assembly process. It will be clear that this is a template method mode.
// It abstracts the creation of components, defines a skeleton method public class builder {public void builder wheel (int N) {}; public void builder engine () {}; public void director construction process () {THIS.BUILDER Wheel (4 ); This.builder wheel ();}} public class polobuilder extends builder {private polo polo = new polo (); public void builder wheel (int N) {for (int i = 0; i