基本概念:
抽象表示的是接口、抽象类。细节就是具体的实现类。接口或抽象类的价值在于指定规范。
一个反面例子:
public class DependencyInversion { public static void main(String[] args) { People people = new People(); people.receive(new Email()); } } class Email { public String getInfo(){ return "这是电子邮件信息"; } } class People { public void receive(Email email){ System.out.println(email.getInfo()); } }
信息不一定是邮件啊,也可能是qq或者微信,这个时候时候就要新增类,People也要新增其他的接收方法。所以改成以下方式:
public class DependencyInversion { public static void main(String[] args) { People people = new People(); people.receive(new Email()); people.receive(new WeiXin()); } } interface IMessage{ public String getInfo(); } class Email implements IMessage{ public String getInfo(){ return "这是电子邮件信息"; } } class WeiXin implements IMessage{ public String getInfo() { return "这是微信信息"; } } class People { public void receive(IMessage iMessage){ System.out.println(iMessage.getInfo()); } }
1.通过接口:
2.通过构造器
3、通过setter方法:
总结: