post-images/static-factory-method-vs-constructor/cover.jpg

Static Factory Method vs Constructor

Greetings, it's me again and a new topic 🤗. In this article, I will talk about Static Factory Methods instead of Constructors, which is the first part of our book, Creating and Destroying Objects. If you have questions such as 'Which book, which chapter?'. I invite you to take a look at my first post.

What is this constructor? What about the static factory method? Is what we call the factory, the factory pattern? If you have questions based on attributing meaning to the words in this type of subject, let me answer them first. First of all, the static factory here and the factory method, which is the design pattern, have nothing to do with it. Actually, by the way, let's remember the factory method pattern. Let's refresh our knowledge.

Factory Pattern (Factory Pattern); It is the structure responsible for the production of objects that derive from the same abstract class or interface. It is a design model that you can use when you want to add a new feature to the application that you have already developed, without making the existing structure difficult.

Well, nice. What is this static factory? Here, I'm going to talk about Static Factory, which is a nice feature that we didn't realize when you and I were new to programming at the time.

Remember when you first got into object-oriented programming. First, they told you about the basic building block, the class. You know, you add the common values you need into it. You added descriptive features such as age, width, height, weight, color, volume, and actions such as draw, paint, measure, search. You used getter(), setter(), and constructors while defining them. This knowledge taught to you at the entry-level starts to be insufficient when things get more complicated. It may even hinder you.

First of all, I would like to list the reasons that are the title of our article here.

Why static factories instead of constructors? Namely:

While constructors take the name of the class directly, you can enrich the readability of the code with more meaningful naming in static factories.

Let me have a class created with Constructor:

public class Egg {  
   public Egg(boolean withSausage) {  
      //make an egg
   }  
}

// I can't understand what the value of 'true' is without entering the egg class  
Egg egg = new Egg(true);

Let's see how it works with a static factory:

public class Egg {
    public static Egg eggWithSausage() {
        //make sausage egg
    }
    public static Yumurta eggWithCheese() {
        //make cheesy eggs
    }
}

// As you can see, you read the code better. Enjoy your meal. 
Egg egg = Egg.eggWithSausage();
Egg egg = Egg.eggWithCheese();

While you can cause heavy loads on the system by creating a new class every time with constructors, you can create a class with the static factory method and multiply this class and even keep it under control. Singleton Class ideal for generating 😉

EnumSet does not use a public constructor, instead, it is generated with a static factory method. If the Enum type has 64 elements or less, the RegularEnumSet is ruled by returning, if it has 65 or more elements, the JumboEnumSet object is returned.

public class Pizza {
    private boolean sliced;

    public Pizza(boolean sliced) {
        this.sliced = sliced;
    }

    @Override
    public String toString() {
        return "Pizza{sliced=" + sliced + '}';
    }
}

public class PizzaFactory {
    private static PizzaFactory pizzaFactoryInstance;

    private String pizzaSize;
    private boolean hasPepperoni;
    private boolean hasCheese;

    // singleton object control over the instance with static factory model  
    public static PizzaFactory getInstance(String pizzaSize, boolean hasPepperoni, boolean hasCheese) {
        PizzaFactory pizzaFactory = new PizzaFactory();

        if (pizzaFactoryInstance != null) {
            pizzaFactory = pizzaFactoryInstance;
        } else {
            pizzaFactory.pizzaSize = pizzaSize;
            pizzaFactory.hasPepperoni = hasPepperoni;
            pizzaFactory.hasCheese = hasCheese;
            pizzaFactoryInstance = pizzaFactory;
        }

        return pizzaFactory;
    }

    public static String slicedPizza() {
        return "Sliced pizza.";
    }

    public static String unSlicedPizza() {
        return "Unsliced pizza.";
    }

    @Override  
    public String toString() {
        return "PizzaFactory{" +  
                "pizzaSize='" + pizzaSize + '\\'' +  
                ", hasPepperoni=" + hasPepperoni +  
                ", hasCheese=" + hasCheese +  
                '}';  
    }  
}

I will tell before I forget. I will be sharing the code pieces in the articles on my github account. You can give star if you like it 🤗

Adiós 🙋🏻‍♂️

JavaEffective JavaCreating and Destroying ObjectsStatic FactoryConstructorFactory PatternSingleton Class