Java Factory Pattern

After reading so many explanations about the factory mode, I still think this article is easy to understand, so I posted it and shared it with everyone.
1. The introduction
            says that ten years ago, there was a **** family with three cars - Benz, BMW, Audi, and hired a driver to drive for him. However, it is always weird when the **** gets in the car: after getting on the Benz, he tells the driver, "Drive a Mercedes-Benz!"; ". You must say: This man is sick! Just say you can't drive? !
             And when the behavior of this **** is put into our program design, it will be found that this is a common phenomenon. Fortunately, this sickly phenomenon can be avoided in OO (object-oriented) languages. The following introduces the theme of our article based on the Java language: the factory pattern.

Second, the classification
           factory mode is mainly to provide a transition interface for creating objects, so as to shield and isolate the specific process of creating objects and achieve the purpose of improving flexibility.

Factory patterns are divided into three categories in Java and Patterns:              1
) Simple Factory

2) Factory Method

3) Abstract Factory
abstract, and more general.
             GOF divides factory patterns into two categories in the book "Design Patterns": Factory Method and Abstract Factory. Think of the SimpleFactory pattern as a special case of the Factory Method pattern, and the two are grouped together.

Either can be used in this article using the "Java and Patterns" taxonomy. Let's take a look at how these factory models "cure".

Third, the simple factory pattern The

simple factory pattern is also known as the static factory method pattern. The renaming shows that the pattern must be very simple. It exists for a simple purpose: to define an interface for creating objects.
       Let's take a look at its composition first:

         1) Factory role: This is the core of this model and contains certain business logic and judgment logic. In java it is often implemented by a concrete class.

         2) Abstract product role: It is generally the parent class inherited by the concrete product or the implemented interface. In java, it is implemented by an interface or an abstract class.

         3) Specific product role: The object created by the factory class is an instance of this role. Implemented by a concrete class in java.
So how to use the simple factory pattern? We will use a simple factory model to transform the way that customers ride in a car - now they only need to sit in the car and say to the driver: "Drive".

Code: //Abstract product role
public interface Car{
     public void drive();
}

//Concrete product role
public class Benz implements Car{
     public void drive() {
         System.out.println("Driving Benz ");
     }
}

public class Bmw implements Car{
     public void drive() {
       System.out.println("Driving Bmw ");
     }
}
. . . (I won't write Audi :P)

//Factory class role
public class Driver{
           //Factory method. Note that the return type is abstract product role
             public static Car driverCar(String s)throws Exception{
                   //Judgment logic, return specific Product role to Client
                   if(s.equalsIgnoreCase("Benz"))
                       return new Benz();
                   else if(s.equalsIgnoreCase("Bmw"))
                           return new Bmw();
                                 …    
                           else throw new Exception();
             . . .

//Welcome to the **** family...
public class Magnate{
             public static void main(String[] args){
                       try{
                             //Tell the driver I am taking a Mercedes-Benz                    
                                 Car today car = Driver.driverCar("benz" );
                             //The next command: drive                            
                                 car.drive();
                       . . .


         The program can run after filling in the other information vacant in this program. If you put all your classes in one file, don't forget that only one class can be declared public. This program runs through jdk1.4.
This is the simple factory pattern. How about it, it's easy to use, right? So what benefits does it bring?
           First of all, after using the simple factory pattern, our program is no longer "sick" and more in line with the real situation; and the client is exempted from the responsibility of directly creating product objects, but only responsible for "consuming" products (as **** households).

          Let's analyze the simple factory pattern from the open-closed principle (open for extension; closed for modification). When the first customer adds a car, as long as it conforms to the contract formulated by the abstract product, it can be used by the customer as long as the factory class is notified. So for the product part, it complies with the open-closed principle; but the factory part does not seem to be ideal, because every time a car is added, corresponding business logic or judgment logic must be added to the factory class, which is obviously a violation of the open-close principle. closed principle. It is conceivable that factories are very passive for the addition of new products. For such a factory class (in our case, the driver driver), we call it the omnipotent class or the god class.
             The example we gave is the simplest case, and in practical applications, it is likely that the product is a multi-level tree structure. Since there is only one factory class in the simple factory pattern to correspond to these products, this may tire our gods and tire us programmers :(
           So the factory method pattern appears as a savior.
Fourth, the factory method pattern
             The factory method pattern removes the static properties of the factory method in the simple factory pattern, so that it can be inherited by subclasses. In this way, the pressure focused on the factory method in the simple factory pattern can be shared by different factory subclasses in the factory method pattern.

You You should roughly guess the structure of the factory method pattern, let's take a look at its composition:

       1) Abstract factory role: This is the core of the factory method pattern, which has nothing to do with the application. It is an interface that a specific factory role must implement or a parent class that must be inherited. In java it is implemented by abstract classes or interfaces.

       2) Specific factory role: it contains code related to specific business logic. Called by the application to create the corresponding product-specific object.

       3) Abstract product role: it is the parent class inherited by the concrete product or the implemented interface. In java, there are generally abstract classes or interfaces to implement.

       4) Specific product role: The object created by the specific factory role is an instance of this role. It is implemented by concrete classes in java.
      The Factory Method pattern replaces the "God Class" in the Simple Factory pattern with multiple subclasses that inherit from the abstract factory role. As mentioned above, this shares the pressure on the object; and this makes the structure flexible - when a new product (ie, the owner's car) is produced, just follow the abstract product role, abstract factory The contract provided by the role is generated, then it can be used by the client without having to modify any existing code. It can be seen that the structure of the factory role is also in line with the open-closed principle!

      Let's stick to the old rules and use a complete example to see how the various roles of the factory pattern are coordinated. In other words, the business of the **** household is getting bigger and bigger, and there are more and more cars. This is hard for the driver, he has to remember and maintain any car, and he has to use it! So the **** family sympathized with him and said: For the sake of you and me for so many years, you don't have to work so hard in the future, I will assign you a few people, you just need to manage them well! Thus, the management of the factory method pattern appeared. The code is as follows:

Code:
//Abstract product role, the specific product role is similar to the simple factory pattern, but it becomes more complicated, which is omitted here.
//Abstract factory role
public interface Driver{
       public Car driverCar();
}
public class BenzDriver implements Driver{
         public Car driverCar(){
               return new Benz();
         }
}
public class BmwDriver implements Driver{
         public Car driverCar(){
           return new Bmw();
         }
}

//Should form a corresponding relationship with specific products. ..
//Please Mr. ****
public class Magnate{
         public static void main(String[] args){
                     try{
                       Driver driver = new BenzDriver();
                       Car car = driver.driverCar();
                       car.drive( );
                     }
             ...
}


It can be seen that the addition of the factory method makes the number of objects grow exponentially. When there are many types of products, there will be a large number of corresponding factory objects, which is not what we want. Because if this situation cannot be avoided, consider using a combination of the simple factory pattern and the factory method pattern to reduce factory classes: that is, use a simple factory for similar types on the product tree (usually siblings in the leaves of the tree) mode to achieve.

V. Summary

The factory method pattern seems to have perfectly packaged the creation of the object, so that the client program only deals with the interface provided by the abstract product role. So do we have to have factories all over the code? You don't have to. Maybe in the following cases you can consider using the factory method pattern:

     1) When the client program does not need to know the creation process of the object to be used.

     2) The object used by the client program may change, or it does not know which specific object to use at all.

Do simple factory patterns and factory method patterns really avoid code changes? no. In the simple factory pattern, the addition of a new product needs to modify the judgment statement in the factory role; while in the factory method pattern, either the judgment logic is left in the abstract factory role, or the specific factory role is hard-coded in the client program (just like the example above). And the change of the creation conditions of the product object will inevitably lead to the modification of the role of the factory.
       Faced with this situation, the clever combination of Java's reflection mechanism and configuration files breaks through the limitations - which is perfectly reflected in Spring.
Sixth, the abstract factory pattern

           Let's first understand what is a product family: A family of products located in different product hierarchy structures with related functions. Let us illustrate with an example.
Back to the topic of the abstract factory pattern.
It can be said that the difference between the abstract factory pattern and the factory method pattern is the complexity of the objects that need to be created. And the abstract factory pattern is the most abstract and general of the three.
The purpose of the abstract factory pattern is: to provide an interface for the client to create product objects in multiple product families,

and to use the abstract factory pattern, the following conditions must be met:
     1) There are multiple product families in the system, and the system can only be used at one time. Consume one of the family of products.
     2) Products belonging to the same product family are used for their use.
Let's take a look at the various roles of the abstract factory pattern (same as the factory method):
     1) Abstract factory role: This is the core of the factory method pattern, which has nothing to do with the application. It is an interface that a specific factory role must implement or a parent class that must be inherited. In java it is implemented by abstract classes or interfaces.

     2) Specific factory role: it contains code related to specific business logic. Called by the application to create the corresponding product-specific object. In java it is implemented by concrete classes.

     3) Abstract product role: it is the parent class inherited by the concrete product or the implemented interface. In java, there are generally abstract classes or interfaces to implement.

     4) Specific product role: The object created by the specific factory role is an instance of this role. It is implemented by concrete classes in java.
After reading the first two modes, I should have a good idea of ​​the coordination between the various characters in this mode, so I will not give specific examples. Just be sure to pay attention to meeting the conditions for using the abstract factory pattern.

<script type="text/javascript">&lt;!--google_ad_client = &quot;pub-4348265167276910&quot;;/* 468x60, 个人博客 */google_ad_slot = &quot;2046406163&quot;;google_ad_width = 468;google_ad_height = 60;//--&gt;</script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><script src="http://pagead2.googlesyndication.com/pagead/expansion_embed.js"></script><script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script><script>google_protectAndRun(&quot;ads_core.google_render_ad&quot;, google_handleError, google_render_ad);</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326391301&siteId=291194637