Introduction to simple factory Creation Mode of Java language

Source: Internet
Author: User
The necessity of UW research and use of the founding Model

One of the purposes of the object-oriented design is to divide responsibilities and assign them to different objects. We recommend this division of responsibility because it is in line with the spirit of encapsulation and delivery. The creation model encapsulates the object creation process, which separates the instance creation responsibility from the instance usage responsibility and is created by a dedicated module in charge of the instance, at the macro level, the system no longer depends on the details of the object creation process.

All object-oriented languages have fixed object creation methods. The Java method is to use the new operator. For example

Stringbuffer S = new stringbuffer (1000 );

Creates an object, whose type is stringbuffer. Before using the new operator, you must know exactly what the class to be instantiated is, and the responsibility for instantiation is often different from the responsibility for using instances. Classes are instantiated using the creation mode. First, you do not need to know which class to instantiate each time. Second, you need to separate the instantiation responsibility from the instance's responsibility, it can make up for the short points that directly use the new operator.

The factory mode is specifically responsible for instantiating a large number of classes with common interfaces, and you do not have to know which class to instantiate each time.

  The factory model has several forms

The factory model has the following forms:

Simple factory Mode

Factory method mode, also known as the polymorphic factory Mode

Abstract Factory mode, also known as Toolkit (kit or Toolkit) Mode
 Introduction to simple factory Mode

For example, you have a system that describes your back garden. There are various flowers in your back garden, but there is no fruit. You need to introduce some new classes to your system to describe the following fruits:

Grapes

Strawberry strawberry

Pingguo Apple

The biggest difference between flowers and fruits is that fruits can finally be picked and eaten. Then, it is natural to create an interface applicable to various fruits, so that these fruits can be used as similar data types as the rest of your system, for example, different flowers are easy to differentiate.


Figure 1. Grape, strawberry, and Apple are classes with common interfaces of fruitif.

Package com. javapatterns. simplefactory;

Public interface fruitif {
Void grow ();

Void harvest ();

Void plant ();

String color = NULL;
String name = NULL;
}

Code List 1. source code of the interface fruitif. This interface determines the essential methods for fruit: planting plant (), growing grow (), and harvesting harvest ().

Package com. javapatterns. simplefactory;

Public class Apple implements fruitif
{

Public void grow ()
{
Log ("Apple is growing ...");
}

Public void harvest ()
{
Log ("Apple has been harvested .");
}

Public void plant ()
{
Log ("Apple has been planted .");
}

Public static void log (string MSG)
{
System. Out. println (MSG );
}

Public int gettreeage () {return treeage ;}

Public void settreeage (INT treeage) {This. treeage = treeage ;}

Private int treeage;
}

Code List 2. Source Code similar to Apple. Pingguo is a perennial woody plant and therefore belongs to treeage.

Package com. javapatterns. simplefactory;

Public class grape implements fruitif
{
Public void grow ()
{
Log ("grape is growing ...");
}

Public void harvest ()
{
Log ("grape has been harvested .");
}

Public void plant ()
{
Log ("grape has been planted .");
}

Public static void log (string MSG)
{
System. Out. println (MSG );
}

Public Boolean getseedful ()
{
Return seedful;
}

Public void setseedful (Boolean seedful)
{
This. seedful = seedful;
}

Private Boolean seedful;
}

Code List 3. Source Code of grape class. There are two types of GRAPES: seedful and seedful.

Package com. javapatterns. simplefactory;

Public class strawberry implements fruitif
{
Public void grow ()
{
Log ("Strawberry is growing ...");
}

Public void harvest ()
{
Log ("Strawberry has been harvested .");
}

Public void plant ()
{
Log ("Strawberry has been planted .");
}

Public static void log (string MSG)
{
System. Out. println (MSG );
}
}

Code list 4. source code of the strawberry class.

As the master and gardener of the flower orchard, you are also part of the system. Naturally, you must be represented by a suitable class, which is the fruitgardener class. For the structure of this class, see the UML class diagram below.


Figure 2. fruitgardener class diagram.

The fruitgardener class will create different fruit types as required, such as Pingguo apple, grape, or strawberry instances. If an invalid requirement is received, the fruitgardener class will provide the exception badfruitexception.


Figure 3. badfruitexception class diagram.
Package com. javapatterns. simplefactory;

Public class fruitgardener
{
Public fruitif Factory (string which) throws badfruitexception
{
If (which. equalsignorecase ("apple "))
{
Return new Apple ();
}
Else if (which. equalsignorecase ("strawberry "))
{
Return new strawberry ();
}
Else if (which. equalsignorecase ("grape "))
{
Return new grape ();
}
Else
{
Throw new badfruitexception ("bad fruit request ");
}
}
}

Code List 5. source code of the fruitgardener class.

Package com. javapatterns. simplefactory;

Public class badfruitexception extends exception
{
Public badfruitexception (string MSG)
{
Super (MSG );
}
}

Code List 6. source code of the badfruitexception class.

In use, you only need to call the factory () method of fruitgardener.

Try
{
Fruitgardener gardener = new fruitgardener ();

Gardener. Factory ("grape ");
Gardener. Factory ("apple ");
Gardener. Factory ("strawberry ");
...
}
Catch (badfruitexception E)
{
...
}

In this way, your small orchard will surely have a bumper harvest!
Simple factory mode definition

All in all, the simple factory mode is to create a product instance based on the parameters of a factory class. The following UML class diagram precisely defines the structure of the simple factory mode.


Figure 4. Class Diagram defined in the simple factory mode.

Public class creator
{
Public Product Factory ()
{
Return new concreteproduct ();
}

}

Public interface Product
{
}

Public class concreteproduct implements Product
{
Public concreteproduct (){}

}

Code List 7. source code of the simple factory framework.

The simple factory model is actually a simplified situation that we will introduce later. After the reader is familiar with the simple factory model introduced in this section, it is not difficult to master the factory method model.
Q &

At the beginning of this section, it is not said that the factory mode is to change ...... is the class instantiated? Why is the new operator still used in the specific implementation?

There are three fruit classes in the small orchard system in this section. Why is there only one product class in Figure 3 (simple factory model defined class diagram?

Use a simple factory model to design an art tracer system that creates different geometric shapes, such as circles, squares, and triangles. You must draw () and erase () in each ry. When the surveyors receive commands to create unsupported geometric images, the exception of badshapeexception must be raised.

A simple example is provided to describe how the system is used.

In the simple factory mode definition (see figure 4) and the flower orchard example, the factory () method belongs to the instance rather than the static or class method. Can the factory () method be a static method?

  Q & A answers

For the entire system, the factory model encapsulates and hides the details of the specific use of the new operator. Of course, as long as the program is written in the Java language, the characteristics of the Java language will certainly appear in the details.

Figure 3. (class chart defined by the simple factory mode) is a refined framework class chart, which is used to give an accurate and refined definition of this model. If there are several product categories, You need to analyze each system.

Here is the complete answer to the question. The UML of the art tracer system is as follows:


The source code of the system is as follows:

Package com.javapatterns.simplefactory.exe rcise;

Public class arttracer
{
Public shape Factory (string which) throws badshapeexception
{
If (which. equalsignorecase ("circle "))
{
Return new circle ();
}
Else if (which. equalsignorecase ("square "))
{
Return New Square ();
}
Else if (which. equalsignorecase ("Triangle "))
{
Return New Triangle ();
}
Else
{
Throw new badshapeexception (which );
}
}
}

Code List 8. source code of the arttracer class.

Package com.javapatterns.simplefactory.exe rcise;

Public Interface Shape
{
Void draw ();

Void erase ();
}

Code List 9. source code of the Shape interface.

Package com.javapatterns.simplefactory.exe rcise;

Public class square implements shape
{
Public void draw ()
{
System. Out. println ("square. Draw ()");
}

Public void erase ()
{
System. Out. println ("square. Erase ()");
}
}

Code List 10. source code of the square class.

Package com.javapatterns.simplefactory.exe rcise;

Public class circle implements shape
{
Public void draw ()
{
System. Out. println ("circle. Draw ()");
}

Public void erase ()
{
System. Out. println ("circle. Erase ()");
}
}

Code List 11. source code of the circle class.

Package com.javapatterns.simplefactory.exe rcise;

Public class triangle implements shape
{
Public void draw ()
{
System. Out. println ("Triangle. Draw ()");
}

Public void erase ()
{
System. Out. println ("Triangle. Erase ()");
}
}

Code List 12. source code of the triangle class.

Package com.javapatterns.simplefactory.exe rcise;

Public class badshapeexception extends exception
{
Public badshapeexception (string MSG)
{
Super (MSG );
}
}

Code listing 13. source code of the badshapeexception class.

The method used by the art tracer system is as follows:

Try
{
Arttracer art = new arttracer ();

Art. Factory ("circle ");
Art. Factory ("square ");
Art. Factory ("Triangle ");

Art. Factory ("diamond ");
}
Catch (badshapeexception E)
{
...
}

Note that when a diamond request is made to the arttracer class, the badshapeexception exception is returned.

Obviously, factory () can be a static method or a class method. This article introduces the simple factory model to make it easier to compare with the factory method model described later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.