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

策略模式打折 #139

Open
wants to merge 2 commits 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 PriceCalculator {
@Override
public int discount(int price,User user){
return (int) (price*0.95);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.hcsp.polymorphism;

public class DiscountStrategy {
public class DiscountStrategy extends PriceCalculator {
public int discount(int price, User user) {
throw new UnsupportedOperationException();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
package com.github.hcsp.polymorphism;

public class NoDiscountStrategy {}
public class NoDiscountStrategy extends PriceCalculator {
@Override
public int discount(int price, User user) {
return price;
}

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
package com.github.hcsp.polymorphism;

public class OnlyVipDiscountStrategy {}
public class OnlyVipDiscountStrategy extends PriceCalculator {
@Override
public int discount(int price,User user){
if(user.isVip()){
return (int) (price*0.95);
}else{
return price;
}
}

}
23 changes: 5 additions & 18 deletions src/main/java/com/github/hcsp/polymorphism/PriceCalculator.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,15 @@
package com.github.hcsp.polymorphism;

public class PriceCalculator {
public abstract class PriceCalculator {
// 使用策略模式重构这个方法,实现三个策略:
// NoDiscountStrategy 不打折
// Discount95Strategy 全场95折
// 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 int calculatePrice(DiscountStrategy strategy, int price, User user) {
return strategy.discount(price,user);

}

}