1. Preamble
In the process of work, the more and more feel the importance of design patterns. Often people will say that people who have been working for 5 years, college students can do the same job with 1-2 months of casual training, and yes, college students can indeed do it.
But the code it writes, maintainability, scalability, ease or simplicity when adding new features. Even the performance of soft power, how to communicate, how to promote the progress of the project, how to do the project scheduling, in fact, fresh graduates do not have. (Of course, 5 years of work and college students are not different, then you should be eliminated by society, not cut you, cut who it)
People don't need to be condescending, but they don't need to be presumptuous either.
In response to this, I've come up with a series of "Follow ChatGPT to learn design patterns", which you are welcome to like, favorite and forward, and today we're learning about the Factory Pattern. Including: Simple Factory Pattern, Factory Pattern, Abstract Factory Pattern
2. Simple factory model
Q: Could you explain the Simple Design Factory pattern in detail, with concise answers so that children can understand it?
What is the Simple Factory Pattern?
The Simple Factory Pattern is a design pattern that takes care of creating instances of other classes through a specialized class. This specialized class is often referred to as a "factory class". The main purpose of the Simple Factory Pattern is to encapsulate the process of creating an object so that the client code does not need to know the details of the creation.
Why do you need the Simple Factory Pattern?
- Simplifying Object Creation: Client-side code doesn't need to know how to create objects, only how to use them.
- Improve code maintainability: If you need to change how an object is created, you only need to modify the factory class, not the client code.
- Reduce duplicate code: Centralize the object creation logic in one place to avoid repeating the same creation code in multiple places.
Take a life example.
Imagine you have a toy store which produces different kinds of toys like cars, dolls and blocks. All you have to do is tell the clerk which kind of toy you want and the clerk will get it for you.
- salesperson: Equivalent to the factory class.
- toys: Equivalent to the object that needs to be created.
- You tell the clerk the type of toy you want.: Equivalent to client code requesting the factory class to create an object.
concrete step
- Define the product: First, you need to define various toys, such as cars, dolls and blocks.
- Creating a Factory Class: Then, you need to create a factory class that has a method that creates the appropriate toy based on the type of toy you provide.
- Using Factory Classes: Finally, when you need a toy, you just call a method of the factory class, tell it which toy you want, and it will return the appropriate toy to you.
vantage
- Simplify client-side code: Client-side code doesn't need to know how to create objects, only how to use them.
- Centralized management of object creation: Centralize the logic of object creation in one place for easy management and maintenance.
- High flexibility: New toy types can be easily added by modifying the factory class without modifying the client code.
drawbacks
- The principle of single responsibility: The factory class can get complicated because it needs to handle all the object creation logic.
- No support for extensions: If a new toy type needs to be added, the code of the factory class must be modified, which violates the open-close principle (open to extensions, closed to modifications).
summarize
The simple factory model is like a clerk in a toy store, you tell him what toys you want and he gets them for you. This way you don't need to find these toys yourself, just focus on playing.
I hope this explanation has helped you! If there are any other questions, just ask.
Q: Then please implement the following in code
public interface Animal {
void speak();
}
public class Cat implements Animal {
@Override
public void speak() {
("Cat speak!");
}
}
public class Dog implements Animal {
@Override
public void speak() {
("Dog speak!");
}
}
public class AnimalFactory {
// In practice, you can use ApplicationContext with @PostConstruct to get all the implementation classes of Animal.
private static Map<String, Animal> map = new HashMap<>();
static {
("dog", new Dog()); ("cat", new Cat", new Cat())
("cat", new Cat());
}
public static Animal createAnimal(String type) {
if ((type)) {
return (type); }
}
throw new IllegalArgumentException("Unknown animal type"); }
}
}
public class Main {
public static void main(String[] args) {
// Whether to create a dog or a cat can usually be determined by the type, which is unique to each class.
// Or, depending on the configuration, environment variables can be read, etc.
Animal dog = ("dog");
().
Animal cat = ("cat"); (); (); (); (); ()
();
}
}
Simple factory pattern is only a factory, according to the type of product to create different types of products, applicable to create simple products. This is a very commonly used in our code is a strategy pattern, especially with spring to use, you can achieve unexpected results.
3. Factory model
Q: What about the factory pattern, please give a detailed explanation of it
What is the Factory Pattern?
The Factory pattern is a creation-based design pattern that defines an interface for creating objects, but leaves it up to the subclasses to decide which class to instantiate. Factory methods allow the instantiation of the class to be deferred to the subclass.
Why do you need the Factory Pattern?
- decoupled: Separate the creation and use of an object so that client code doesn't need to know the exact creation details.
- scalability: The product range can be extended by adding new subclasses without modifying existing code.
- The principle of single responsibility: Each factory class is responsible for creating only one product, with a single responsibility and clearer code.
Take a life example.
Imagine you have a toy store that has different departments, each department is responsible for producing a specific type of toy, such as the car department, the doll department, and the building block department. All you need to do is find the appropriate department and they will help you produce the toy you want.
- toy store: Equivalent to the factory interface.
- Different sectors: Equivalent to a concrete factory class.
- toys: Equivalent to the object that needs to be created.
- You find the appropriate department.: Equivalent to client code requesting a concrete factory class to create an object.
concrete step
- Define the product interface: First, you need to define a toy interface that all toys implement.
- Creating a concrete product class: Then, you need to create concrete toy classes, such as cars, dolls, and blocks, which implement the toy interface.
- Defining the Factory Interface: Next, you need to define a factory interface that has a method for creating toys.
- Creating a concrete factory class: Then, you need to create concrete factory classes, each of which is responsible for creating a particular kind of toy.
- Using Factory Classes: Finally, when you need a toy, you just call the method of the appropriate factory class, and it will return the appropriate toy to you.
vantage
- decoupled: The client code does not need to know the exact creation details, only the factory interface.
- scalability: You can extend the product range by adding new concrete factory classes without modifying existing code.
- The principle of single responsibility: Each factory class is responsible for creating only one product, with a single responsibility and clearer code.
drawbacks
- Increase in the number of classes: For each additional product, a specific factory class needs to be added and the number of classes increases.
- Increased complexity: Compared to the Simple Factory pattern, the Factory pattern has a more complex structure and requires more interfaces and classes to be defined.
summarize
The factory model is like a toy store with different departments, each of which is responsible for producing a specific toy. All you need to do is find the appropriate department and they will help you produce the toys you want. This way you don't need to create these toys yourself, just focus on using them.
I hope this explanation has helped you! If there are any other questions, just ask.
Q: Then please implement the following in code
public interface AnimalFactory {
Animal createAnimal();
}
public class CatFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Cat();
}
}
public class DogFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
}
public class Main {
public static void main(String[] args) {
AnimalFactory dogFactory = getFactory("dog");
Animal dog = ();
();
AnimalFactory catFactory = getFactory("cat");
Animal cat = ();
();
}
// Generally createdogFactoryneverthelesscatFactory,This can generally be done withtypejudgement,Each class has atype
// or eradication configuration,Environment variables can be read, etc.
public static AnimalFactory getFactory(String animalType) {
if ("dog".equals(animalType)) {
return new DogFactory();
} else if ("cat".equals(animalType)) {
return new CatFactory();
}
throw new IllegalArgumentException("Unknown animal type");
}
}
The factory pattern compared to the simple factory pattern, it has an AnimalFactory interface, specifically a factory for each product. It is possible to generate very complex products, but with that comes an inflated factory
4. Abstract Factory Pattern
Q: What about the Abstract Factory Pattern?
What is the Abstract Factory Pattern?
The Abstract Factory pattern is a creation-based design pattern that provides an interface for creating a series of related or interdependent objects without specifying their specific classes. The Abstract Factory pattern enables more complex object creation by combining multiple factory methods.
Why do you need the Abstract Factory pattern?
- The concept of product families: When a system needs to handle multiple product families, the abstract factory pattern can provide a uniform interface to create these products.
- decoupled: The client code does not need to know the specific product class, only the factory interface.
- consistency: Ensure that objects in the same product family are compatible when used together.
Take a life example.
Imagine you have a furniture store that produces different styles of furniture, such as modern and classic styles. Each style of furniture includes chairs and tables. All you need to do is tell the store clerk which style of furniture you want, and the clerk will produce the appropriate style of chairs and tables for you.
- furniture store: Equivalent to an abstract factory interface.
- Different styles of furniture sector: Equivalent to a concrete factory class.
- Chairs and tables: Equivalent to the object that needs to be created.
- You tell the clerk the style of furniture you want: Equivalent to client code requesting a concrete factory class to create an object.
concrete step
- Define product interface: First, you need to define the interfaces for chairs and tables, which all chairs and tables implement.
- Creating a concrete product class: Then, you need to create concrete chair and table classes, such as modern style chairs and tables and classical style chairs and tables, which implement the appropriate interfaces.
- Defining the Abstract Factory Interface: Next, you need to define an abstract factory interface that has methods for creating chairs and tables.
- Creating a concrete factory class: Then, you need to create concrete factory classes, each responsible for creating a particular style of chair and table.
- Using Factory Classes: In the end, all you need to do when you need furniture is to call the methods of the appropriate factory class, and it will return the appropriate style of chairs and tables to you.
vantage
- Product Family Creation: It is easy to create a series of related or interdependent objects.
- decoupled: The client code does not need to know the specific product class, only the factory interface.
- consistency: Ensure that objects in the same product family are compatible when used together.
drawbacks
- Increased complexity: Compared to the factory method pattern, the abstract factory pattern has a more complex structure and requires more interfaces and classes to be defined.
- Expansion difficulties: If you need to add a new product family, you need to modify the abstract factory interface and all its concrete factory classes.
summarize
The abstract factory pattern is like a furniture store with different style departments, each responsible for producing a particular style of furniture. All you need to do is tell the store clerk which style of furniture you want, and they will produce chairs and tables in the appropriate style for you. This way you don't need to create these pieces of furniture yourself, just focus on using them.
I hope this explanation has helped you! If there are any other questions, just ask.
Q: Then please implement the following in code
We now have not only animals, but also food
public interface AnimalFood {
void eat();
}
public class CatFood implements AnimalFood {
@Override
public void eat() {
("Cat is eating cat food.");
}
}
public class DogFood implements AnimalFood {
@Override
public void eat() {
("Dog is eating dog food.");
}
}
public interface AnimalFactory {
Animal createAnimal();
AnimalFood createAnimalFood();
}
public class CatFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Cat();
}
@Override
public AnimalFood createAnimalFood() {
return new CatFood();
}
}
public class DogFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
@Override
public AnimalFood createAnimalFood() {
return new DogFood();
}
}
public class Main {
public static void main(String[] args) {
AnimalFactory catFactory = new CatFactory();
Animal cat = ();
AnimalFood catFood = ();
();
();
//---------------------------------------//
AnimalFactory dogFactory = new DogFactory();
Animal dog = ();
AnimalFood dogFood = ();
();
();
}
}
Abstract factories can easily create a series of related or interdependent objects, but their classes are very bloated and are still relatively little used in the development process.
5. Finally
All the codes in the article are available to everyone at the following linkgithub
Finally this series will continue to be updated, so feel free to like favorite and retweet!