5、测试类
package dependenceinversion; public class Main { public static void main(String[] args) { Customer customer = new Customer(new FridgeGood()); customer.buy(); Customer customer2 = new Customer(new TelevisionGood()); customer2.buy(); } }
执行结果 :
购买冰箱 购买电视
五、依赖倒置原则代码示例 ( 推荐示例 | 使用 Setter 方法注入 IGood 实现类 )
1、顾客类
使用 Setter 方法注入 IGood 实现类 ;
package dependenceinversion; public class Customer { private IGood iGood; public void setiGood(IGood iGood) { this.iGood = iGood; } public void buy() { this.iGood.buy(); } }
2、商品接口
package dependenceinversion; /** * 商品接口 */ public interface IGood { /** * 购买商品 */ void buy(); }
3、冰箱商品
package dependenceinversion; /** * 冰箱商品 */ public class FridgeGood implements IGood { @Override public void buy() { System.out.println("购买冰箱"); } }
4、电视商品
package dependenceinversion; /** * 电视商品 */ public class TelevisionGood implements IGood { @Override public void buy() { System.out.println("购买电视"); } }
5、测试类
package dependenceinversion; public class Main { public static void main(String[] args) { Customer customer = new Customer(); customer.setiGood(new FridgeGood()); customer.buy(); customer.setiGood(new TelevisionGood()); customer.buy(); } }
执行结果 :
购买冰箱 购买电视