Skip to content

Commit

Permalink
Add1 (#140)
Browse files Browse the repository at this point in the history
Add1 (#140)
  • Loading branch information
XinleZhou authored Mar 23, 2020
1 parent 34a50f0 commit c1d573f
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
package com.github.hcsp.polymorphism;

public class Discount95Strategy {}
public class Discount95Strategy extends DiscountStrategy{
@Override
public int discount(int price, User user) {
return (int)(price * 0.95);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
package com.github.hcsp.polymorphism;

public class NoDiscountStrategy {}
public class NoDiscountStrategy extends DiscountStrategy{
@Override
public int discount(int price, User user) {
return price;
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
package com.github.hcsp.polymorphism;

public class OnlyVipDiscountStrategy {}
public class OnlyVipDiscountStrategy extends DiscountStrategy{
@Override
public int discount(int price, User user) {
return user.isVip() ? (int) (price * 0.95) : price;
}
}
22 changes: 4 additions & 18 deletions src/main/java/com/github/hcsp/polymorphism/PriceCalculator.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,8 @@ public class PriceCalculator {
// OnlyVipDiscountStrategy 只有VIP打95折,其他人保持原价
// 重构后的方法签名:
// public static int calculatePrice(DiscountStrategy strategy, int price, User user)
public static int calculatePrice(String discountStrategy, int price, User user) {
switch (discountStrategy) {
case "NoDiscount":
return price;
case "Discount95":
return (int) (price * 0.95);
case "OnlyVip":
{
if (user.isVip()) {
return (int) (price * 0.95);
} else {
return price;
}
}
default:
throw new IllegalStateException("Should not be here!");
}
public static int calculatePrice(DiscountStrategy strategy, int price, User user) {
return strategy.discount(price, user);
}
}

}

0 comments on commit c1d573f

Please sign in to comment.