A對象依賴B對象三種寫法
1.構(gòu)造函數(shù)傳遞依賴對象
//汽車
public interface ICar{
void run();
}
//司機(jī)(依賴汽車)
public interface IDriver{
void driver();
}
public Class Driver implements IDriver{
private ICar car;
public Driver(ICar car){
this.car = car;
}
}
2.Setter方法傳遞依賴對象
public interface IDriver{
}
public Class Driver implements IDriver{
private ICar car;
public void setCar(ICar car){
this.car = car;
}
public void drive(){
this.car.run();
}
}
3.接口聲明依賴對象
public interface IDriver{
void driver(ICar car);
}
public Class Driver implements IDriver{
public void drive(ICar car){
car.run();
}
}
前兩種在Spring容器的注入方式中有體現(xiàn);
第3種方式在日常編碼中經(jīng)常遇到返咱;
要講這三種方式在設(shè)計(jì)層面如何選擇胖齐,各自的適用場景翰苫,還需要更深入的理解摊欠。
記錄《設(shè)計(jì)模式之禪》--秦小波