[英]Java Structured Method Chaining
關於使用 java 中的對象的一些問題。 假設我有以下 class。
public class Example {
private String ex1 = new String();
private String ex2 = new String();
private int varOne;
public Example logicOne(/*Input variables*/) {
// Do logic
return this;
}
public Example logicTwo(/*Input variables*/) {
// Do logic
return this;
}
public int subLogicOne(/*Input variables*/) {
return varOne;
}
public int subLogicTwo(/*Input variables*/) {
return varTwo;
}
public int subLogicThree(/*Input variables*/) {
return varThree;
}
}
我知道將方法類型設置為 class 名稱並使用return 這將允許我在調用 class object 時鏈接方法。
Example obj = new Example;
obj.logicOne("inputOne").logicTwo("inputTwo");
但是我將如何限制可以調用哪些方法呢? 例如,使logicOne和logicTwo互斥,並將subLogicOne限制為logicOne ,將subLogicTwo限制為logicTwo ,並且subLogicThree像這樣在它們之間共享。
Example obj = new Example;
obj.logicOne("inputOne").subLogicOne("subInputOne");
obj.logicTwo("inputTwo").subLogicTwo("subInputTwo");
obj.logicOne("inputOne").subLogicThree("subInputThree");
obj.logicTwo("inputTwo").subLogicThree("subInputThree");
您可以使用接口來划分方法。
// you can probably come up with better names, taking your real situation into account
interface Logicable {
SubLogicOneAble logicOne(/*same input variables as logicOne*/);
SubLogicTwoAble logicTwo(/*same input variables as logicTwo*/);
}
interface SubLogicThreeAble {
int subLogicThree(/*same input variables as subLogicThree*/);
}
interface SubLogicOneAble extends SubLogicThreeAble {
int subLogicOne(/*same input variables as subLogicOne*/);
}
interface SubLogicTwoAble extends SubLogicThreeAble {
int subLogicTwo(/*same input variables as subLogicTwo*/);
}
然后,您可以讓調用者通過返回Logicable
的工廠方法創建Example
的實例,而不是new Example()
。 這樣,調用者可以調用的第一個方法只有logicOne
和logicTwo
,當然,除非它們顯式轉換為Example
。
class Example implements SubLogicOneAble, SubLogicTwoAble, Logicable {
private Example() {}
// could also consider putting this in Logicable and calling it newLogicable (?)
public static Logicable newExample() {
return new Example();
}
Example.newExample().subLogicOne() // compiler error
另請注意,我將logicOne
和logicTwo
更改為分別返回SubLogicOneAble
和SubLogicTwoAble
。 這是為了確保調用者只能在這些方法的返回值上調用某些方法(同樣,除非它們顯式轉換)。 Example
中的簽名應更改為與接口一致:
public SubLogicOneAble logicOne (/*Input variables*/){
// Do logic
return this;
}
public SubLogicTwoAble logicTwo (/*Input variables*/){
// Do logic
return this;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.