我正在学习java并开始尝试以正确的方式做事......
我不知道标题是否正确,如果不清楚,请告诉我,英语不是我的母语。 我有太多的代码发布它。所以我做了这个"简化"证据的版本我怀疑。我认为它更清楚。如果还不够清楚,请告诉我。
这是我解决方案的方案:
public class Test2 {
public static void test (String args[]){
A a = new A();
//... filling the A,B,C data..
//... done...
//.. now the cake:
public String newD = "C=45,D=67,more info...."; // 45 is the C id, 67 is the D id.
D dude = new D(newD);
// so i need to put this friend in the C object...
a.addSomeDude(dude); // looks easy...
}
}
class A{ // I have 3 B's in my collection = B_1, B_2, B_3. And i can have more...
private List<B> Blist;
private String id;
// blah blah
public void addSomeDude(D dude){ //... ok, i have some problems... i don't know where to put this dude
String Bid = SaveTheday.whoGoesWhere(dude.getId()); //oh! you save the day SavetheDay, what a suitable name!
for(B bDude : Blist)
if(bDude.getId() ==Bid ){
bDude.addSomeDude(dude);
}
}
//some things...
}
class B{ // I have some C's in my collections...
private List<C> Clist;
private String id;
//blah blah blah
public void addSomeDude(D dude){ //... i know where to put this dude, i just get the C id from the dude...
for(C cGuy : Clist)
if(dude.getCid() == cGuy.getId()){
cGuy.addSomeDude(dude);
}
}
}
class C{ // I i have some D dudes...
private List<D> Dlist;
private String id;
//yes, more things...
public void addSomeDude(D dude){
D objectDude = new D(dude.getCId());
Dlist.add(objectDude);
}
}
class D{
private String id;
private String cId;
//...some things and getters
}
class SaveTheday{
//...well, maybe i can do the job...
public static String whoGoesWhere(String id){
String [] B_1 = {"1","2","3","4","5","6"}; // these are C ids...
String [] B_2 = {"11","22","33","44","55"};
String [] B_3 = {"12","45","55","66","77"};
for( String i : B_1)
if (i.equals(id))
return "B_1";
for( String i : B_2)
if (i.equals(id))
return "B_2";
for( String i : B_3)
if (i.equals(id))
return "B_3";
return null;
}
}
这最终有效,但我开始认为这是一个非常不友好的OO原则解决方案。为什么呢?
那么,你们能告诉我我失踪的是什么吗?有一些我没见过的模式? 我希望表达自己是对的,如果没有,请告诉我添加更多细节。
答案 0 :(得分:0)
只是一般性说明:
String [] B_1 = {"1","2","3","4","5","6"};
不要认为在函数体中对这些指令进行硬编码是一个好主意。宁愿宣布为私人类成员。不知道Java编译器是否优化了这样的思考,但是每次调用&#34; whoGoesWhere&#34;
时,创建新数组都没有意义。我不会在你的情况下使用列表。如果您需要搜索特定ID(https://docs.oracle.com/javase/7/docs/api/java/util/Map.html)
,地图会更加高效你的问题:
是的,它不是完美的OO编程。你违反了责任。应该能够生成D的新位置的唯一一个是D.我永远不会创建一个方法来生成有关另一个对象的信息。
我会将D的ID传递给A作为方法参数。像&#34; public void addSomeDude(D dude,String insertInThisB)&#34;。
最好的地方&#34; whoGoesWhere&#34;将在D.更好:字符串Id_of_B到D的构造函数。
要将D添加到A,我会创建一个新方法&#34; addToA(A a)&#34;在D.和&#34; addToA&#34;电话&#34; a.addSomeDude(this,ID_of_my_B)&#34;。
编辑: 你的问题1和2非常棘手。如果你添加一个未知的B或C,会发生什么? 答案取决于新信息的来源。你可以扩展&#34; whoGoesWhere&#34;像一个更大的数据库&#34;它将D映射到D的路径,并允许您更新这些信息。 或者你说:如果你给我一个B和C id,你只能创建一个D来添加这个D.
EDIT2: 我也会传递C-id作为&#34; addSomeDude&#34;的参数。然后传递C-id作为&#34; addSomeDude&#34;的参数。 B. 就我个人而言,我认为这比使用Getters要好得多,也不过是OO。