anilchahal7

DI Example

Oct 23rd, 2020 (edited)
665
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public interface Engine {
  2. }
  3. public class SlowEngine implements Engine {
  4. }
  5. public class FastEngine implements Engine {
  6. }
  7. public class DieselEngine implements Engine {
  8. }
  9.  
  10. public class Car {
  11.     private DieselEngine engine;
  12. }
  13.  
  14. public class Car {
  15.     private Engine engine = new DieselEngine();
  16. }
  17.  
  18.  
  19. ---
  20. Tightly Coupled
  21. ---
  22.  
  23. DI by Constructor
  24.  
  25. public class Car {
  26.     private Engine engine;
  27.  
  28.     public Car(Engine engine) {
  29.         this.engine = engine;
  30.     }
  31. }
  32.  
  33. public class Test {
  34.     public static void main(String[] args) {
  35.         Car dieselCar = new Car(new DieselEngine());
  36.         Car slowCar = new Car(new SlowEngine());
  37.     }
  38. }
  39.  
  40. ----
  41. DI by Setter
  42. ----
  43. public class Car {
  44.     private Engine engine;
  45.     public void setEngine(Engine engine) {
  46.         this.engine = engine;
  47.     }
  48. }
  49.  
  50.  
  51. public class Test {
  52.     public static void main(String[] args) {
  53.         Car dieselCar = new Car();
  54.         dieselCar.setEngine(new DieselEngine());
  55.         Car slowCar = new Car();
  56.         slowCar.setEngine(new SlowEngine());
  57.     }
  58. }
  59.  
  60.  
RAW Paste Data