编写用来获取数据的接口
public interface DataBase{
//改方法用来获取数据
public void getData();
}
编写具体负责获取数据的类
public class SqlDataBase1 implement DataBase{
//该方法1用来获取数据
public void getData(){
//以下是具体获取数据的代码
}
}
public class SqlDataBase2 implement DataBase{
//该方法2用来获取数据
public void getData(){
//以下是具体获取数据的代码
}
}
1.接口注入
1.1编写一个接口
public interface IBuiness{
public void createDI(DataBase);
}
1.2实现这个接口
public class Buiness implement IBuiness{
private DataBase db;
public void createDI(DataBase db){
this.db=db;
}
public void getData(){
db.getData();
}
}
1.3测试Test
public class TestBuiness{
private Buiness buiness=new Buiness();
public void getData(){
buiness.createDI(new SqlDataBase2());
buiness.getData();
}
}
2.Set注入
2.1编写业务逻辑类
public class Buiness{
private DataBase db;
public void setDataBase(DataBase db){
this.db=db;
}
public void getData(){
db.getData();
}
}
2.2测试Test
public class Test{
private Buiness buiness=new Buiness();
public void getData(){
buiness.setDataBase(new SqlDataBase1());
buiness.getData();
buiness.setDataBase(new SqlDataBase2());
buiness.getData();
}
}
3.构造注入
public class Buiness{
private DataBase db;
public Buiness(DataBase ab){
this.db=db;
}
public void getData(){
db.getData();
}
}
3.2测试Test
public void Test(){
private Buiness buiness;
public void getData(){
buiness=new Buiness(new SqlDataBase1());
buiness.getData();
}
}