For well-trained thieves, there is a powerful thief training institution or company behind them to operate the daily work of the thieves. Just like a herd, Feng Yu's "thief Company" has many departments.
Of course, in the previous simple factory, the specific action of stealing something (operation) was sent to the subclass, but at the top of the thieves company, it was not a solution, all logics are defined in
In the factory method, if I want to add a car stealing action, I need to modify the current factory method. Of course, this is against the "development-closure principle. It is open to extensions and closed to modifications.
Then I will assign a new middle-level administrator to take charge of the special theft function. For example, if I want to steal a bicycle, I will assign a specialist to train the administrator of the bicycle. Responsible for producing special theft technologies. This is what the industry specializes in.
That's good. It creates a special factory for every theft technology. This is the factory method model. Let's look at the class chart directly:
TheCodeHere, we will not post the implementation code of the client:
Package designpattern. factorymethodpattern. stealcompany;
Public ClassStealcompanytest {
/**
*
*
*
* @ Param ARGs
*/
Public Static VoidMain (string [] ARGs ){
// Todo auto-generated method stub
Istealcompanyfactory stealoperfactory =NewStealwalletfactory ();
Stealoperation = stealoperfactory. createstealoperation ();
Stealfetch. Steal ();
}
}
Here, an object is generated through a specific stolen factory, and the variable of an istealcompanyfactory interface points to this object. Then, the istealcompanyfactory method is implemented by calling this object,
Createstealoperation to generate a specific stealoperation object. Then the steal method in stealoperation is rewritten.
Output result:
I stole my wallet! Oh, baby!
Summary:
The factory method mode will not be able to avoid the option, because if I want to steal the wallet, I Will instantiate the factory that steals the wallet, and then let the factory that steals the bag to produce the operation that steals the wallet. But it moves the internal logic in a simple factory to the client code.
. If I want to steal a mobile phone, I only need to add the content of the mobile phone to the client. If I want to add a car stealing operation, I only need to create a factory class that implements the istealcompanyfactory interface,
Create a new class that overwrites the steal method in stealoperation to steal a car. In this way, no changes will be made to any existing code. Of course, the "open-close principle" is well followed for modification and opening to expansion.
The factory method model is just the mother of this principle! Raised in one hand!
Finally, the typical UML class diagram of the factory method is given:
Attachment: complete Java code written using eclipse