我正在實施類似於nand2tetris項目的東西,除非我寫我所有的代碼在Java中不使用HDL,我自己寫測試。 對於問題ilustration: 我已經實現了nand邏輯門,它將依賴於OR,AND,XOR和NOT邏輯門。我應該避免迪,當類是可測試的黑盒測試
我有這兩種方法的疑問:
1)DI方法
public interface Nand {
int nand(int a, int b);
}
public class NandImpl implements Nand {
public int nand(int a, int b) {
return a * b == 0 ? 1 : 0;
}
}
public interface And {
int and(int a, int b);
}
public class AndImpl implements And {
Nand nand;
public AndImpl(Nand nand) {
this.nand = nand;
}
public int and(int a, int b) {
return nand.nand(nand.nand(a, b), nand.nand(a, b));
}
}
2)方法,而不DI
public class NandImpl {
static NandImpl singleton = null;
protected NandImpl() {
}
public static NandImpl getInstance() {
if(singleton == null) {
singleton = new NandImpl();
}
return singleton;
}
public int nand(int a, int b) {
return a * b == 0 ? 1 : 0;
}
}
public class AndImpl {
static AndImpl singleton = null;
NandImpl nand;
protected AndImpl() {
nand = NandImpl.getInstance();
}
public static AndImpl getInstance() {
if(singleton == null) {
singleton = new AndImpl();
}
return singleton;
}
public int and(int a, int b) {
return nand.nand(nand.nand(a, b), nand.nand(a, b));
}
}
我開始用的aproach下1),但我現在有一種懷疑,因爲我總是需要在測試中存根依賴,以便實現某種程度上似乎對我而言不正確的實現。 另外我在這裏看不到任何優勢,因爲我可以完全測試AND,OR,NOT和XOR與真值表的實現。
我應該選擇哪種方式?