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
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
package com.strategypattern.example; public interface EngineType { public void engine(); }
BodyStyle.java
package com.strategypattern.example; public interface BodyStyle { public void body(); }
GasolineEngine.java
package com.strategypattern.example; public class GasolineEngine implements EngineType{ @Override public void engine() { System.out.println("Engine Type : Gasoline"); } }
DieselEngine.java
package com.strategypattern.example; public class DieselEngine implements EngineType{ @Override public void engine() { System.out.println("Engine Type : Diesel"); } }
CompactSedan.java
package com.strategypattern.example; public class CompactSedan implements BodyStyle{ @Override public void body() { System.out.println("Body Style : Compact Sedan"); } }
Hatchback.java
package com.strategypattern.example; public class Hatchback implements BodyStyle{ @Override public void body() { System.out.println("Body Style : Hatchback"); } }
HondaCivic.java
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
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
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