Design Pattern-simple factory pattern

Source: Internet
Author: User

Design Pattern-simple factory pattern
Dr. Yan Hong's book "JAVA and patterns" describes the simple factory model as follows: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.

In what scenarios is the simple factory model used? The following is an example of my understanding:

Take the login function as an example. If the application system needs to support multiple login methods, such as password authentication and domain authentication (password authentication is usually used to verify the user in the database, domain authentication requires you to verify the user in the Microsoft domain ). The natural method is to create an interface applicable to various logon methods, as shown in:




Public interface Login {// logon verification public boolean verify (String name, String password);} copy the code public class DomainLogin implements Login {@ Override public boolean verify (String name, String password) {// TODO Auto-generated method stub/*** business logic */return true;} public class PasswordLogin implements Login {@ Override public boolean verify (String name, String password) {// TODO Auto-generated method stub/*** business logic */return true ;}}


We also need a factory-class LoginManager to create different login objects and return them according to the caller's requirements. If an invalid requirement is met, a Runtime exception is returned.

Public class LoginManager {public static Login factory (String type) {if (type. equals ("password") {return new PasswordLogin ();} else if (type. equals ("passcode") {return new DomainLogin ();} else {/*** it is more appropriate to throw a custom exception here */throw new RuntimeException ("No logon type found ");}}}


Test class:
Public class Test {public static void main (String [] args) {// TODO Auto-generated method stub String loginType = "password"; String name = "name "; string password = "password"; Login login = LoginManager. factory (loginType); boolean bool = login. verify (name, password); if (bool) {/*** business logic */} else {/*** business logic */}}}

The structure of the simple factory model is as follows:



We can imagine the real scenario. If we use the Test above as a servlet, when the client initiates a login request --> the Servlet sent to the server --> Servlet calls the factory () method of the factory LoginManager according to the loginType passed by the client --> factory () the method is to create a logon verification class (DomainLogin or PasswordLogin) based on the loginType parameter and return --> the method of calling the logon verification class verify () to verify that the user name and password are correct.



If you do not use the simple factory mode, verify that the logon Servlet code is as follows (assume that Test is a Servlet, and the variable loginType, name, and password indicate the parameters passed from the client ):

Public class Test {public static void main (String [] args) {// TODO Auto-generated method stub String loginType = "password"; String name = "name "; string password = "password"; // process password authentication if (loginType. equals ("password") {PasswordLogin passwordLogin = new PasswordLogin (); boolean bool = passwordLogin. verify (name, password); if (bool) {/*** business logic */} else {/*** business logic */} // process domain authentication else if (loginType. equals ("passcode") {DomainLogin domainLogin = new DomainLogin (); boolean bool = domainLogin. verify (name, password); if (bool) {/*** business logic */} else {/*** business logic */}}
Will the above Code be so cool... Haha

The JAVA. text. DataFormat class is used as a typical example of the simple factory mode in java and mode.

Advantages of the simple factory Model
The core of the model is the factory class. This class contains the necessary logical judgment to determine when to create an instance of the login authentication class, and the caller can be exempted from directly creating objects. The simple factory mode separates responsibility by using this method. When the system introduces a new Login method, the caller does not need to be modified.

Disadvantages of the simple factory Model

This factory class focuses on the Creation logic. When there is a complex multi-level hierarchy, all the business logic is implemented in this factory class. When it cannot work, the entire system will be affected.

For example, a hungry Chinese Singleton class returns an instance.

For example, in Android:

Principle: After the input parameter is found in the configuration file through reflection, an instance of the Name class is returned. [If you have configured the instance in the configuration file]

As follows:

Factory type:

 

Import com. example. lottery. engine. userEngine;/** factory class */public class BeanFactory {// Attribute class private static Properties properties; static {properties = new Properties (); try {properties. load (BeanFactory. class. getClassLoader (). getResourceAsStream ("bean. properties ");} catch (IOException e) {e. printStackTrace () ;}// use generics to load public static
 
  
T getImpl (Class
  
   
Clazz) {String key = clazz. getSimpleName (); String className = properties. getProperty (key); try {return (T) Class. forName (className ). newInstance ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} return null ;}}
  
 

 

 

Configuration File: UserEngine = com. example. lottery. engine. impl. UserEngineImpl

Usage:

 

UserEngine impl=BeanFactory.getImpl(UserEngine.class);

Summary: The factory class returns the instance of the class you need based on the instance you pass 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.