I see the design pattern of the factory design pattern 1

This semester has newly opened the course Design Patterns, and the teacher asked to write an experiment report, so I will synchronize my own experiment report on CSDN!
Write the first simple factory design pattern first! Reminder: This is a series!
In the Java language, objects can be created in many ways

  • Create objects directly using the new keyword
  • Create objects through reflection
  • Create an object through the clone method
  • Create objects using deserialization

Factory patterns are divided into simple factory patterns, factory method patterns, and abstract factory patterns. The simple factory pattern, which simply realizes the separation of object creation and use, is also called the static factory method pattern, which belongs to the class creation pattern. In the simple factory pattern, instances of different classes are returned depending on the parameters. Look at the code:

public abstract class BallPen {
    
    
    BallPen() {
    
    
        System.out.println("生产了一只装有"+getPenCore().color+"笔芯的圆珠笔");
       }
    public abstract PenCore getPenCore();
}

For example, an abstract class BallPen is defined in Pen and Refill, which has a constructor for creating an instance of the class. When the constructor is called, it prints a message to the console indicating that a ballpoint pen with a refill of the specified color has been produced. It has an abstract method called getPenCore(). This method returns an instance of the abstract class PenCore.
So the purpose of this class is to provide a template to create different types of ballpoint pens. The specific type of core used by the ballpoint pen is determined by the subclasses that extend BallPen. By defining getPenCore() as an abstract method, BallPen allows each subclass to implement its own version of this method and return the specific type of PenCore it uses.

public abstract class PenCore {
    
    
    String color;
    public abstract void writeWord(String s);
}

The PenCore abstract class has a color instance variable, which represents the color of the pen refill, and an abstract method writeWord(), which represents the behavior when using the pen refill to write. Since both classes are abstract, they cannot be instantiated directly. Instead, they must be extended by subclasses that implement their abstract methods.

public class BlueBallPen extends BallPen{
    
    
    public PenCore getPenCore(){
    
    
       return new BluePenCore();
    }
}

At the same time, BuleBallPen inherits the BallPen method, because it is an abstract class, it must implement the PenCore method of the parent class, so BuleBallPen returns its own BluePenCore instance object.

public class BluePenCore extends PenCore{
    
    
    BluePenCore(){
    
    
      color="蓝色";
    }
    public void writeWord(String s){
    
    
       System.out.println("写出"+color+"的字:"+s);
    }
}

So when the subclass of PenCore overrides the method, its specific refill type is determined by the subclass.
For example, when the blue refill inherits the PenCore. The writeWord method is rewritten to print out "the word of the incoming color type has been written".

    public static void main(String args[]){
    
    
       PenCore penCore;
       BallPen ballPen=new BlueBallPen();
       penCore=ballPen.getPenCore();
       penCore.writeWord("你好,很高兴认识你");

    }

So in the main function, the first line defines PenCore penCore;
because PenCore is an abstract method that cannot be instantiated, but abstract classes can declare objects. When declaring a variable of an abstract class type, the variable itself can be instantiated as null, although we Objects cannot be instantiated directly, but we can use the variable penCore to refer to an instance of any concrete subclass of PenCore.

So in line 4 of the code, we refer the pencore to the getPenCore method of the ballPen to obtain a PenCore object, which is an instance of a subclass of PenCore.

Line 2 of the Main function Ball ballPen = new BlueBallPen(); We created a new BlueBallPen and used upcasting (upcasting is to directly assign the subclass object to the parent class reference without mandatory conversion. Using the upcasting can call the parent class type All members of the subclass type cannot call the unique members of the subclass type, and the final operation effect depends on the specific implementation of the subclass), use the variable of the parent class type to refer to the subclass object, so as to dynamically select which specific implementation class to use at runtime, and also It is the dynamic binding mechanism.
At the same time, subclass initialization and inheritance of the parent class need to call the constructor of the parent class, and there is a default constructor in the parent class BallPen.

  BallPen() {
    
    
    System.out.println("生产了一只装有"+getPenCore().color+"笔芯的圆珠笔");
   }

So when creating a BlueBallPen object, it will call the constructor of its parent class BallPen, and the BallPen will call the getPenCore() method to get the BluePenCore object. And the BluePenCore constructor sets the color field to "blue". When the BallPen constructor prints a message, it accesses the PenCore object returned by getPenCore(), that is, the color field of the BluePenCore object, which has been set to "blue", and it will output "A pen with a blue refill has been produced. ballpoint pen".
The next step is to output the writeWord method rewritten by BluePenCore to write the blue word "Nice to meet you".
insert image description here
You can use the debug mode to see the execution order of the code.
Well now I don't want to use blue ballpoint pens, I want to use black ones. you can write like this

public class BlackBallPen extends BallPen{
    
    
    public PenCore getPenCore(){
    
    
       return new BlackPenCore();
    }
}
public class BlackPenCore extends PenCore{
    
    
    BlackPenCore(){
    
    
      color="黑色";
    }
    public void writeWord(String s){
    
    
       System.out.println("写出"+color+"的字:"+s);
    }
}

insert image description here

The console will output a ballpoint pen with a black refill to write a sentence: nice to meet you.
So, the BallPen class is like a factory responsible for producing ballpoint pens, PenCore represents an abstract product (that is, an ink cartridge), and BluePenCore is a concrete embodiment of this product, and you can provide whatever color you need. This allows the production of different types of pens with different cartridges, while keeping client code separate from specific pen and cartridge implementations. This is the simple factory design pattern.

The above is the content of today, if you want to read the next article, please click to follow!

Guess you like

Origin blog.csdn.net/m0_56653797/article/details/129652424