JAVA Design Pattern--Factory Pattern

JAVA Design Pattern--Factory Pattern

The factory pattern is divided into simple factory, factory method pattern and abstract factory pattern. Simple factories, as the name suggests, are the simplest. Obtaining the required products from a factory is similar to factory.getProduct1(); or factory.getProduct2(), the most classic use of switch statements. If a simple factory wants to add products, it needs to modify the source code and destroy the ocp principle (open for extension, closed for modification)

The difference between the factory method pattern and the simple factory is that the factory method pattern has a factory interface

The biggest difference between the abstract factory pattern and the factory method pattern is that the products of the factory method pattern are derived from the same interface or abstract class, while the products of the abstract factory pattern are derived from different interfaces or abstract classes. Because the factory method pattern is aimed at a product hierarchy, and the abstract factory method is aimed at multiple ones, corresponding to one interface (abstract class) and multiple interfaces (abstract class). What product hierarchy? For example, for example, cars are divided into Audi and BMW, and Audi and BMW are divided into large-displacement and small-displacement, then large-displacement Audi and small-displacement Audi belong to the same product hierarchy, while large-displacement Audi Audi and large-displacement BMW belong to the same product family. If it is for a product hierarchy, that is, Audi or BMW, then the factory product is a product hierarchy, and the factory method pattern is used. If it is for multiple products, such as BMW and Audi, the abstract factory pattern is used, and its product is a product. clan. This is their application scenario.

Here is an example to familiarize yourself with the abstract factory pattern. (Use the singleton mode to avoid a large number of factory creations and waste resources. I don't understand the previous article about singletons)

 

public interface IFactoryDao {  
    public IUserDao createUserDao();  
    public IAddressDao createAddressDao();  
} // Factory interface

 

public interface IAddressDao {  
    public  void add(Address address,int userId);  
    public void update(Address address);  
    public void delete(int id);  
      
} // Product 1 interface  

 
public interface IUserDao {  
    public void add(User user);  
    public void delete(int id);  
    public void update(User user);  
      
} // Product 2 interface  
 


 
public class UserJDBCDao implements IUserDao {  
  
    @Override  
    public void add(User user) {  
        System.out.println("UserJDBCDao....add");  
  
    }  
  
    @Override  
    public void delete(int id) {  
        System.out.println("UserJDBCDao....delete");  
  
    }  
  
    @Override  
    public void update(User user) {  
        System.out.println("UserJDBCDao....update");  
  
    }  
  
  
  
} // Product 2 implementation for JDBC  


 
public class AddressJDBCDao implements IAddressDao {  
  
    @Override  
    public void add(Address address, int userId) {  
        System.out.println("addressJDBCDao....add");  
    }  
  
    @Override  
    public void update(Address address) {  
        System.out.println("addressJDBCDao....update");  
  
    }  
  
    @Override  
    public void delete(int id) {  
        System.out.println("addressJDBCDao....delete");  
  
    }  
  
      
  
} // Product 1 implementation for JDBC  


 
public class JDBCDaoFactory implements IFactoryDao {  
    private static JDBCDaoFactory factory = new JDBCDaoFactory();  
      
    private JDBCDaoFactory(){}  
      
    public static IFactoryDao getInstance() {  
        return factory;  
    }  
  
    @Override  
    public IUserDao createUserDao() {  
        return new UserJDBCDao();  
    }  
  
    @Override  
    public IAddressDao createAddressDao() {  
        return new AddressJDBCDao();  
    }  
  
} // Factory interface implementation 1 (JDBC)  



 
public class UserMySqlDao implements IUserDao {  
  
    @Override  
    public void add(User user) {  
        System.out.println("UserMySqlDao....add");  
  
    }  
  
    @Override  
    public void delete(int id) {  
        System.out.println("UserMySQlDao....delete");  
  
    }  
  
    @Override  
    public void update(User user) {  
        System.out.println("UserMySqlDao....update");  
  
    }  
  
      
  
} // Product 2 implementation for MySql  



 
public class AddressMySqlDao implements IAddressDao {  
  
    @Override  
    public void add(Address address, int userId) {  
        System.out.println("addressMySqlDao....add");  
    }  
  
    @Override  
    public void update(Address address) {  
        System.out.println("addressMySqlDao...update");  
  
    }  
  
    @Override  
    public void delete(int id) {  
        System.out.println("addressMySqlDao....delete");  
  
    }  
  
      
  
} // Product 1 implementation for MySql  
 
    
//Factory implementation 2 (MySql)   
public class MysqlDaoFactory implements IFactoryDao {
private static IFactoryDao factory = new MysqlDaoFactory();  
    private MysqlDaoFactory() { }  
      
    public static IFactoryDao getInstance() {  
        return factory;  
    }  
      
    @Override  
    public IAddressDao createAddressDao() {  
        return new AddressMySqlDao();  
    }  
  
    @Override  
    public IUserDao createUserDao() {  
        return new UserMySqlDao();  
    }  
  
      
}

 

 


It can be found from the two factories that the products in the two factories are product families (AddressMySqlDao and AddressJDBCDao are the implementation of the same interface)

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Calling factory 1 or 2 in the project also needs to modify the code, which is also not good, so reflection can be used. Write the factory className to be created in the configuration file so that you only need to modify the configuration file, which is flexible, does not destroy encapsulation, and ocp.

 

[java]  view plain copy  
 
  1. package com.yan.factory.dao;  
  2.   
  3.   
  4.   
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.lang.reflect.Method;  
  7. import java.util.Properties;  
  8.   
  9. public class DaoUtil {  
  10.       
  11.     public static IFactoryDao createDaoFactory() {  
  12.         IFactoryDao f = null;  
  13.         try {  
  14.             Properties prop = PropertiesUtil.getDaoProp();  
  15.             String fs = prop.getProperty("factory");  
  16.             Class clz = Class.forName(fs);  
  17.             String mn = "getInstance";  
  18.             Method m = clz.getMethod(mn);  
  19.             f = (IFactoryDao)m.invoke(clz);  
  20.         } catch (ClassNotFoundException e) {  
  21.             e.printStackTrace ();  
  22.         } catch (SecurityException e) {  
  23.             e.printStackTrace ();  
  24.         } catch (NoSuchMethodException e) {  
  25.             e.printStackTrace ();  
  26.         } catch (IllegalArgumentException e) {  
  27.             e.printStackTrace ();  
  28.         } catch (IllegalAccessException e) {  
  29.             e.printStackTrace ();  
  30.         } catch (InvocationTargetException e) {  
  31.             e.printStackTrace ();  
  32.         }  
  33.         return f;  
  34.     }  
  35. }  

dao.properties file

 

 
  1. factory=com.yan.factory.dao.JDBCDaoFactory  

Modifiable configuration file test.

In the project private IAddressDao addressDao = DaoUtil.createDaoFactory().createAddressDao();

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The disadvantage of the above is that it is too complicated. To create multiple factory instances, we can use reflection to create only one factory and write the Dao to be created in the configuration file.

package com.yan.factory.dao;  
  
  
  
import java.util.HashMap;  
import java.util.Map;  
import java.util.Properties;  
  
public class PropertiesFactory implements IFactoryDao {  
    private static PropertiesFactory f = new PropertiesFactory();  
      
    private PropertiesFactory() {   }  
    public static IFactoryDao getInstance() {  
        return f;  
    }  
    @Override  
    public Object getDao(String name) {  
        try {  
              
            Properties prop = PropertiesUtil.getDaoProp();  
            String cn = prop.getProperty(name);  
            Object obj = Class.forName(cn).newInstance();  
            System.out.println(obj);  
            return obj;  
        } catch (InstantiationException e) {  
            e.printStackTrace ();  
        } catch (IllegalAccessException e) {  
            e.printStackTrace ();  
        } catch (ClassNotFoundException e) {  
            e.printStackTrace ();  
        }  
        return null;  
          
          
    }  
  
}  

factory=com.yan.factory.dao.PropertiesFactory  
UserDao="com.yan.factory.dao.UserJDBCDao"  

Reprinted: https://blog.csdn.net/empyan/article/details/54897088; If there is any infringement, please contact to delete it.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686932&siteId=291194637