Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Writing in the front
Design pattern, in fact, to a certain extent, represents the optimal solution, the best practice, the solution summarized by some developers based on experience, and the optimal solution for different scenarios.
In the current environment, design patterns are also highly respected by developers, and use them to solve many problems, so it is imperative to learn design patterns.
Let’s take a look at the abstract Factory pattern.
Abstract factory pattern is to create other factories around a gigafactory, which is equivalent to creating a factory on top of the factory pattern to coordinate the factories of various factories.
This is also a creative design pattern.
Usage scenarios
When we do a series of operations, we can use the abstract factory pattern, call a method, and use the same object to perform an internal series of operations.
The advantages and disadvantages
The advantage is that when performing a series of operations, the abstract factory pattern allows for a series of operations to be performed using the same object.
The downside is that it can be complex to extend, requiring additional code in multiple classes.
Code implementation
First, declare the interface
public interface Shape {
void draw(a);
}
Copy the code
Second, implement the 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
Third, create a color interface.
public interface Color {
void fill(a);
}
Copy the code
Step 4, create an implementation class for the color interface.
public class Red implements Color {
@Override
public void fill(a) {
System.out.println("Inside Red::fill() method."); }}Copy the code
public class Green implements Color {
@Override
public void fill(a) {
System.out.println("Inside Green::fill() method."); }}Copy the code
Fifth, create the corresponding factory abstraction classes for the shape class and the color class.
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape) ;
}
Copy the code
Step 6, create the factory class for Step 5.
public class ShapeFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } return null; } @Override public Color getColor(String color) { return null; }}Copy the code