通过工厂模式

我们在使用Java代码处理某个问题的时候,需要创建A对象,调用      A对象中的某个方法,但是A对象的创建依赖B对象,而B对象的 创建又依赖于C对象,C对象的创建又依赖于D对象.....,如下:

D d=new D();

C c=new C(d);

B b=new B(c);

A a=new A(b);

这样造成,代码的阅读性极差

解决:

将对象的创建过程进行封装,直接返回创建好的对象使用.

实现:

工厂设计模式

本质:就是封装对象的创建过程的一种代码的编程思想

静态工厂:生产对象的方法是静态方法

public class AFactory{

public static A newInstance(){

D d=new D();

C c=new C(d)

B b=new B(c);

A a=new A(b);

return a;

}

}

动态工厂:生产对象的方法是非静态方法

public class AFactory{

public A newInstance(){

D d=new D();

C c=new C(d)

B b=new B(c);

A a=new A(b);

return a;

}

}

SpringIOC使用工厂创建对象:

传统方案:

我们自己创建工厂,然后调用工厂生产对象的方法,获取生产的对象,然后使用生产的对象完成功能开发.

IOC方案:

Spring容器创建工厂,并自动调用其创建的工厂的生产对象的方法,生产的对象直接存储在Spring容器中,我们直接从Spring容器中获取对象,完成功能开发.

①动态工厂模式

②静态工厂模式

applicationcontext.xml配置示例:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--创建student的bean对象-->
    <!--工厂设计模式-->
    <!--动态工厂-->
        <bean id="factory" class="com.bjsxt.pojo.StudentFactory"></bean>
        <!--生产Student对象-->
        <bean id="stu4" factory-bean="factory" factory-method="newIntance"></bean>
    <!--静态工厂-->
    <!--可以理解为静态方法直接用类名调用-->
        <bean id="stu5" class="com.bjsxt.pojo.StudentFactory2" factory-method="newIntance"></bean>
</beans>

  

package com.bjsxt.controller;

import com.bjsxt.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author wuyw2020
 * @date 2020/1/8 15:16
 */
public class testStu {
    
    public static void main(String[] args) {
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        //获取容器中的对象
        //工厂设计模式     
            //动态工厂
            Student student = (Student) ac.getBean("stu4");
            System.out.println("动态工厂:"+student);
            //静态工厂
            Student student1 = (Student) ac.getBean("stu5");
            System.out.println("静态工厂:"+student1);
    }
}

  

posted @ 2021-01-18 17:22  巧克力曲奇  阅读(57)  评论(0编辑  收藏  举报