條目1 考慮使用靜態工廠方法代替構造方法

2022-09-12 18:09:05 字數 2555 閱讀 3317

body

body>*:first-child

body>*:last-child

p, blockquote, ul, ol, dl, table, pre

h1, h2, h3, h4, h5, h6

h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code

h1 h2

h3 h4

h5 h6

body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child

a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6

h1+p, h2+p, h3+p, h4+p, h5+p, h6+p

a a:hover

ul, ol

ul li>:first-child, ol li>:first-child, ul li ul:first-of-type, ol li ol:first-of-type, ul li ol:first-of-type, ol li ul:first-of-type

ul ul, ul ol, ol ol, ol ul

dl dl dt

dl dt:first-child

dl dt>:first-child

dl dt>:last-child

dl dd

dl dd>:first-child

dl dd>:last-child

pre, code, tt

code, tt

pre>code

pre

pre code, pre tt

kbd

blockquote

blockquote>:first-child

blockquote>:last-child

hr table th

table th, table td

table tr

table tr:nth-child(2n)

img

1.可以為它們取名可以讓客戶端更加方便使用。

integer.probableprime();

integer.natural();

可以分別用來表示獲取可能的質數和自然數,清晰易讀。

2.不用在每次在每次呼叫它時建立乙個新的物件。

a.預先構建好例項;

b.將構建好的例項儲存起來,進行重複利用。

3.它可以返回原型別的任何子型別的物件。
4.在建立引數化型別的例項時,它們使**變得更加簡潔。
1.類如果不含有共有的或者受保護的構造方法,它就不能被子類化。
2.它與其他靜態方法實質上沒有任何區別。

不過靜態方法有一些慣用的取名:

valueof

ofgetinstance

newinstance

gettype

newtype

客戶端:

public class test ;};}

};private static final provider custome_provider = new provider() ;};}

};public static void main(string args)

}

/**

* 註冊服務提供者

* @author tisakong

* 2015-5-4

*/public class services

public static void registerdefaultprovider(provider p)

public static service newinstance()

public static service newinstance(string name)

return p.newservice();

}}

/**

* 服務介面

* @author tisakong

* 2015-5-4

*/public inte***ce service

/**

* 服務提供商介面

* @author tisakong

* 2015-5-4

*/public inte***ce provider

1 考慮用靜態工廠方法代替構造器

1.考慮用靜態工廠方法代替構造器 例子 public static boolean valueof boolean b 使用靜態工廠替代構造器的優勢 1 他們有名稱 2 不必每次呼叫都產生新的物件 3 可以返回原返回型別任何子型別的物件 4 建立引數化型別例項的時候,使 更簡潔 缺點 1 類如果不含...

第1條 考慮用靜態工廠方法代替構造器

第1條 考慮用靜態工廠方法代替構造器 優點 1.靜態工廠方法有名稱 2.不必每次呼叫的時候都建立乙個新的物件 3.可以返回型別的任何子型別的物件 4.在建立引數化型別例項的時候,使 更加簡潔 缺點 1.類如果不含有共有的或者受保護的構造器,就不能被子類化 2.與其他的靜態方法實際上沒有任何區別 pu...

使用靜態工廠方法代替構造器

雖然他們類似,但是工廠模式需要建立乙個工廠物件,然後呼叫方法來建立例項,而靜態工廠方法可以寫在類中直接替代構造器,並可以通過類名直接呼叫,無需重新建立物件。構造器需要建立物件 靜態工廠方法有名字 對於構造器來說,根據入參的不同可以有多個構造器,但是這些構造器的名稱都是一樣的,使用者在呼叫時就會一頭霧...