Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java factory pattern (Factory mode)     - Linux tar compressed exclude a folder (Linux)

- MySQL stored procedures execute dynamic sql statement (Database)

- build Android environment on Ubuntu 12.04 (Server)

- MongoDB 3.2 Cluster Setup (Database)

- Linux NIC configuration (Linux)

- Oracle VirtualBox Problem Solving Case (Linux)

- 30 minutes with your Quick Start MySQL Tutorial (Database)

- The signature can not be verified under Debian (Linux)

- Glibc support encryption by modifying the DNS (Programming)

- How do you access Dropbox Linux command line (Linux)

- You know the difference between URL, URI and URN among you (Linux)

- Manager Docker browser (Server)

- Unetbootin make use U disk loading Linux system (Linux)

- Android and OpenCV2.4.4 build an image processing framework (2013 edition) (Linux)

- Figlet use (Linux)

- Install the free open source financial software GnuCash 2.6.6 under Ubuntu (Linux)

- Oracle to start to solve the error ORA-27102 (Database)

- Python interview must look at 15 questions (Programming)

- Talking about the shortcomings and deficiencies of the firewall (Linux)

- Build Eclipse + Maven + Scala-IDEA the Scala Web development environment (Server)

 
         
  Java factory pattern (Factory mode)
     
  Add Date : 2017-08-31      
         
       
         
  Factory pattern definition: Provides an interface for creating objects.

Why use the factory pattern

Factory model is our most commonly used model, the famous Jive forum, the extensive use of the factory pattern, the factory pattern in the Java programming system can be said to be everywhere.

Why is the factory pattern so common? Because the factory model is equivalent to the creation of examples of the new object, we often have to generate examples of objects under the Class Class, such as Aa = new A () factory model is used to create the instance object, so after the new multi- Whether you can consider the practical factory pattern, although doing so, may do more work, but will give you more scalability and minimize the amount of system modifications.

Let's take the class Sample as an example, if we want to create a Sample instance of Sample:
    Sample sample = new Sample ();
However, the reality is that we usually have to do in the creation of examples of sample initialization work, such as the value of the database query.

First of all, we think that you can use the Sample constructor function, so that the instance is written as:
    Sample sample = new Sample;
However, if you create a sample instance of the initial work done is not as simple as assignment, may be a very long piece of code, if it is also written in the constructor, then your code is difficult to read (Refactor refactor will need).

Why the code is ugly, beginners may not have this feeling, we analyze the following, initialization work is a very long piece of code that a lot of work to be done, a lot of work into a method, the equivalent of a lot of eggs on A basket, it is very dangerous, which is back to the principles of object-oriented Java, object-oriented Encapsulation (Encapsulation) and distribution (Delegation) tells us, as long as the code distribution "cut" into each, The segment is then "encapsulated" (reducing the coupling between segments and segments), so that the risk will be dispersed, if later need to be modified, as long as the change of each paragraph will not happen again.

In this case, first, we need to separate the work of creating the instance from the work of using the instance, that is, separating the bulk of the initialization work needed to create the instance from Sample's constructor.

At this time we need to Factory Factory pattern to generate the object, and can not use the above simple new Sample (parameters). Also, if Sample has an inheritance, such as MySample, that is programmed as an interface, we need to abstract the Sample into an interface. Now Sample is the interface, there are two sub-categories MySample and HisSample. We will instantiate them as follows:
    Sample mysample = new MySample (); Sample hissample = new HisSample ();
With the project in depth, Sample may also "give birth to a lot of son out", then we have these son one by one instance, even worse, may also have to modify the previous code: Joined later gave birth to the son of the instance. This is unavoidable in traditional programs.

But if you start with the conscious use of the factory pattern, the trouble is gone.

Factory method

You will build a factory that specializes in producing Sample instances:

Public class Factory {
    Public static Sample creator (int which) {
        // getClass Generating a Sample You can typically load classes using dynamic classes.
        If (which == 1)
            Return new SampleA ();
        Else if (which == 2)
            Return new SampleB ();
    }}
}}
Then in your program, if you want to instantiate Sample when used
    Sample sampleA = Factory.creator (1);
Thus, in the whole does not relate to the specific subclass Sample to achieve the effect of packaging, it will reduce the chance of error correction, this principle can be used very popular words to metaphor: the more specific things to do, the more easily Fan wrong. This has done a specific job of each person have deep experience, on the contrary, the higher the officer to do, say the more abstract the more general, the less likely to Fan error. As if we are from the programming process can realize the truth of life?

First of all, you need to define the product interface, such as the above Sample, the product interface under the Sample interface implementation class, such as SampleA, followed by a factory class, used to generate the product Sample

Further a little more complex, that is, to expand on the factory class, the factory class also inherited its implementation class concreteFactory.

Abstract Factory

The factory pattern is the Factory Method and the Abstract Factory.

The difference between these two modes is the level of complexity required to create the object. If our method of creating an object becomes more complex, as in the factory method above is to create an object Sample, if we have a new product interface Sample2.

Here suppose: Sample has two concrete class SampleA and SamleB, and Sample2 also has two concrete class Sample2A and SampleB2, then we will be the example of the factory into an abstract class, the common part of the package in the abstract class, the use of different parts Sub-class to achieve, here is the example of the Factory to expand into an abstract factory:

Public abstract class Factory {
    Public abstract Sample creator ();
    Public abstract Sample2 creator (String name);
}}
Public class SimpleFactory extends Factory {
    Public Sample creator () {......... return new SampleA}
    Public Sample2 creator (String name) {......... return new Sample2A}
}}
Public class BombFactory extends Factory {
    Public Sample creator () {... return new SampleB}
    Public Sample2 creator (String name) {... return new Sample2B}
}}
As you can see from the above, each of the two plants produces a Sample and a Sample2, and you may wonder why I can not use two factory methods to produce Sample and Sample2, respectively.

Another key point of the abstract factory is that there is a connection between the Sample and the Sample2 methods in the SimpleFactory, so it is necessary to bundle the two methods in a class. The factory class has its own characteristics. Manufacturing process is uniform, such as: manufacturing process is relatively simple, so the name is SimpleFactory.

In practice, the factory method used more than some, but also and dynamic class loader combined with the application,

Java factory pattern example

We Jive's ForumFactory example, this example in the previous Singleton model, we discussed, and now to discuss its factory model:

Public abstract class ForumFactory {
    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;}
        // The following uses Singleton singleton mode
        If (factory == null) {
            Synchronized (initLock) {
                If (factory == null) {...
                        Try {
                            / / Dynamic reproduced class
                            Class c = Class.forName (className);
                            Factory = (ForumFactory) c.newInstance ();
                        } Catch (Exception e) {return null;}
                 }}
            }}
        }}
        // Now, return proxy. Used to restrict access to the forum
        Return new ForumFactoryProxy (authorization, factory, factory.getPermissions (authorization));
    }}
    // really create the forum method inherited from the subclass of forumfactory to complete.
    Public abstract Forum createForum (String name, String description)
        Throws UnauthorizedException, ForumAlreadyExistsException;
    ...
}}
Because now Jive is stored through the database system, such as forum posts and other content data, if you want to change to the file system through the implementation of this factory method ForumFactory provides a dynamic interface:
    Private static String className = "com.jivesoftware.forum.database.DbForumFactory";
You can use their own method to create forums instead of com.jivesoftware.forum.database.DbForumFactory can.

In the above section of the code in a shared three models, in addition to the factory model, there are Singleton single-state model, and the proxy model, proxy mode is mainly used to authorize the user's visit to the forum, because the visit forum there are two kinds of people: Is a registered user is a guest guest, then the corresponding permissions are not the same, and this authority is running through the system, so the establishment of a proxy, similar to the concept of gateway, can be very good to achieve this effect.

Look at the CatalogDAOFactory in the Java pet store:

Public class CatalogDAOFactory {
    / **
      * This method makes a special subclass to implement the DAO schema.
      * The specific subclass definition is in the J2EE deployment descriptor.
    * /
        Public static CatalogDAO getDAO () throws CatalogDAOSysException {
            CatalogDAO catDao = null;
            Try {
                InitialContext ic = new InitialContext ();
                // Dynamically load CATALOG_DAO_CLASS
                // You can define your own CATALOG_DAO_CLASS, so you do not have to change too much code
                / / Under the premise of the great changes to complete the system.
                String className = (String) ic.lookup (JNDINames.CATALOG_DAO_CLASS);
                CatDao = (CatalogDAO) Class.forName (className) .newInstance ();
            } Catch (NamingException ne) {
                Throw new CatalogDAOSysException ( "CatalogDAOFactory.getDAO: NamingException while getting DAO type: \ n" + ne.getMessage ());
            } Catch (Exception se) {
                Throw new CatalogDAOSysException ( "CatalogDAOFactory.getDAO: Exception while getting DAO type: \ n" + se.getMessage ());
           }}
           Return catDao;
    }}
}}
CatalogDAOFactory is a typical factory method, catDao through dynamic class loader className access CatalogDAOFactory specific implementation of subclasses, the realization of subclasses in the Java pet store is used to operate catalog database, the user can according to the type of database, customize their specific Implementation of sub-categories, their sub-class name can be given to CATALOG_DAO_CLASS variables.

Thus, the factory method for the system structure does provide a very flexible and powerful dynamic expansion mechanism, as long as we replace the specific factory method, the rest of the system without a little change, it is possible to make changes in system functionality.
     
         
       
         
  More:      
 
- Some security configuration of Linux systems (Linux)
- The difference between equals and == in Java (Programming)
- tcpdump Linux system security tools (Linux)
- CentOS 6.4 RPM install MySQL-5.6.22-1 (Database)
- Java abstract class instantiation (Programming)
- Intel Graphics Installer 1.0.3 released, support for Ubuntu (Linux)
- MySQL flip-flop (Database)
- MongoDB query statistics grouping remove duplicate records (Database)
- Monitor log file (listener.log) (Database)
- 6 common PHP security attacks (Linux)
- Deb package installation method under ubuntu (Linux)
- To compile and install Redis Linux and master-slave replication configuration (Database)
- Loop arrays in C language is not easy to find a bug (Programming)
- MySQL5.6.12 Waiting for commit lock lead to hang from the library housing problem analysis (Database)
- CentOS5 installation Nodejs (Linux)
- systemctl Command Complete Guide (Linux)
- Zorin OS: Linux novice most personal desktop system should be used (Linux)
- X security settings in Ubuntu (Linux)
- How the program is executed (Programming)
- FastDFS installation and deployment (Server)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.