Skip to content

Instantly share code, notes, and snippets.

@rohanjai777
Created November 8, 2022 21:19
Show Gist options
  • Save rohanjai777/5bb7451bcd9295fa04824df4760dd955 to your computer and use it in GitHub Desktop.
Save rohanjai777/5bb7451bcd9295fa04824df4760dd955 to your computer and use it in GitHub Desktop.
import java.util.*;
enum TransportMode{
CAR,
BIKE,
WALK
}
//-----------------------------------------
interface PathStrategy{
public void calculatePath(String from, String to);
}
class CarPathStrategy implements PathStrategy{
public void calculatePath(String from, String to){
System.out.println("Finding path by car");
}
}
class BikePathStrategy implements PathStrategy{
public void calculatePath(String from, String to){
System.out.println("Finding path by bike");
}
}
class WalkPathStrategy implements PathStrategy{
public void calculatePath(String from, String to){
System.out.println("Finding path by Walk");
}
}
//-----------------------------------------
class PathRegistry{ //registry for storing objects
Map<TransportMode, PathStrategy> paths = new HashMap<>();
public void register(TransportMode mode, PathStrategy pathStrategy){
paths.put(mode,pathStrategy);
}
public PathStrategy getRegister(TransportMode mode){
return paths.get(mode);
}
}
//----------------------------------------
class GoogleMaps{ //made for calling choosen registory mode
//get the registry object
PathRegistry pathRegistry;
GoogleMaps(PathRegistry pathRegistry){
this.pathRegistry = pathRegistry;
}
public void findPath(String from, String to, TransportMode mode){ //called calculatePath of choosen mode.
pathRegistry.getRegister(mode).calculatePath(from,to);
}
}
//---------------------------------------
public class Client{
public static void main(String[] args){
//make original object
PathStrategy car = new CarPathStrategy();
PathStrategy bike = new BikePathStrategy();
PathStrategy walk = new WalkPathStrategy();
//add the in registry
PathRegistry pathRegistry = new PathRegistry();
pathRegistry.register(TransportMode.CAR, car);
pathRegistry.register(TransportMode.BIKE, bike);
pathRegistry.register(TransportMode.WALK, walk);
//Use google map class to get the path from one point to another using a mode;
GoogleMaps googleMap = new GoogleMaps(pathRegistry);
googleMap.findPath("Alwar","Delhi",TransportMode.WALK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment