Q: What are design patterns
Slowly: Design pattern is a solution for common scenarios in system service design, which can solve common problems encountered in the development of functional logic. Design pattern is not limited to the final implementation scheme, but in this conceptual pattern, to solve the code logic problems in system design.
Q: What is factory mode
Slowly: The factory pattern, also known as the Simple Factory pattern, is a type of creative design pattern that provides the best way to create objects on demand. At the same time, this method of creation does not expose the creation details.
That is, by defining the parent class interface of a class of items, through this interface to standardize all the items below it, and then by creating a factory, to achieve fast and flexible creation of such items.
Q: Can you understand it in code?
Slowly: OK.
This is an item parent interface:
public interface Shape {
void draw(a);
}
Copy the code
All items in this mode need to inherit the above interface:
public class Rectangle implements Shape {
@Override
public void draw(a) {
System.out.println("Inside Rectangle::draw() method."); }}Copy the code
public class Square implements Shape {
@Override
public void draw(a) {
System.out.println("Inside Square::draw() method."); }}Copy the code
Create a factory:
public class ShapeFactory {
// Use getShape to get an object of the shape type
public Shape getShape(String shapeType){
if(shapeType == null) {return null;
}
if(shapeType.equalsIgnoreCase("RECTANGLE")) {return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")) {return new Square();
}
return null; }}Copy the code
We call the factory to get the item we want.
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
// Get the Rectangle object and call its draw method
Shape shape1 = shapeFactory.getShape("RECTANGLE");
// Call the Rectangle draw method
shape1.draw();
// Get the Square object and call its draw method
Shape shape2 = shapeFactory.getShape("SQUARE");
// Call Square's draw methodshape2.draw(); }}Copy the code
Q: Why a factory? Can’t I just create the class?
Slowly: If a class has many properties and the default values of those properties or behaviors are roughly the same, we can encapsulate that code in the form of a factory to reduce the hassle of having to set it up again every time the class is created.
Q: Why bother to create so many classes, just use if-else to distinguish different items?
Slowly: That’s what learning design patterns is all about. If we differentiate between different items in the code, if there are a large number of items that need to be changed, we not only have to locate the location to be changed, but we may even have to figure out the logic of the whole code.
To distinguish between different classes, we just need to locate the class and make specific changes to it.