简体   繁体   中英

Regarding constructors Vs Static Factory Methods

I was having a query that is if we have constructor in the class as below..

class A
{
  A{}

}

Now what is the alternative to the constructors , I have gone for the approach that is static factory methods

class A
{
  public staic A getinstance()
  {
return new A();
}

}

In the above approch as per the analysis it will return immutable object but I have doubt on this analysis as the object that can be return with static factory method and can later be changed on , How to make it completely immutable..!! please advise..!!

Immutability is not related to the manner you create your objects. ie from constructors or factory methods .

JDK provides some ways to do this for Collections, using Collections.unmodifiableCollection and related methods.

You can also incorporate it into your design, which becomes useful when working with concurrent applications.

A complete strategy for this is given here : http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html

alternative to the constructors : static factory methods are not alternative to constructors. But you can have block intialization which is equivalent to the constructors, but disadvantage is you can not pass arguments to it like :

class B {
  private int i;
  //intialization block, can not pass arguments like constructor
  {
    i=2;
  }
  //getter and setters
}

.

class A
{
  public staic A getinstance()
  {
    return new A();
  }

}

--> well this class will not return immutable object. To make class immutable, make class final, all members private and final, provide only getter methods and parameterised constructor. See below example :

final class A
{
   final private int b;
  public A(int b)
  {
    this.b = b;
  }

   public int getB() {
       return this.b;
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM