Spring band you fly (2) - When the spring before useless, how do we solve the problem of coupling procedures

First, let's look at what is the coupling procedure, the coupling means that dependencies between programs. Then the decoupling means is to reduce the dependencies between programs. In our actual development: should do, compile does not depend on, rely only run .

Well, so much nonsense above, let's look at a program.

/**
 * @ClassName: AccountServiceImpl
 * @author: benjamin
 * @version: 1.0
 * @description: 账户业务层接口的实现类
 * @createTime: 2019/07/24/17:10
 */
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao = new AccountDaoImpl();
    public void  saveAccount(){   
        System.out.println("业务层保存账户。。。");
    }
}

We can see, at this time the code calls the business layer entity classes persistence layer, if we do not at this time persistence layer implementation class, the compiler can not. During the compilation of this dependence, we should put an end to.

Factory mode decoupling

In the actual development, we can put three layers of objects with a profile configured up when starting the server application loading, so that the method in a class by reading the configuration file, to create out of these objects coexist together. When the next use directly take over with a fine. So, this reads the configuration file and create an object of class is acquiring three factories.

We first look at the project structure:

  1. Create a maven project;

  2. Create a business layer interface and implementation class

    /**
     * 账户的业务层接口
     * @ClassName: IAccountService
     * @author: benjamin
     * @createTime: 2019/07/24/17:08
     */
    public interface IAccountService {
        /**
         * 模拟保存账户
         */
        void saveAccount();
    }
    
    /**
     * @ClassName: AccountServiceImpl
     * @author: benjamin
     * @version: 1.0
     * @description: 账户业务层接口的实现类
     * @createTime: 2019/07/24/17:10
     */
    
    public class AccountServiceImpl implements IAccountService {
        private IAccountDao accountDao = new AccountDaoImpl();
    
        public void  saveAccount(){
            System.out.println("业务层保存账户。。。");
            accountDao.saveAccount();
        }
    }
  3. Create a persistence layer interface and implementation class

    /**
     * 账户的持久层接口
     * @ClassName: IAccountDao
     * @author: benjamin
     * @createTime: 2019/07/24/17:07
     */
    public interface IAccountDao {
    
        /**
         * 模拟保存账户
         */
        void saveAccount();
    }
    
    /**
     * @ClassName: AccountDaoImpl
     * @author: benjamin
     * @version: 1.0
     * @description: 账户的持久层实现类
     * @createTime: 2019/07/24/17:10
     */
    
    public class AccountDaoImpl implements IAccountDao {
        public  void saveAccount(){
            System.out.println("保存了账户");
        }
    }
  4. Creating presentation

    /**
     * @ClassName: Client
     * @author: benjamin
     * @version: 1.0
     * @description: 模拟一个表现层,用于调用业务层
     * @createTime: 2019/07/24/17:08
     */
    
    public class Client {
        public static void main(String[] args) {
            // 耦合
            IAccountService as = new AccountServiceImpl();
            System.out.println(as);
            as.saveAccount();
        }
    }

    You can see, now the presentation layer and the business layer, presentation layer and persistence layer appeared coupling procedure, we should avoid following the use of factory pattern to reduce coupling.

  5. Create a file bean.properties

    accountService=com.ben.service.impl.AccountServiceImpl
    accountDao=com.ben.dao.impl.AccountDaoImpl
  6. Creation bean factory object, which is to create our service and dao objects.

    Bean: English in the computer, there is the meaning of reusable components.

    JavaBean: written in java language reusable components.
    javabean> entity class

    1. You need a configuration file to configure the content of our service and dao configuration: = uniquely identifies the fully qualified class name (key = value);
    2. By reading the contents of the configuration of the configuration file, the reflection to create objects. Xml configuration file can also be properties (Spring framework is used xml file), in this case we use properties.
    /**
     * @ClassName: BeanFactory
     * @author: benjamin
     * @version: 1.0
     * @description: bean工厂
     * @createTime: 2019/07/24/17:08
     */
    
    public class BeanFactory {
    
        //定义一个Properties对象
        private static Properties props;
    
        //定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
        private static Map<String, Object> beans;
    
        //使用静态代码块为Properties对象赋值
        static{
            try {
                //实例化对象
                props = new Properties();
                //获取properties文件的流对象
                InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
                props.load(in);
                //实例化容器
                beans = new HashMap<String,Object>();
                //取出配置文件中所有的Key
                Enumeration keys = props.keys();
                //遍历枚举
                while (keys.hasMoreElements()){
                    //取出每个Key
                    String key = keys.nextElement().toString();
                    //根据key获取value
                    String beanPath = props.getProperty(key);
                    //反射创建对象
                    Object value = Class.forName(beanPath).newInstance();
                    //把key和value存入容器中
                    beans.put(key,value);
                }
            }catch(Exception e){
                throw new ExceptionInInitializerError("初始化properties失败!");
            }
        }
    
        /**
         * 根据bean的名称获取对象
         * @param beanName
         * @return Object
         */
        public static Object getBean(String beanName){
            return beans.get(beanName);
        }
    }
  7. Modify the presentation layer file

    public class Client {
        public static void main(String[] args) {
    
            for(int i=0;i<5;i++) {
                IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
                System.out.println(as);
                as.saveAccount();
            }
        }
    }

Guess you like

Origin www.cnblogs.com/benjieqiang/p/11238356.html