Java factory design pattern (from network)

Source: Internet
Author: User

I.ProgramDesign Objectives

We set up a simple fruit production program to describe the process of fruit planting on the farm. This design aims to further understand the engineering design model and enhance the structural ability of programming.

Development Environment: jdk1.5

Development Tool: JBuilder 2006

II. Introduction to Program Design

1. Program Structure

We set up a simple production program for a Fruit Company, which sells various fruits to the market. We have created a project named farm for the program. The program structure is relatively simple. There are 7 classes in total and they are all placed in a default package. Its hierarchical structure can be embodied in:

Description of each class:

Fruit class: fruit interface, fruit method implementation

Apple: Apple, implementing the fruit Interface

Grape: Grape class, implementing the fruit Interface

Strawberry class: Strawberry class, implementing the fruit Interface

Fruitgardener: gardener type, which can be planted with various fruits

Badfruitexception: the fruit to be planted is not within the scope of the fruit operated by the company.

Plantfruit class: implements the main () method.

2. Procedure

In this system, you need to describe the following fruits:

Grape

Strawberry strawberry

Apple

The fruit is very different from other plants, that is, the fruit can finally be picked and eaten. So a natural

The practice is to establish an interface applicable to various fruits so that they can be separated from other plants on the farm. As shown in.

The fruit interface specifies the interfaces that all fruits must implement, including methods required for any fruit class: planting plant (), growing grow (), and harvesting harvest (). The class diagram of the interface fruit is as follows.

This fruit InterfaceSource codeAs shown below.

CodeListing 1: source code of the interface fruit

Public interface fruit {

// Growth

Void grow ();

// Gains

Void harvest ();

// Planting

Void plant ();

} The following figure shows the source code of the apple class.

Apple is a kind of fruit, so it implements all the methods declared by the fruit interface. In addition, because Apple is a perennial plant, a treeage exists to describe the age of the apple tree. The following is the source code of the apple class.

Code List 2: source code similar to Apple

Public class Apple

Implements fruit {

Private int treeage;

// Growth

Public void grow (){

Log ("Apple is growing ...");

}

// Gains

Public void harvest (){

Log ("Apple has been harvested .");

}

// Planting

Public void plant (){

Log ("Apple has been planted .");

}

// Auxiliary Method

Public static void log (string MSG ){

System. Out. println (MSG );

}

// Method for Determining the Tree Age

Public int gettreeage (){

Return treeage;

}

// Tree Age Assignment Method

Public void settreeage (INT treeage ){

This. treeage = treeage;

}

}

Similarly, the grape class is a fruit class and implements all the methods declared by the fruit interface. However, because grapes are divided into two types: seedless and seedless, there is more seedless than the common fruit, as shown in.

The source code of grape is as follows. It can be seen that grape class also implements the fruit interface, but is a seed type of the fruit type.

Code List 3: source code of grape class

Public class grape

Implements fruit {

Private Boolean seedless;

// Growth

Public void grow (){

Log ("grape is growing ...");

}

// Gains

Public void harvest (){

Log ("grape has been harvested .");

}

// Planting

Public void plant (){

Log ("grape has been planted .");

}

// Auxiliary Method

Public static void log (string MSG ){

System. Out. println (MSG );

}

// Method for determining the value with no seeds

Public Boolean getseedless (){

Return seedless;

}

// Method for assigning values with no seeds

Public void setseedless (Boolean seedless ){

This. Seedless = seedless;

}

}

The following is a diagram of the strawberry class.

The strawberry class implements the fruit interface. Therefore, it is also a child type of the fruit type. Its source code is as follows.

Code list 4: source code of the strawberry class

Public class strawberry

Implements fruit {

// Growth

Public void grow (){

Log ("Strawberry is growing ...");

}

// Gains

Public void harvest (){

Log ("Strawberry has been harvested .");

}

// Planting

Public void plant (){

Log ("Strawberry has been planted .");

}

// Auxiliary Method

Public static void log (string MSG ){

System. Out. println (MSG );

}

}

Farm gardeners are also part of the system, naturally represented by a suitable class. This class is the fruitgardener class, and its structure is described by the class diagram below.

The fruitgardener class creates different fruit objects, such as Apple, grape, or strawberry instances, based on client requirements. If an invalid requirement is received, the fruitgardener class throws a badfruitexception, as shown in.

The source code of the gardener class is as follows.

Code List 5: source code of the fruitgardener class

Public class fruitgardener {

// Static factory Method

Public static Fruit 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 ");

}

}

}

As you can see, the gardener class provides a static factory method. Call the client to create the fruit object required by the client. If the client request is not supported by the system, the factory method throws a badfruitexception. The source code of this exception class is as follows.

Code List 6: source code of the badfruitexception class

Public class badfruitexception

Extends exception {

Public badfruitexception (string MSG ){

Super (MSG );

}

}

During use, the client only needs to call the static method Factory () of fruitgardener. See the source code of the schematic client below.

Code List 7: implement planting as main ()

Public class plantfruit {

Public plantfruit (){

}

Public static void main (string [] ARGs ){

Plantfruit = new plantfruit ();

Try {

// Grape planting

Fruitgardener. Factory ("grape"). Plant ();

Fruitgardener. Factory ("grape"). Grow ();

Fruitgardener. Factory ("grape"). Harvest ();

System. out. println ("================================== ");

// Planted apple

Fruitgardener. Factory ("apple"). Plant ();

Fruitgardener. Factory ("apple"). Grow ();

Fruitgardener. Factory ("apple"). Harvest ();

System. out. println ("================================== ");

// Plant strawberries

Fruitgardener. Factory ("strawberry"). Plant ();

Fruitgardener. Factory ("strawberry"). Grow ();

Fruitgardener. Factory ("strawberry"). Harvest ();

System. out. println ("================================== ");

}

Catch (badfruitexception e ){

}

}

}

So far, our simple program has been designed. We can create a fruitgardener object to plant the fruit. No matter what you want, we only need to call the factory () method in the object. The output result is as follows:

3. Simple factory model definition

The simple factory mode is the class creation mode, also called the static factory method mode. The simple factory mode is determined by a factory object to create a product instance.

Iv. Structure of the simple factory Model

The simple factory mode is the class creation mode. shows the general structure of this mode.

Roles and structures

In simple factory mode, a factory class can decide which product class instance to create based on input parameters. The following example illustrates the structure of a simple factory model with a schematic implementation.

The simple factory model involves factory roles, abstract product roles, and specific product roles.

Three roles:

(1) The Creator role is the core of the factory method model, which is closely related to applications.

Secret-related business logic. The factory class creates a product object directly called by the client.

Java class implementation.

(2) Abstract Product role: the class that assumes this role is the parent of the object created in the factory method mode.

Class, or the interfaces they share. Abstract product roles can use a Java interface or Java Abstract class

.

(3) The role of a specific product: Any object created in the factory method mode is in this corner.

Color instance. The specific product role is implemented by a specific Java class.

The schematic source code of the factory class is as follows. We can see that this factory method creates a new product instance and returns it to the caller.

Code List 8: source code of the Creator class

Public class creator

{

// Static factory Method

Public static product factory ()

{

Return new concreteproduct ();

}

}

Abstract product roles are designed to provide a common type for all specific product classes. In the simplest case, they can be simplified to an interface for identification. The identification interface is an empty interface that does not declare any methods.

Code List 9: source code of the abstract role product Interface

Public interface Product

{

}

The schematic source code of the specific product category is as follows.

Code List 10: source code of the concreteproduct class of a specific product role

Public class concreteproduct implements Product

{

Public concreteproduct (){}

}

Although only one specific product class is provided in this simple schematic implementation, multiple product classes are usually encountered in actual applications.

V. Implementation of the simple factory Model

1. Multi-Level Product Structure

In a real system, a product can form a complex hierarchical structure. For example, the tree structure shown in shows multiple abstract product classes and specific product classes.

At this time, the simple factory model adopts a policy that does not change, and uses the same factory class. As shown in.

In the figure, the dotted line from the factory class to each product class represents the creation (dependency) relationship; the line from the client to other classes is a general dependency. The advantage of this is that the design is simple, and the hierarchical structure of the product class is not reflected in the factory class, so that the change of the hierarchical structure of the product class will not affect the factory class. However, the disadvantage is that adding new products will inevitably lead to changes to the factory class.

2. Use the Java interface or Java Abstract class

If the specific product classes produced by the model do not share the same business logic with each other, the abstract Product role can be assumed by a Java interface. On the contrary, if the specific product classes do have the same business logic with each other, the public logic should be moved to the abstract role, which means that the abstract role should be assumed by an abstract class. In a hierarchical structure, common code should be moved up as much as possible to achieve the purpose of sharing, as shown in.

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.