当前位置:网站首页>Thoroughly explain the details of the simple factory that you haven't paid attention to

Thoroughly explain the details of the simple factory that you haven't paid attention to

2022-06-24 01:54:00 Tom bomb architecture

This article is excerpted from 《 This is how design patterns should be learned 》

1 Encapsulate product creation details using the simple factory pattern

Now let's look at the code , Let's take the creation of an online course as an example . Suppose there is Java framework 、 big data 、 Artificial intelligence and so on , Has formed an ecological . We can define a curriculum standard ICourse Interface .

public interface ICourse {
    /**  record video  */
    public void record();
}

Create a Java Implementation class of course JavaCourse.

public class JavaCourse implements ICourse {
    public void record() {
        System.out.println(" Recording Java Course ");
    }
}

The client call code is as follows .

public static void main(String[] args) {
    ICourse course = new JavaCourse();
    course.record();
}

From the above code, we can see , Parent class ICourse Pointing subclass JavaCourse References to , Application layer code needs to rely on JavaCourse. If the business expands , Continue to increase PythonCourse, Even more , Then the dependence of the client will become more and more bloated . therefore , We have to find a way to reduce this dependence , Hide creation details . Although in the current code , The process of creating objects is not complicated , But it's not easy to extend from a code design point of view . therefore , Optimize the code with a simple factory pattern . First, add courses PythonCourse class .

public class PythonCourse implements ICourse {
    public void record() {
        System.out.println(" Recording Python Course ");
    }
}

Then create CourseFactory Factory .

public class CourseFactory {
    public ICourse create(String name){
        if("java".equals(name)){
            return new JavaCourse();
        }else if("python".equals(name)){
            return new PythonCourse();
        }else {
            return null;
        }
    }
}

Finally, modify the client call code .

public class SimpleFactoryTest {
    public static void main(String[] args) {
        CourseFactory factory = new CourseFactory();
        factory.create("java");
    }
}

Of course , For the convenience of calling , Can be CourseFactory Of create() Change method to static method , The class diagram is shown in the following figure .

file

Although the client call is simple , But if the business continues to expand , To add front-end courses , In the factory create() The method is to modify the code logic every time with the enrichment of the product chain , This is not in line with the open close principle . therefore , We can continue to optimize the simple factory model using reflection technology , The code is as follows .

public class CourseFactory {
    public ICourse create(String className){
        try {
            if (!(null == className || "".equals(className))) {
                return (ICourse) Class.forName(className).newInstance();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

The client calling code is modified as follows .

public static void main(String[] args) {
        CourseFactory factory = new CourseFactory();
        ICourse course = factory.create("com.gupaoedu.vip.pattern.factory.simplefactory.JavaCourse");
        course.record();
}

After the optimization , Products are constantly enriched , It doesn't need to be modified CourseFactory The code in . But the problem is , Method arguments are strings , Controllability needs to be improved , And there is a need for forced transformation . Continue to modify the code .

public ICourse create(Class<? extends ICourse> clazz){
    try {
        if (null != clazz) {
            return clazz.newInstance();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

Optimize client test code .

public static void main(String[] args) {
    CourseFactory factory = new CourseFactory();
    ICourse course = factory.create(JavaCourse.class);
    course.record();
}

Finally, let's look at the class diagram shown in the figure below .

file

2 The simple factory model is JDK Application in source code

The simple factory model is JDK The source code is everywhere , for example Calendar class , see Calendar.getInstance() Method . The opening below is Calendar The specific creation class of .

private static Calendar createCalendar(TimeZone zone, Locale aLocale) {
    CalendarProvider provider =
        LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
                             .getCalendarProvider();
    if (provider != null) {
        try {
            return provider.getInstance(zone, aLocale);
        } catch (IllegalArgumentException iae) {
        }
    }

    Calendar cal = null;

    if (aLocale.hasExtensions()) {
        String caltype = aLocale.getUnicodeLocaleType("ca");
        if (caltype != null) {
            switch (caltype) {
            case "buddhist":
            cal = new BuddhistCalendar(zone, aLocale);
                break;
            case "japanese":
                cal = new JapaneseImperialCalendar(zone, aLocale);
                break;
            case "gregory":
                cal = new GregorianCalendar(zone, aLocale);
                break;
            }
        }
    }
    if (cal == null) {

        if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
            cal = new BuddhistCalendar(zone, aLocale);
        } else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
                   && aLocale.getCountry() == "JP") {
            cal = new JapaneseImperialCalendar(zone, aLocale);
        } else {
            cal = new GregorianCalendar(zone, aLocale);
        }
    }
    return cal;
}

3 The simple factory model is Logback Application in source code

In what we often use Logback in , You can see LoggerFactory There are multiple overloaded methods in getLogger().

public static Logger getLogger(String name) {
    ILoggerFactory iLoggerFactory = getILoggerFactory();
    return iLoggerFactory.getLogger(name);
}

public static Logger getLogger(Class clazz) {
    return getLogger(clazz.getName());
}

Pay attention to WeChat public number 『 Tom Bomb architecture 』 reply “ Design patterns ” The complete source code is available .

【 recommend 】Tom Bomb architecture :30 A real case of design pattern ( Source code attached ), Challenge annual salary 60W Is not a dream

This paper is about “Tom Bomb architecture ” original , Reprint please indicate the source . Technology is about sharing , I share my happiness !undefined If this article helps you , Welcome to pay attention and like ; If you have any suggestions, you can also leave comments or private letters , Your support is the driving force for me to adhere to my creation . Pay attention to WeChat public number 『 Tom Bomb architecture 』 More technical dry goods are available !

原网站

版权声明
本文为[Tom bomb architecture]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211110144124986a.html