SOLID Principles: Dependency Inversion Principle (DIP)

public class Email{public void sendMail(){// send mail 
}
}
public class Notification{private Email _email;public Notification(){_email = new Email();
}
public void promotionalNotification(){_email.sendMail();
}
}

1. create an interface.

public interface Messeneger{void sendMessage();
}

2. create classes implements this interface.

public class Email implements Messenger{void sendMessage(){// send email
}
}
public class SMS implements Messenaer{void sendMessage(){// send SMS
}
}

3. build class Notification which has Messenger property.

public class Notification{private Messenger _messenger;public Notification(){_messenger = new Email();
}
public void promotionalNotification(){_messeager.sendMessage();
}
}

1. Constructor injection:

public class Notification{private Messenger _messenger;public Notification(Messenger messenger){_messenger= messenger;
}
public void promotionalNotification(){_messenger.sendMessage();
}
}

2. Property injection:

public class Notification{private Messenger messenger;public void setMessenger(Messenger messenger) {
this.messenger= messenger;
}
public void promotionalNotification(){_messenger.sendMessage();
}
}

3. Method injection:

public class Notification{public void promotionalNotification(Messenger messenger){messenger.sendMessage();
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store