Strategy Pattern 処理の切替
- 拠点報告( hubReport.showReport ) を
- 「東京拠点 → 大阪拠点」と順に出力する
- 内部処理
- 処理ロジックを
- 東京拠点の報告処理 → 大阪拠点の報告処理 としてみる
- 内部処理
src | +-- jp.ymatsukawa +-- Main.java | +-- report | + -- HubReportStrategy.java (interface) + -- HubReport.java + -- ReportType (enum) + -- TokyoReport.java + -- OsakaReport.java + -- Reporter.java (interface) + -- ReportCreator.java
jp.ymatsukawa/Main.java
package jp.ymatsukawa; import jp.ymatsukawa.report.HubReport; import jp.ymatsukawa.report.ReportType; public class Main { public static void main(String[] args) { HubReport hubReport; hubReport = new HubReport(ReportType.TOKYO); System.out.println(hubReport.showReport()); // this is Tokyo's report hubReport.changeStrategy(ReportType.OSAKA); System.out.println(hubReport.showReport()); // hello, this is ... Osaka's Report } }
jp.ymatsukawa/report/HubReportStrategy.java
package jp.ymatsukawa.report; public interface HubReportStrategy { public String showReport(); }
jp.ymatsukawa/report/HubReport.java
package jp.ymatsukawa.report; public class HubReport { private HubReportStrategy hubReportStrategy; public HubReport(ReportType reportType) { this.changeStrategy(reportType); } public void changeStrategy(ReportType reportType) { Reporter reporter = new ReportCreator(); this.hubReportStrategy = reporter.createHubReport(reportType); } public String showReport() { return this.hubReportStrategy.showReport(); } }
jp.ymatsukawa/report/ReportType.java
package jp.ymatsukawa.report; public enum ReportType { TOKYO, OSAKA; }
jp.ymatsukawa/report/TokyoHubReport.java
package jp.ymatsukawa.report; public class TokyoHubReport implements HubReportStrategy { @Override public String showReport() { return "this is Tokyo's report"; } }
jp.ymatsukawa/report/OsakaHubReport.java
package jp.ymatsukawa.report; public class OsakaHubReport implements HubReportStrategy { @Override public String showReport() { return "hello, this is ... Osaka's Report"; } }
jp.ymatsukawa/report/Reporter.java
package jp.ymatsukawa.report; public interface Reporter { public HubReportStrategy createHubReport(ReportType reportType); }
jp.ymatsukawa/report/ReportCreator.java
package jp.ymatsukawa.report; public class ReportCreator implements Reporter { protected ReportCreator() {} @Override public HubReportStrategy createHubReport(ReportType reportType) { switch(reportType) { case TOKYO: return new TokyoHubReport(); case OSAKA: return new OsakaHubReport(); default: throw new RuntimeException("Illegal hub passed"); } } }
technical reference from
thanks