Java – object instantiation using factory methods

I am currently taking CS2 course (data structure), in which Java is the language used. I am interested in comparing and comparing object instances using traditional constructor methods Factory method Does one person represent a higher degree of computational elegance than another? Does the factory method handle parameters in a way similar to a parameterized constructor? For example:

public class Tester
{
    private String name;
    private int age;

    // Parameterized constructor  
    public Tester(String myName,int myAge)
    {
        this.name = myName;
        this.age = myAge; 
    }
}

In essence, I am curious about how to write an equivalent factory method and the potential benefits of doing so

thank you,

~ Caitlin

Solution

Factory methods are good because they can return references to objects that are not necessarily instances of this class It can return the class, subtype, or even null, and can usually do anything in the way they want Therefore, you can move the logic of selecting types into your own code You can return an existing instance in the appropriate location to save heap space, etc

Another basic pseudo example is integer Forvalue(), which can implement integers, so the same immutable object will not be recreated for no reason See also executors newXxxThreadPool().

A basic example:

public class Tester
{
    private String name;
    private int age;

    // Parameterized constructor  
    private Tester(String myName,int myAge)
    {
        this.name = myName;
        this.age = myAge; 
    }
    public static Tester getTester(String mn,int ag){
        if(age>0){return new Tester(mn,ag);}
        else if(age>80){return new OldPersonThatExtendsTester(mn,ag);} 
        //we'd need a public or otherwise accessible constructor above. It's a subtype!
        else {return null;} //yes,this is possible
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>