Original: Curly brace MC(wechat official account: Huakuohao-MC), welcome to share, please keep the source.
The factory pattern is a creative design pattern. Is the daily use of a more common design pattern. Frameworks such as Logback and Spring use this design pattern extensively.
The simple factory pattern mentioned in the previous article can be used in simple systems, but because the factory class itself contains too much business logic, and if you want to add new chart types, you need to modify the factory class. So our real production system is more factory mode.
The factory pattern defines a separate factory class for each class that is responsible for creating a single product.
For example
Logs are created in factory mode, creating different types of factories for different types of loggers.
Take a look at the UML diagram:
How does the code work
Let’s define a Logger interface and a LoggerFactory interface
public interface Logger {
void writeLogger();
}
Copy the code
public interface LoggerFactory{
Logger createLogger();
}
Copy the code
Define FileLogger and FileLoggerFactory respectively
public class FileLogger implements Logger { @Override public void writeLogger() { System.out.println("File logger"); }}Copy the code
Public class FileLoggerFactory implements LoggerFactory {@override public Logger createLogger() Logger logger = new FileLogger(); return logger; }}Copy the code
If you want to add a new Logger, just implement Logger and LoggerFactory
public class Client { public static void main(String[] args){ Logger logger; LoggerFactory loggerFactory; loggerFactory = new FileLoggerFactory(); logger = loggerFactory.createLogger(); logger.writeLogger(); }}Copy the code
conclusion
Factory mode is one of the creation mode, which is used more frequently in daily life. Each type of product has a corresponding factory class. The factory pattern migrates the internal logic of a simple factory to the client, and when the functionality needs to be extended, the client needs to be modified.
Recommended reading
1. Java concurrent programming stuff (10) — Final summary
2. Common network problem locating tools that programmers should master
3. Do you know how to use Awk
4. Teach you how to build a set of ELK log search operation and maintenance platform
Original: Curly brace MC(wechat official account: Huakuohao-MC) Focus on JAVA basic programming and big data, focus on experience sharing and personal growth.