Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用了策略模式对代码进行重构,使业务与打折策略分离。 #74

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,11 @@
package com.github.hcsp.polymorphism;

public class OnlyVipDiscountStrategy {}
public class OnlyVipDiscountStrategy extends DiscountStrategy{
public int discount(int price, User user) {
if (user.isVip()) {
return (int) (price * 0.95);
} else {
return price;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ 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) {
public static int calculate(DiscountStrategy strategy, int price, User user) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public static int calculate(DiscountStrategy strategy, int price, User user) {
public static int calculatePrice(DiscountStrategy strategy, int price, User user) {

为什么改名字啊。。。

return strategy.discount(price, user);
/* switch (discountStrategy) {
case "NoDiscount":
return price;
case "Discount95":
Expand All @@ -23,6 +24,6 @@ public static int calculatePrice(String discountStrategy, int price, User user)
}
default:
throw new IllegalStateException("Should not be here!");
}
}*/
}
}