Advertisement
Guest User

Untitled

a guest
Oct 12th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. public class InterfaceBlogExample{
  2.  
  3. public static void main(String[] args){
  4. // Creating hard coded wheels
  5. DefaultWheels hardCodedWheels = new DefaultWheels();
  6. // Injecting hard coded wheels
  7. Car nonMantainableCar = new Car(hardCodedWheels);
  8. nonMantainableCar.roll();
  9. //Rolling
  10.  
  11. //Using interface
  12. Wheels defaultWheels = new DefaultWheelsImpl();
  13. Wheels AwesomeWheelsImpl = new AwesomeWheelsImpl();
  14. // New car with default wheels
  15. MaintainableCar maintainableCar = new MaintainableCar(defaultWheels);
  16. maintainableCar.roll();
  17. // Went to the dealer, and decided to change wheels
  18. maintainableCar.changeWheels(AwesomeWheelsImpl);
  19.  
  20. maintainableCar.roll();
  21. //Car still rolling
  22.  
  23. }
  24. }
  25.  
  26. class DefaultWheels{
  27.  
  28.  
  29.  
  30. public void roll(){
  31. System.out.println("Let's roll with hard coded wheels!!");
  32. }
  33.  
  34. }
  35.  
  36.  
  37. // This is a non maintainable car
  38. class Car{
  39.  
  40. // This are the default wheels
  41. private DefaultWheels carWheel;
  42.  
  43. Car(DefaultWheels wheels){
  44. carWheel = wheels;
  45. }
  46.  
  47. void roll(){
  48. carWheel.roll();
  49. }
  50.  
  51. // at this point, your car is hard coded to use just the default wheels.
  52. // putting other wheels on it will not work (obviously).
  53. }
  54.  
  55.  
  56. class MaintainableCar{
  57.  
  58. Wheels wheels;
  59.  
  60. MaintainableCar(){}
  61.  
  62. MaintainableCar(Wheels wheels){
  63. this.wheels = wheels;
  64. }
  65.  
  66. void roll(){
  67. wheels.roll();
  68. }
  69.  
  70. void changeWheels(Wheels newWheels){
  71. this.wheels = newWheels;
  72. }
  73.  
  74. }
  75.  
  76. interface Wheels{
  77.  
  78. void roll();
  79.  
  80. }
  81.  
  82. // The same default wheels but now, implementing the Wheels interface
  83. class DefaultWheelsImpl implements Wheels{
  84.  
  85.  
  86. @Override
  87. public void roll(){
  88. System.out.println("Let's roll :/ with defult wheels!!");
  89. }
  90.  
  91. }
  92.  
  93. class AwesomeWheelsImpl implements Wheels{
  94.  
  95. @Override
  96. public void roll(){
  97. System.out.println("Let's ROOOLLL with Awesome Wheels!!");
  98. }
  99.  
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement