Simple Factory mode of Java design mode

Source: Internet
Author: User

Simple Factory mode of Java design mode

Recently in the study of Java design patterns, has always felt that design patterns are difficult, so has not been to contact, a job is more busy no time to learn, and secondly because they are lazy so also lazy move, thanks to the company is still quite busy, so found a book to learn the Java design model.

    1. Definition of a simple factory
    2. The idea of using a simple factory to solve problems
    3. Structure and description of a simple factory
    4. Simple Factory Code
    5. Using the Simple factory rewrite sample
    6. Mode explanation
    7. How to approach a simple factory
    8. Advantages and disadvantages of a simple factory
    9. Think Simple factory

1, the definition of simple factory

Provides a function to create an instance of an object without having to relate its specific implementation. The type of the instance being created can be an interface, an abstract class, or a specific class.

2, the use of simple factory to solve the problem of the idea

Simple factory can not let the module outside the module to know the implementation of the internal, but the inside of the module is also able to know the implementation of the class, and the creation of interfaces need to know the specific implementation class.
So, simply create a new class inside the module that creates the interface in this class, and then returns the created interface to the specific caller, so that the external application simply acquires the corresponding interface object based on that class, and then it can manipulate the method of the interface definition. This is called a simple factory, factory it.

3. Structure and description of simple factory

The results of the simple factory are as shown.

    • API: Defines the functional interfaces required by the customer.
    • Impl: Implement the API implementation class, can have more than one, according to the specific business.
    • Factory: Factory, select the appropriate implementation class to create the API interface object.
    • Client: Clients, Get API interface object through factory, and then program for API interface.

4. Simple Factory Code

(1) The API definition code is as follows:

publicinterface Api {    /**     * 示意,具体功能方法的定义     * @param s 示意,需要的参数     */    publicvoidoperation(String s);}

(2) After defining the interface, the implementation class IMPLA code is as follows:

publicclass ImplA implements Api {    @Override    publicvoidoperation(String s) {        System.out.println("ImplA s==" + s);    }}

The implementation class Implb.java code is as follows

publicclass ImplB implements Api {    @Override    publicvoidoperation(String s) {        System.out.println("ImplB s==" + s);    }}

(3) Implementation of simple factory. The code is as follows:

/** * Factory class for wearing the API object * @author veione */ Public  class Factory {    /** * Methods for creating API objects * @param condition, from external incoming selection criteria * @return Create a good API object * *     Public StaticApiCreateapi(intCondition) {//Create concrete implementation objects based on conditionsAPI API =NULL;if(Condition = =1) {API =NewImpla (); }Else if(Condition = =2) {API =NewIMPLB (); }returnApi }}

(4) Look at the client's schematic, the code is as follows:

/** * 客户端,使用Api接口 * @author veione */publicclass Client {    publicstaticvoidmain(String[] args) {        // 通过简单工厂来获取接口对象        Api api = Factory.createApi(1);        api.operation("使用简单工厂进行操作");    }}

5. Use simple Factory rewrite example

To rewrite the previous example with a simple factory, the main thing is to create a simple factory object that allows a simple factory to be responsible for creating the interface object. After the client obtains the interface object through the factory, the interface object is no longer created by the client itself.
The system structure looks like this:

(1) The Interface API and implementation class Impl, like the previous example, are not described here.

(2) Create a new object for a simple factory. The code is as follows:

/** * 工厂类,用来创建Api对象 */publicclass Factory{     /**      * 具体创建Api对象的方法      * @return 创建好的Api对象      */      publicstaticcreateApi(){          //由于只有一个实现就无需再条件判断了          returnnew Impl();      } }

(3) Use simple factory

This time the client will not have to create the interface object itself, should use the factory to obtain. After the transformation code is as follows:

/** * 客户端:测试使用Api接口 */publicclass Client{     publicstaticvoidmain(String[] args){        Api api=Factory.createApi();        api.test1("Hello,World!简单那工厂");     } }
Mode explanation

1, the function of simple factory

A factory is used to produce something. In Java, it is usually used to create an interface, but it can also create an abstract class, or even an instance of a concrete class.

2. Static Factory

When using a simple factory, it is usually not necessary to create a simple factory class instance without creating an instance. Therefore, the simple factory class can be implemented as a tool class directly using static methods. This means that a simple factory method is usually static, so it is also called a static factory. If you want to prevent clients from needlessly creating simple factory instances, you can also privatize the construction of simple factories.

3. Universal Factory

A simple factory can contain a lot of methods for constructing things, which can create different interfaces, abstract classes, or class instances. A simple factory can theoretically construct anything, so it's called a "universal factory."
Although the above example has only one method in a simple factory, in fact, there can be a lot of such creation methods, this should be noted.

4, simple factory to create the scope of the object

Although a simple factory can be created in theory, it is generally not too large for a simple factory to create objects, and it is recommended to control at a separate component level or at a module level, which is a simple factory of components or modules. Otherwise this simple factory class will be unclear, a bit of a hodgepodge of feeling.

5, the order of simple factory call

UML use case diagrams are not very useful, so refer here for a moment.

How to approach a simple factory

Although the simple factory approach is mostly used to create interfaces, but careful analysis you will find that the real implementation of the function is the implementation of the class, these implementation classes are already done, not really to rely on the simple factory to create, simple engineering method is no more than: the implementation of the choice of a suitable implementation class to use.
So the simple factory method The main function of the internal implementation is to select the appropriate implementation class to create the instance object. Since the choice is to be achieved, then the choice of criteria or the choice of parameters, the selection criteria or the source of the parameters are usually divided into the following categories:

    • Source and client: Incoming parameters by client
    • From the configuration file, get the value for judging from the configuration file
    • A value from the runtime of the program, such as getting a value from the cache for a run-time period.
Advantages and disadvantages of a simple factory

Simple factories have the following advantages.

    • Help encapsulation

      Simple factory is very simple, but it is very helpful for us to implement the encapsulation of the components, and then let the components outside can be really interface-oriented programming.

    • Decoupling

      The decoupling of the client and the specific implementation class is realized through a simple factory.

A simple factory has the following drawbacks.

    • May increase the complexity of the client

If you choose a specific implementation class through the parameters of the client, then you must let the client understand the specific functions and meanings that each parameter represents, which will increase the difficulty of client use, and partly expose the internal implementation, which can be implemented in a configurable way.


    • Inconvenient to extend sub-factory

Privatizing simple factory construction methods, using static methods to create interfaces, you cannot change the method behavior of creating interfaces by writing a subclass of a simple factory class. However, it is usually not necessary to create a subclass for a simple factory.

Think Simple factory

1, the essence of simple factory

The essence of a simple factory is: choose to implement

2. When to choose a simple factory

It is recommended to use a simple factory in the following cases.

    • If you want to complete the encapsulation isolation implementation, so that the external only through the interface to manipulate the package, then you can choose a simple factory, let the client through the factory to obtain the corresponding interface, without the need for a specific implementation of the relationship.
    • If you want to centrally manage and control the responsibility of creating objects externally, you can choose a simple factory, a simple factory can create a lot of unrelated objects, you can focus on the responsibility of creating objects to a simple factory, so as to achieve centralized management and control.

Simple Factory mode of Java design mode

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.