Skip to content

Commit c0f12f8

Browse files
策略模式
1 parent 4e8c7b7 commit c0f12f8

7 files changed

+108
-38
lines changed

.idea/workspace.xml

Lines changed: 35 additions & 38 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package strategy;
2+
3+
public class AdvancedMemberStrategy implements MemberStrategy {
4+
@Override
5+
public double calcPrice(double booksPrice) {
6+
System.out.println("高级会员的折扣为20%");
7+
return booksPrice* 0.8;
8+
}
9+
}

src/main/java/strategy/Client.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package strategy;
2+
3+
/**
4+
* 策略模式。针对不同的客户,采用不同的算法
5+
* 参考博客:http://www.cnblogs.com/java-my-life/archive/2012/05/10/2491891.html
6+
*/
7+
public class Client {
8+
public static void main(String[] args) {
9+
MemberStrategy strategy=new AdvancedMemberStrategy();
10+
Price price=new Price(strategy);
11+
double quote=price.quote(300);
12+
System.out.println("该会员购买的图书经过计算价格为:"+quote);
13+
14+
}
15+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package strategy;
2+
3+
public class IntermediateMemberStrategy implements MemberStrategy {
4+
@Override
5+
public double calcPrice(double booksPrice) {
6+
System.out.println("对于中级会员的折扣为10%");
7+
return booksPrice* 0.9 ;
8+
}
9+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package strategy;
2+
3+
/**
4+
* 抽象折扣类
5+
*/
6+
public interface MemberStrategy {
7+
public double calcPrice(double booksPrice);
8+
}

src/main/java/strategy/Price.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package strategy;
2+
3+
public class Price {
4+
private MemberStrategy strategy;
5+
6+
/**
7+
*
8+
* @param strategy 具体的策略对象
9+
*/
10+
public Price(MemberStrategy strategy){
11+
this.strategy=strategy;
12+
}
13+
14+
/**
15+
* 计算折扣后的价格。
16+
* @param boosPrice
17+
* @return
18+
*/
19+
public double quote(double boosPrice){
20+
return this.strategy.calcPrice(boosPrice);
21+
}
22+
23+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package strategy;
2+
3+
public class PrimaryMemberStrategy implements MemberStrategy {
4+
@Override
5+
public double calcPrice(double booksPrice) {
6+
System.out.println("对于初级会员没有折扣");
7+
return booksPrice;
8+
}
9+
}

0 commit comments

Comments
 (0)