Applying design mode in Java - Factory Method

zhaozj2021-02-12  159

Source: http://www.cn.ibm.com/developerWorks

In the design mode, Factory Method is also a relatively simple, but the app is very wide, EJB, RMI, COM, CORBA, Swing can see the shadow of this mode, which is one of the most important modes. In many places we I will see the class named by XXXFactory, then, what is Factory Method, why use this mode, how to use Java language to implement this mode, this is what you want to bring to you.

Basic Concept Factory Method is a creative model that defines an interface to create an object, but allows the subclass to determine which class of specific instantiation. When a class cannot be expected to create which type of object or a class We need Factory Method mode when you need to specify the objects created. Simply, Factory Method can produce different instances according to different conditions. Of course, these different instances are usually the same type, which has common The parent class. Factory Method encapsulates the specific process of creating these instances, simplifies the client's application, and improves the program's scalability, so that you can do the minimum change in the future to add new to the class to be created. Usually we Use Factory Method as a standard to create objects, when you find more flexibility, you will start considering transformation to other creation mode

Simple analysis Figure 1 is a structural diagram of the Factory Method mode, which provides some terms that allow us to make more convenient description:

Product: The abstraction of the product you need to create. ConcreteProduct: Product's subclass, a series of specific products. Creator: Abstract creator interface, declaration returns Factory Method. Concretecreator: Concretecreator: Specific creator, rewrite Creator Factory Method, returns an instance of the ConcreteProduct type.

Figure 1: Factory Method mode structure

It can be clearly seen that such parallel correspondence: product <====> Creator; conreteproduct <====> Conretecreator

Abstract products correspond to abstract creators, specific products corresponding to specific creators. What is the benefit of this? Why don't we use specific products and specific creators to complete your needs? In fact, we can do this. But through Factory Method mode is completed, customer (Client) simply refers to abstract Product and Creater, which can do not care about specific ConcreteProduct and ConcreteCreator, so we can get additional benefits:

First of all, the client can unify the example from the abstract creator, the Creator's role is separated by the CLIENT and the product creation process, and the customer does not have to pay back the specific product, nor to care about how these products are created. ConcreteProduct is also hidden behind the Product, and ConreProduct inherits all properties of the Product and implements the abstract method defined in the product. Follow the principle of the object in Java, the ConcreteProduct generated by Concretecreator can automatically trace into Product In this way, the concreteproduct different from the substantive content can be unified in the form, and it is accessed by Creator to the client. Second, when we add a new ConcreteCreator, the client program is unchanged because the interface provided by Creator is unchanged. There will be no change in change, and the disaster that will not be moved. This is a good encapsulation. But if you use CONCRETEPRODUCT and CONCRETECREATOR two classes, you can't do this, excellent Object-oriented design encourages the encapsulation and delegation, and the Factory Method mode is a typical example of encapsulation and commission. The package is reflected by abstract creator Creator, and the delegation is through abstract creator. The responsibility of the creation object is fully handed over to the specific creator ConcreteCreator.

Now, please look back to see the password in the basic concept, starting to feel that it is difficult to understand, now it is a lot of unclear. Let's take a look at how to implement Factory Method mode in Java, further deepen it understanding.

The specific implementation is a bit, and the use of Factory Method mode is not necessarily let our code shorter. In fact, we have used more classes, the real purpose is to be flexible, flexible Create an uncertain object. Moreover, the reusability of the code is improved, and the client's application is simplified, and the code of the client is greatly reduced, more readable.

Standard Realization: Here I use Bruce Eckel to describe the classic example shape of OO thinking. This is more familiar. I have written the following paragraph one segmentation code in full according to the structure defined in Figure 1. This code is created Different Shape instances, each instance completions two operations: DRAW and ERASE. The specific creation process is commissioned to shareFactory. 1.A First define an abstract class shape to define two abstract methods.

Abstract Class Shape {// Hook Shape Public Abstract Void Draw (); // Wipe SHAPE PUBLIC Abstract Void Erase (); Public String Name; Public Shape (String Aname) {Name = Aname;}} 1.B Defining Shape Two subclasses: Circle, Square, realize abstract methods defined in Shape

// Circular Subclass Class Circle Extends Shape {Public Void Draw () {System.out.Println ("IT Will Draw A Circle.");} Public void Erase () {System.out.Println ("IT WILL ERASE A circle. ");} // Constructor PUBLIC CIRCLE (String Aname) {Super (Aname);}} // Square subclass class square extends shape {public void draw () {system.out.println (" IT Will Draw A Square. ");} public void erase () {system.out.println (" IT WILL ERASE A Square. ");} // Constructor PUBLIC SQUARE (String Aname) {Super (Aname);}} 1 .c define an abstract creator, Anoperation Create a single object to create an object and operate a series of operations.

abstract class ShapeFactory {protected abstract Shape factoryMethod (String aName); // define a series of acts Shape public void anOperation (String aName) {Shape s = factoryMethod (aName) in the anOperation; System.out.println ( "The current shape IS: " s.Name); s.draw (); S.RASE ();}} 1.D defines two specific creator CircleFactory, SquareFactory corresponding to Circle and Square, to implement the MethodFactory method for the parent class

// define return circle instance CircleFactory class CircleFactory extends ShapeFactory {// overloaded factoryMethod method returns Circle object protected Shape factoryMethod (String aName) {return new Circle (aName "(created by CircleFactory)");}} // Square define return instance SquareFactory class SquareFactory extends ShapeFactory {// overloaded factoryMethod method, the object returns Square protected Shape factoryMethod (String aName) {return new Square (aName "(created by SquareFactory)");}} 1.e test Category: Please note that this client program is concise, neither the conditional judgment statement, no need to care for the details of ConcreteProduct and Concretecreator (because I have encapsulated two methods in Product in Anoperation, so even Product's shadow is not See, of course, put the specific calls of Product methods in the customer program is also good) .class main {public static void main (string [] args) {shapefactory sf1 = new squarefactory (); shapefactory sf2 = new circlectory (); Sf1.anoperation ("Shape One"); sf2.anoperation ("Shape TWO");}} The result is as follows: The Current Shape IS: Shape One (Created By SquareFactory) It Will Draw A Square.it Will Erase A Square. THE CURRENT Shape IS: Shape Two (Created By Circlefactory) IT Will Draw A Circle.it Will Erase A CIR CLE. Parameterized Factory Method: This way relies on the specified parameters as a flag to create a corresponding instance. This is a very common way. For example, BorderFactory in JFC is a very good example. The following example is String as a tag, if the type of parameter is different, then you can use the overload function to solve this problem, define a series of parameters and method of the same name function, here java.util.calendar.GetInstance ( It is an excellent example. The parameterized creation method overcomes the most significant defect in Factory Method mode, which is when the specific product is more, we have to establish a series of specific constructors. But at the client We must specify parameters to determine which class to create. .

Class Nothisshape Extends Exception {public Nothisshape (String Aname) {super (aname);}} 2.b Removed two subclasses of ShapeFactory, changed by ShapeFactory directly to create an instance. Shapefactory turns into a specific creator, Directly use the parameterized method to implement FactoryMethod returns multiple objects.

abstract class ShapeFactory {private static Shape s; private ShapeFactory () {} static Shape factoryMethod (String aName, String aType) throws NoThisShape {if (aType.compareTo ( "square") == 0) return new Square (aName); else IF (atype.compareto ("circle") == 0) Return new circle (aname); Else Throw new nothingness (atype);} // A series of behaviors static void Aname (String Aname) (String Aname) in Anoperton "throws nothisshape {s = factorymethod (aname, atype); system.out.println (" the current shape is: " s.Name); s.draw (); s.led ();}} 2.c test Class: Here the client must specify the parameters to determine which class specifically created. This example is a static function, you can directly reference .class main {public static void main (String [] args) throws inisshape {ShapeFactory.anoperation ("Shape) One "," circle "); ShapeFactory.anoperation (" Shape TWO "," Square "); ShapeFactory.anoperation (" Shape Three "," Delta ");}} The results are as follows:

The current shape is: Shape one It will draw a circle It will erase a circle The current shape is:.. Shape two It will draw a square It will erase a square Exception in thread "main" NoThisShape:.. Delta at ShapeFactory. FactoryMethod (Shapefactory.java: 10) at ShapeFactory.Java:15) At main.main (main.java: 5) Dynamic loading mechanism: Sometimes we pass the concreteproduct instance to the creator as a parameter, In this case, if the creation process is completed in the creator, you must judge the specific type of parameters (with instanceof), and then you can generate the corresponding instance, then a better practice is to use Java's dynamic loading mechanism to complete this matter. For example, we get a subclass of Shape, but don't know if the subclass can use the method of the Class class, newInstance () obtained to obtain instance return () s.getClass (). NewInstance (); this The way is interested that the reader can try itself, limited to the space, and do not write the specific code.

After reading this article, I believe that the reader has a relatively clear understanding of the Factory Method mode. What I want to say is that we should not only care about a specific model, how to implement this mode, more Through the phenomenon, it is not only known, but also knows it, but it is necessary to deepen the understanding of object-oriented ideas through the learning of the model, let your understanding will sublimate. Factory method model seems simple, and it is deep. Abstraction, Package, inheritance, commission, polymorphism, conceptual concepts of objects, etc., is here to be referred to here. Only have the essence of it, we can not use the form of flexible use, not to use Mode and mode. Reference

Thinking in Pattern with Java ---- Bruce Eckel The Factory Method Design Pattern by Gopalan Suresh Raj ---- http://gsraj.tripod.com/design/creational/factory/factory.html SENG609_40 FACTORY PATTERNS PAPER --- - http://sern.ucalgary.ca/~kjfu/courses/seng60904/paper.html factory method pattern ---- http: // www.ugolandini.net/factoryMethodPattern.html Design Patterns in java ---- Bob Tarr Design Patterns ---- Gang of Four Dynamic Class Loading in java ---- http://www.pramodx.20m.com/dynamic_class_loading_in_java.htm

转载请注明原文地址:https://www.9cbs.com/read-6399.html

New Post(0)