[英]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. JDK使用
Collections.unmodifiableCollection
和相关方法提供了一些用于Collections的方法。
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 此处提供了完整的策略: http : //docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
alternative to the constructors : static factory methods
are not alternative to constructors. 替代构造函数:
static factory methods
不能替代构造函数。 But you can have block intialization
which is equivalent to the constructors, but disadvantage is you can not pass arguments to it like : 但是您可以进行等效于构造函数的
block intialization
,但是缺点是您不能像这样传递参数:
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.
要使类不可变,请将类设为final,将所有成员设为private和final,仅提供getter方法和参数化构造函数。 See below example :
参见以下示例:
final class A
{
final private int b;
public A(int b)
{
this.b = b;
}
public int getB() {
return this.b;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.