Java design mode (2): Factory Method)

Source: Internet
Author: User

In practical applications, it is very likely that the product is a multi-level tree structure.

Since there is only one factory class in the simple factory model to correspond to these products, this may make our God exhausted, and We programmers tired, so the factory method model emerged as the savior.

The factory method mode removes the static attribute of the factory method in the simple factory mode so that it can be inherited by the quilt class. In this way, the pressure on the factory method in the simple factory mode can be shared by different factory subclass in the factory method mode.


You should roughly guess the structure of the factory method mode, and look at its composition:

Abstract Factory role: this is the core of the factory method model and has nothing to do with the application. It is an interface that must be implemented by a specific factory role or a parent class that must be inherited. In java, it is implemented by abstract classes or interfaces. Specific factory role: it contains code related to specific business logic. An application is called to create the objects of a specific product. Abstract Product role: it is the parent class or implemented interface inherited by a specific product. In java, abstract classes or interfaces are generally used for implementation. Specific product role: the object created by the specific factory role is the instance of this role. It is implemented by specific classes in java.

Use a class chart to clearly represent the relationship between them:
Kernel + bL + kernel/kernel + csf-vcd4kpha + kernel/kernel + rPJo6zEx8O0vs2/ydLUsbu/kernel/J0tS/kernel/u6z7 + kernel + PGJyPgo8L3A + kernel/kernel + expires + expires/L2bTy06G7 + expires/expires + sbVzai08tOhu/expires + PGJyPgo8L3A + expires/Co7o8L3A + CjxwPrPpz/Oy + expires/expires + expires "brush: java; "> public abstract class Printer {public abstract void out (); public abstract void getData (String msg );}


Specific product role (we define two products, one is a common printer and the other is a high-speed printer)

/** High-speed Printer */public class BetterPrinter extends Printer {private final int MAX_CACHE_LINE = 10; private String [] printData = new String [MAX_CACHE_LINE * 2]; private int dataNum = 0; @ Overridepublic void getData (String msg) {if (dataNum> = MAX_CACHE_LINE * 2) {System. out. println ("the output queue is full, adding failed");} else {printData [dataNum ++] = msg ;}@ Overridepublic void out () {while (dataNum> 0) {System. out. println ("high-speed printer printing:" + printData [0]); System. arraycopy (printData, 1, printData, 0, -- dataNum) ;}}/ ** common Printer */public class CommonPrinter extends Printer {private final int MAX_CACHE_LINE = 10; private String [] printData = new String [MAX_CACHE_LINE]; private int dataNum = 0; @ Overridepublic void getData (String msg) {if (dataNum> = MAX_CACHE_LINE) {System. out. println ("the output queue is full, adding failed");} else {printData [dataNum ++] = msg ;}@ Overridepublic void out () {while (dataNum> 0) {System. out. println ("printer print:" + printData [0]); System. arraycopy (printData, 1, printData, 0, -- dataNum );}}}

Abstract Factory role

public interface PrinterFactory{public Printer getPrinter();}

Specific factory role (we define two factories, one is a normal printer factory and the other is a high-speed printer factory)

/** High-speed Printer factory, only the high-speed Printer product */public class BetterPrinterFactory implements PrinterFactory {public Printer getPrinter () {return new BetterPrinter ();}} /** normal Printer factory, only common Printer products */public class CommonPrinterFactory implements PrinterFactory {public Printer getPrinter () {return new CommonPrinter ();}}



Finally, we tested it. we defined a computer that calls the factory to produce the printer we need. What type of printer is needed, and a corresponding factory is created, it is used to produce the printers we need.

public class Computer{private Printer out;public Computer(Printer out){this.out = out;}public void keyIn(String msg){out.getData(msg);}public void print(){out.out();}public static void main(String[] args){PrinterFactory of = new CommonPrinterFactory();Computer c = new Computer(of.getPrinter());c.keyIn("hello");c.keyIn("world");c.print();}}

Print result:

Printer print: hello
Print with a normal printer: world

We can see that the addition of factory methods doubles the number of objects. When there are many product categories, there will be a large number of corresponding factory objects, which is not what we want. If this problem cannot be avoided, consider combining the simple factory mode with the factory method mode to reduce the factory class: that is to say, a simple factory model is used for similar types on the product tree (generally the leaves of the tree are sibling ones.

The factory method mode seems to have perfectly packaged the object creation, so that the client program only processes the interfaces provided by the abstract Product role. So do we have to spread code across factories? Not required. You may consider using the factory method mode in the following situations:

When the customer program does not need to know the creation process of the object to be used. The objects used by the customer program may change, or they do not know which specific object to use. Does the simple factory mode and factory method mode actually avoid code changes? No. In the simple factory mode, the new product is added to modify the judgment statement in the factory role. In the factory method mode, the judgment logic is either left in the abstract factory role, either write down the specific factory role in the customer Program (as in the above example ). In addition, changes to product object creation conditions will inevitably lead to changes to the factory role.

In the face of this situation, the clever combination of the reflection mechanism of Java and the configuration file breaks through the limitations-this is perfectly reflected in Spring.

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.