Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Java factory pattern (Factory mode)     - Linux environment installation of rvm and ruby (Linux)

- Using Maven to download Spring (Linux)

- Linux Open coredump (Linux)

- Erlang concurrency and foundation (Programming)

- How to use the TF / SD card making Exynos 4412 u-boot boot disk in Ubuntu (Linux)

- Execute command sentence can result in equipment permanently bricked in Linux laptop (Linux)

- Linux command ls (Linux)

- How to enhance the Nagios server security (Linux)

- Linux ./configure --prefix command (Linux)

- ssh using scp: / directory: Permission denied (Server)

- CentOS source installation GitLab Chinese Version (Server)

- java.net.NoRouteToHostException of Hadoop problem: no route to host (Server)

- C ++ Replication Control: Assignment operators and destructors (Programming)

- Linux /var/spool/ insufficient clientmqueue space solutions (Linux)

- Hadoop 2.2.0 installation development environment (standalone pseudo-distributed mode) (Server)

- Use LVM partition on Ubuntu and easily adjust the snapshot (Linux)

- Linux system man help tips (Linux)

- Linux-du and df command (Linux)

- Linux Desktop allows exceptionally different launch applications (Linux)

- MongoDB data replication and data slices (Database)

  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.
- Ubuntu 14.04 Configuring cuda-convnet (Linux)
- How to troubleshoot error java.lang.NoSuchMethodError (Programming)
- CentOS 6 / Linux su: Unable to set user ID: Resource temporarily unavailable (Linux)
- Terminal multiplexing tool tmux use (Linux)
- The Linux kernel and AVL tree in red-black tree (Programming)
- rpm package specify the installation path (Linux)
- How to cool down your Ubuntu system (Linux)
- Commonly used Linux system camouflage method (Linux)
- Check with Hello World Docker installation (Server)
- MySQL / MariaDB database master-slave replication (Database)
- To install Oracle Database Details and FAQ Summary under CentOS (Database)
- How to configure MariaDB replication in CentOS Linux (Database)
- Ant command-line compiler Android project (Programming)
- Java string concatenation techniques (StringBuilder tips) (Programming)
- Upgrading to MySQL 5.7 partitioning problem solving (Database)
- Those things packaged using Gradle to Android (Programming)
- When Linux virtual machine to another copy of the operating system, a static IP NAT mode Invalid (Linux)
- To learn linux security (Linux)
- extundelete: the Linux-based open source data recovery tools (Linux)
- Linux Regular expressions grep and egrep (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.