The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from specific classes. In the Java framework, the factory pattern is used to: create complex objects (such as beans in Spring), provide object isolation, enhance testability and maintainability, support extensions, and increase support for new object types by adding new factory classes
What is the factory pattern?
Factory pattern is a pattern for creating objects. It encapsulates the creation process in a factory class, thereby decoupling the creation process from the specific class that creates the object.
Application scenarios of factory pattern in Java framework
In Java framework, factory pattern is used in the following scenarios:
AbstractBeanFactory
class uses the factory pattern to create complex objects such as beans and bean definitions. Practical case
The following is an example of Spring Bean using factory pattern:
// 工厂类 public class BeanFactory { public Bean createBean(String beanType) { switch (beanType) { case "A": return new BeanA(); case "B": return new BeanB(); default: throw new IllegalArgumentException("Invalid bean type: " + beanType); } } } // Bean 接口 interface Bean { void doSomething(); } // Bean A 实现 class BeanA implements Bean { @Override public void doSomething() { System.out.println("Bean A doing something"); } } // Bean B 实现 class BeanB implements Bean { @Override public void doSomething() { System.out.println("Bean B doing something"); } } // 主类 public class Main { public static void main(String[] args) { BeanFactory factory = new BeanFactory(); // 使用工厂创建 bean 对象 Bean beanA = factory.createBean("A"); beanA.doSomething(); // 输出:Bean A doing something Bean beanB = factory.createBean("B"); beanB.doSomething(); // 输出:Bean B doing something } }
In this example, The BeanFactory
class is a factory class that is responsible for creating Bean
objects based on a given bean type. The Bean
interface defines the public interface of the bean. BeanA
and BeanB
are the specific implementations of the Bean
interface. The Main
class uses the BeanFactory
to create and use Bean
objects.
The above is the detailed content of What are the application scenarios of factory pattern in java framework?. For more information, please follow other related articles on the PHP Chinese website!