[英]Regarding constructors Vs Static Factory Methods
我正在查詢是否在類中有如下構造函數。
class A
{
A{}
}
現在構造函數的替代方法是什么,我采用的是靜態工廠方法
class A
{
public staic A getinstance()
{
return new A();
}
}
在以上根據分析的方法中,它將返回不可變的對象,但是我對此分析表示懷疑,因為該對象可以通過靜態工廠方法返回並可以在以后進行更改,如何使其完全不可變..! 請指教..!!
不變性與創建對象的方式無關。 即從構造函數或工廠方法 。
JDK使用Collections.unmodifiableCollection
和相關方法提供了一些用於Collections的方法。
您也可以將其合並到您的設計中,這在使用並發應用程序時非常有用。
此處提供了完整的策略: http : //docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
替代構造函數: static factory methods
不能替代構造函數。 但是您可以進行等效於構造函數的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();
}
}
->很好,此類不會返回不可變的對象。 要使類不可變,請將類設為final,將所有成員設為private和final,僅提供getter方法和參數化構造函數。 參見以下示例:
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.