This repository was archived by the owner on Dec 30, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 7 files changed +84
-0
lines changed
src/designpattern/strategy Expand file tree Collapse file tree 7 files changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ package designpattern .strategy ;
2+
3+ public class Book {
4+ private double amount ;
5+
6+ public Book (double amount ) {
7+ this .amount = amount ;
8+ }
9+
10+ public double getAmount () {
11+ return this .amount ;
12+ }
13+
14+ public void setAmount (double amount ) {
15+ this .amount = amount ;
16+ }
17+ }
Original file line number Diff line number Diff line change 1+ package designpattern .strategy ;
2+
3+ public class DiscountStrategy implements Strategy {
4+ @ Override
5+ public void discount (Book book ) {
6+ double amount = book .getAmount ();
7+ book .setAmount (amount * 0.9 );
8+ }
9+ }
Original file line number Diff line number Diff line change 1+ package designpattern .strategy ;
2+
3+
4+ public class Main {
5+ public static void main (String [] args ) {
6+ Book comic = new Book (500 );
7+ Book technicalBook = new Book (2500 );
8+
9+ Strategy discountStrategy = new DiscountStrategy ();
10+ Strategy specialDiscountStrategy = new SpecialDiscountStrategy ();
11+
12+ Shop shop = new Shop (discountStrategy );
13+ shop .shell (comic );
14+ System .out .println ("割引後金額は、" + comic .getAmount () + "円" );
15+
16+ shop .setStrategy (specialDiscountStrategy );
17+ shop .shell (technicalBook );
18+ System .out .println ("割引後金額は、" + technicalBook .getAmount () + "円" );
19+ }
20+ }
Original file line number Diff line number Diff line change 1+ package designpattern .strategy ;
2+
3+ public class Shop {
4+ private Strategy strategy ;
5+
6+ public Shop (Strategy strategy ) {
7+ this .strategy = strategy ;
8+ }
9+
10+ public void setStrategy (Strategy strategy ) {
11+ this .strategy = strategy ;
12+ }
13+
14+ public void shell (Book book ) {
15+ this .strategy .discount (book );
16+ }
17+ }
Original file line number Diff line number Diff line change 1+ package designpattern .strategy ;
2+
3+ public class SpecialDiscountStrategy implements Strategy {
4+ @ Override
5+ public void discount (Book book ) {
6+ double amount = book .getAmount ();
7+ book .setAmount (amount * 0.7 );
8+ }
9+ }
Original file line number Diff line number Diff line change 1+ package designpattern .strategy ;
2+
3+ public interface Strategy {
4+ void discount (Book book );
5+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * Strategy パターン
3+ *
4+ * - 処理アルゴリズムを簡単に切り替えられるようにする
5+ * - Command パターンと同様のことができる
6+ */
7+ package designpattern .strategy ;
You can’t perform that action at this time.
0 commit comments