Strategy Pattern

Strategy Pattern Java Design Pattern Tutorial
Strategy Pattern: defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Example

Car.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.strategypattern.example;
 
public abstract class Car {
 EngineType engineType;
 BodyStyle bodyStyle;
 
 public void setEngineType(EngineType engineType) {
  this.engineType = engineType;
 }
 
 public void setBodyStyle(BodyStyle bodyStyle) {
  this.bodyStyle = bodyStyle;
 }
 
 public void drive() {
  engineType.engine();
  bodyStyle.body();
 }
 
}
EngineType.java
1
2
3
4
5
package com.strategypattern.example;
 
public interface EngineType {
 public void engine();
}
BodyStyle.java
1
2
3
4
5
package com.strategypattern.example;
 
public interface BodyStyle {
 public void body();
}
GasolineEngine.java
1
2
3
4
5
6
7
8
9
10
package com.strategypattern.example;
 
public class GasolineEngine implements EngineType{
 
 @Override
 public void engine() {
  System.out.println("Engine Type : Gasoline");
 }
 
}
DieselEngine.java
1
2
3
4
5
6
7
8
9
10
package com.strategypattern.example;
 
public class DieselEngine implements EngineType{
 
 @Override
 public void engine() {
  System.out.println("Engine Type : Diesel");
 }
 
}
CompactSedan.java
1
2
3
4
5
6
7
8
9
10
package com.strategypattern.example;
 
public class CompactSedan implements BodyStyle{
 
 @Override
 public void body() {
  System.out.println("Body Style : Compact Sedan");
 }
 
}
Hatchback.java
1
2
3
4
5
6
7
8
9
10
package com.strategypattern.example;
 
public class Hatchback implements BodyStyle{
 
 @Override
 public void body() {
  System.out.println("Body Style : Hatchback");
 }
 
}
HondaCivic.java
1
2
3
4
5
6
7
8
9
10
11
12
package com.strategypattern.example;
 
public class HondaCivic extends Car {
 public HondaCivic(){
  engineType = new GasolineEngine();
  bodyStyle = new CompactSedan();
 }
  
 public String toString(){
  return "Honda Civic";
 }
}
SuzukiSwift.java
1
2
3
4
5
6
7
8
9
10
11
12
package com.strategypattern.example;
 
public class SuzukiSwift extends Car {
 public SuzukiSwift(){
  engineType = new GasolineEngine();
  bodyStyle = new Hatchback();
 }
  
 public String toString(){
  return "Suzuki Swift";
 }
}
CarTestDrive.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.strategypattern.example;
 
public class CarTestDrive {
 public static void main(String[] args) {
  Car suzukiSwift = new SuzukiSwift();
  System.out.println("You are Driving " + suzukiSwift);
  suzukiSwift.drive();
   
  Car hondaCivic = new HondaCivic();
  System.out.println("You are Driving " + hondaCivic);
  hondaCivic.drive();
  //Hand Civic is giving low mileage on Gasoline,so Engine Type changed to Diesel
  hondaCivic.setEngineType(new DieselEngine());
  hondaCivic.drive();
  
 }
}



Home

No comments:

Post a Comment