Define a factory class that can return instances of different classes depending on the parameters. The created instances usually have a common parent class

In simple Factory mode, the methods used to create instances are usually static methods, so simple Factory mode is also called static Factory Method, which simply needs to pass in a correct parameter to get the desired object without knowing how to implement it

Test cases

Take, for example, a beverage processing plant

1. Create a drink interface (or abstract class)

public interface Drink {
    void production(a);
Copy the code

2. Realization of specific drinks (Cola, Sprite)

public class ColaDrinkProduction implements Drink{
    public void production(a) {
        System.out.println("Producing cola beverages.");
Copy the code
public class SpriteDrinkProduction implements Drink{
    public void production(a) {
        System.out.println("Making Sprite."); }}Copy the code

3. Beverage manufacturing Factories

public class DrinkProductionFactory {
    public static Drink productionDrink(String type){
        switch (type){
            case "cloa":
                return new ColaDrinkProduction();
                return newSpriteDrinkProduction(); }}}Copy the code

4. Factory call

What object is required to pass in the corresponding argument

Drink cloa = DrinkProductionFactory.productionDrink("cloa");
Copy the code

The characteristics of

It is a concrete class, a non-interface abstract class. There is an important call method (productionDrink), which is usually static, using if or switch to create the product and return it


I want to add a beverage. In addition to adding a beverage product class, I also need to modify the factory class method (adding branch conditions for ‘Case’) so that it is open not only for extension, but also for modification which violates the open-closed principle


That’s all for this article, hoping to help you