Design Pattern Abstract Factory Schema

Source: Internet
Author: User

I studied the factory model and thought about its application scenarios and many online statements.


Several questions:

1. If you use factory on the internet, you don't need to use new. But the question is, if you don't rely directly or indirectly, what is the role? How much code is saved? Easy to expand?

2. The book says that a system must be independent of the creation, combination, and representation of its products. A system must be configured by one of multiple product generations. When you want to emphasize the design of a series of related product objects for joint use. When you provide a product library, instead of displaying their interfaces, you should use the factory mode. But the question is, what the fuck is talking about?


So I started my thinking process with the following ideas:

1. What I said in the book will become a fairy after I understand it. The author writes a book or the interpreter writes this book without morality and does not consider the feelings of the readers, there is not much talk here, so you don't need to run the question

2. I started to think about many online statements and tried to find out the starting point behind them.

-If the amount of code saved is shown in the demo on the Internet, on the surface, there is not much code saved, but a lot of interfaces are added. However, in the big job, what if there are many classes? If you simply change New to getfromfactory, the advantage of factory is obviously not realized.

-If decoupling is true, but the original direct dependency is changed to indirect dependency, what is the role? It seems to have no effect, because consumers still need to ask the factory for the type they want.


When there is no answer to the above ideas, I began to try to find the real example, and then consider its practical significance. Then I thought of spring's beanfactory, which is a typical factory model, so what does it mean? I decided to follow spring to find the answer.

During the interview N years ago, I was asked, "What are the benefits of using IOC "? I replied, "no new" and asked, "what if I don't use spring and all of them are new ?", I'm speechless. However, if I want to answer this question again, I will say, "decoupling, unified bean management, and dependency inversion"

"Unified bean management and dependency reversal" relies on the factory mode.

In a complicated scenario, as an administrator who provides beans externally, I want to tag all the beans that come out from me. How can this problem be solved? I want to unify the requirements. The bean I provided should send a message to me when it is called to count the number of calls. How can this problem be solved? The premise is that the internal logic of bean cannot be changed? (In fact, it is impossible to change it one by one). The answer is factory + proxy, which is a unified management.

Another problem is IOC. When the factory mode is used, the factory acts as the maintainer of the bean dependency, that is, from the original function that a must rely on B to implement a function, the implementation function of A does not know who to depend on. The factory tells it that the Online Demo here is easy to misunderstand: from the original new to getfromfactory ("beanname "), I don't know here -- this dependency has not actually changed, but there is only one more layer. But actually not, spring bean Management maintains bean Dependencies from spring configuration files. Before calling each other, spring has long assembled various beans according to this management file. This is the so-called control reversal.


In this way, bean functions become more simple, and complicated relationship maintenance is handed over to the factory, so there is no doubt here. Then a program is written to simulate the bean loading process of spring:


Factory interface:

public interface AbstractFactory {Object getBean(String beanName);}

Factory implementation:

public class ApplicationContext implements AbstractFactory {private BeanDefinitionRegistry beanMapper = new BeanDefinitionRegistry();private Map<String,Object> beans = new HashMap<String,Object>();public Object getBean(String beanName) {return beans.get(beanName);}public ApplicationContext () {init();}private void init() {loadBean();wireBean();}private void wireBean() {for (Entry<String,Object> entry : beans.entrySet()) {Object bean = entry.getValue();Class c = bean.getClass();Field[] fields = c.getDeclaredFields();wireField(fields,bean);}}private void wireField(Field[] fields,Object bean) {for (Field field : fields) {try {field.setAccessible(true);Object value = field.get(bean);if (value == null) {field.set(bean, beans.get(field.getName()));}} catch (Exception e) {}}}private void loadBean() {for (Entry<String, Object> entry : beanMapper.getBeanDefinition().entrySet()) {doLoadBean(entry.getKey(),entry.getValue());}}private void doLoadBean(String key, Object value) {Class c = (Class)value;try {Object o = c.getConstructor().newInstance(null);beans.put(key, o);} catch (Exception e) {}}}


Bean configuration simulation:

public class BeanDefinitionRegistry {public Map<String,Object> beanDefinition = new HashMap<String,Object>();public BeanDefinitionRegistry() {beanDefinition.put("serviceA", ServiceA.class);beanDefinition.put("serviceB", ServiceB.class);}public Map<String, Object> getBeanDefinition() {return beanDefinition;}}

Two Dependent Services:

public class ServiceA {private ServiceB serviceB;public ServiceB getServiceB() {return serviceB;}public void setServiceB(ServiceB serviceB) {this.serviceB = serviceB;}public String getCurrentDate() {return serviceB.getCurrentDate();}}
public class ServiceB {public String getCurrentDate() {return new Date().toString();}}
The final test class:

public class Tester {public static void main(String[] args) {AbstractFactory beanFactory = new ApplicationContext();ServiceA serviceA = (ServiceA)beanFactory.getBean("serviceA");String currentDate = serviceA.getCurrentDate();System.out.println(currentDate);}}


Here, the factory model has its own understanding, welcome to exchange, welcome to challenge









Design Pattern Abstract Factory Schema

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.