当前位置:网站首页>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 .
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 .
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 .
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 !
边栏推荐
- [SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)
- Echo framework: implementing service end flow limiting Middleware
- 2021-11-14:Fizz Buzz。 I'll give you an integer n and find the number from 1 to n
- Ppt layout design how to make pages not messy
- [planting grass by technology] three big gifts prepared by Tencent cloud for you on the double 11, welcome to touch~
- Embedded hardware development tutorial -- Xilinx vivado HLS case (process description)
- Baysor: cell segmentation in imaging based spatial transcriptomics
- NFS operations and deployment
- Kubesphere upgrade & enable plug-ins after installation
- Stm32g474 infrared receiving based on irtim peripherals
猜你喜欢

It's too difficult for me. Ali has had 7 rounds of interviews (5 years of experience and won the offer of P7 post)

layer 3 switch

Review of AI hotspots this week: the Gan compression method consumes less than 1/9 of the computing power, and the open source generator turns your photos into hand drawn photos

I, a 27 year old female programmer, feel that life is meaningless, not counting the accumulation fund deposit of 430000
![[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)](/img/b5/a8c4bbaf868dd20b7dc9449d2a4378.jpg)
[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)
![[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)](/img/c8/f6c2a62b8ab8fa88bd2b3d8f35f592.jpg)
[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)

Stm32g474 infrared receiving based on irtim peripherals
随机推荐
How to determine whether easycvr local streaming media is started successfully?
tokio_ Rustls self signed certificate
Make standardized tools in the cloud native era to realize efficient cloud R & D workflow
DCOM horizontal movement of Intranet penetration
[official time limit activity] in November, if you dare to write, you will get a prize
Tencent cloud database tdsql elite challenge --q & A
Analysis report on operation situation and development trend of global and Chinese diisobutyl aluminum hydride (Dibah) industry 2022-2028
Tcapulusdb Jun · industry news collection
[tcapulusdb knowledge base] how to rebuild tables in tcapulusdb table management?
[technical grass planting] the cloud driver takes you straight to the clouds
Nature Reviews Neuroscience: cognitive and behavioral flexibility - neural mechanisms and clinical considerations
How does easynvr set the video recording to be saved for more than 30 days?
[actual combat] how to realize people nearby through PostGIS
[untitled]
[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)
How to make a ECS into a fortress machine how long does it take to build a fortress machine
Build and enable all plug-ins of kubesphere high availability cluster
Devops learning notes (II)
Clean system cache and free memory under Linux
Clubhouse online supports replay function; Webobs live streaming tools are going to be popular |w