Simple Factory method

Source: Internet
Author: User

Simple Factory mode explanation:

simple Factory mode (simple Factory pattern "is the creation pattern of the class, also called Span style= "font-family: Song body; Background:white None repeat scroll 0% 0%; " > static factory method mode (static factorymethod pattern) , is responsible for creating instances of other classes by defining a class specifically. The instances that are created typically have a common parent class.

UML diagram for simple Factory mode:

the roles contained in the Simple factory model and their corresponding responsibilities are as follows:

Factory Role (Creator): This is the core of the simple factory pattern, which is responsible for creating the internal logic of all classes. Of course the factory class must be able to be called outside to create the desired product object.

       abstract ( Product ) Product Roles : The parent class of all objects created by simple Factory mode, note that the parent class here can be an interface or an abstract class, which is responsible for describing common interfaces common to all instances.

specific products ( concrete Product ) Role: A concrete instance object created by a simple factory that often has a common parent class .

In-depth analysis of the Simple factory model :

The Simple factory model solves the problem of how to instantiate an appropriate object. The core idea of the simple factory model is that there is a specialized class that is responsible for creating the instance process. look at the product is a collection of classes, These classes are an object tree derived from an abstract class or interface. If there is no common logic between the specific products involved in the simple factory model, then we can use interfaces to play the role of abstract products, and if there is functional logic between specific products, we must extract these common things, put them in an abstract class, and then let the specific product inherit the abstract class.

in practical use, abstract products and specific products are often multi-layered product structure, as shown in:

 //@ class Description: Establish an interface for all kinds of login methods Public InterfaceLogin { Public BooleanVerify (string name, string password); }   //@ class Description: Domain authentication  Public classDomainloginImplementsLogin {@Override Public BooleanVerify (string name, string password) {//TODO auto-generated Method Stub        /*** Business logic*/          return true; }    }   //@ class Description: Password Authentication Public classPasswordloginImplementsLogin {@Override Public BooleanVerify (string name, string password) {//TODO auto-generated Method Stub        /*** Business logic*/          return true; }    }  
View Code

We also need a factory class Loginmanager that creates different login objects and returns based on the caller's different requirements. If an illegal request is encountered, a runtime exception is returned.

//@ Class Description: Factory class Public classLoginmanager { PublicLogin Factory (String type) {if(Type.equals ("Password") {System.out.println ("What you get from the factory: Password Authentication"); return NewPasswordlogin (); } Else if(Type.equals ("passcode") {System.out.println ("What you get from the factory: Domain Certification"); return NewDomainlogin (); } Else {                         Throw NewRuntimeException ("Login type not Found"); }      }  }  
View Code
 //@ Class Description: Test factory class Public classtestfactory {@Test Public voidtestfactory () {//TODO auto-generated Method StubString logintype = "Password"; String name= "Name"; String Password= "Password"; Login Login=NewLoginmanager (). factory (Logintype); BooleanBOOL =login.verify (name, password); if(bool) {/*** Business logic*/          } Else {              /*** Business logic*/          }      }  }  
View Code

Advantages and disadvantages of the simple factory model:

Pros: factory class is the key to the entire pattern. It contains the necessary judgment logic to determine which specific class of objects should be created based on the information given by the outside world.

Cons: because the factory class centralizes the creation logic of all instances, this leads directly to all clients being implicated once the factory has a problem; and because the product of the simple factory model is based on a common abstract class or interface, this way, when the type of product is increased, When there are different product interfaces or abstract classes, the factory class needs to decide when to create the kind of product, which is confused with the products that create the kind of product, violating a single duty, resulting in loss of flexibility and maintainability of the system. And more importantly, the simple factory model violates the "open closure principle", ,

To summarize: The simple factory model separates the product creator and the consumer, is advantageous to the software system structure optimization; But since all logic is concentrated in a factory class, it leads to no high cohesion, and also violates the "open closure principle". In addition, simple Factory mode methods are generally static, while static factory methods cannot inherit from subclasses, so simple Factory mode cannot form an inheritance tree structure based on a base class.

Introduction to the practical application of the simple factory model:

As one of the most basic and simplest design patterns, the simple factory model has a very wide range of applications, as illustrated in the example of the JDBC operations database in Java.

JdbcIsSUNA set of database programming interfaces provided by the companyApi, it usesJavaLanguages provide a simple, consistent way to access a variety of relational databases.JavaProgram throughjdbc is a mechanism by which Java applications can interact with various relational data by executing SQL statements, processing the acquired data, and depositing the changed data back into the database. when using JDBC for database access, use the driver interface provided by the database vendor to interact with the database management system.

When the client wants to use the data, it only needs to interact with the factory, which causes the operation steps to be greatly simplified, in order to register and load the database driver, the general useClass.forName ();Create a link to a databaseConnectionobject; createSQL Statement Object preparedstatement (SQL), commit SQL statement, use ExecuteQuery () as per the actual situation, or Executeupdate (); display the corresponding results; close the database.

Simple Factory method

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: 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.