GOF23设计模式(十三)

GOF设计模式之策略模式(Strategy)与模板方法模式(template method)

策略模式(Strategy)

分离算法,选择实现。

接口

1
2
3
public interface Strategy {
public double getPrice(double standardPrice);
}

实现接口方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class NewCustomerFewStrategy implements Strategy{

@Override
public double getPrice(double standardPrice) {
System.out.println("不打折,原价");
return standardPrice;
}
}

public class NewCustomerManyStrategy implements Strategy{

@Override
public double getPrice(double standardPrice) {
System.out.println("打九折");
return standardPrice*0.9;
}
}

public class OldCustomerFewStrategy implements Strategy{

@Override
public double getPrice(double standardPrice) {
System.out.println("打八五折");
return standardPrice*0.85;
}
}

public class OldCustomerManyStrategy implements Strategy{

@Override
public double getPrice(double standardPrice) {
System.out.println("打八折");
return standardPrice*0.8;
}
}

负责交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 负责和具体的策略类交互
*
*/
public class Context {
private Strategy strategy;

public Context(Strategy strategy) {
this.strategy = strategy;
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void pringPrice(double s) {
System.out.println("您的价格是:"+strategy.getPrice(s));
}
}

测试

1
2
3
4
5
6
7
8
public class Client {

public static void main(String[] args) {
Strategy s1 =new OldCustomerManyStrategy();
Context ctx =new Context(s1);
ctx.pringPrice(864);
}
}

结果

打八折
您的价格是:691.2

模板方法模式(template method)

定义一个操作中的算法骨架,将某些步骤延迟到子类中实现。

抽象类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public abstract class BankTemplateMethod {
//具体方法
public void takeNumber() {
System.out.println("取号排队");
}
public abstract void transact();//办理具体的业务 钩子方法
public void evaluate() {
System.out.println("反馈评分");
}
public final void process() { //模板方法
this.takeNumber();
this.transact();
this.evaluate();
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Client {

public static void main(String[] args) {
BankTemplateMethod btm=new DrawMoney();
btm.process();
//匿名内部类
BankTemplateMethod btm1 = new BankTemplateMethod() {

@Override
public void transact() {
System.out.println("我要存钱");
}
};
btm1.process();
}

}
class DrawMoney extends BankTemplateMethod{

@Override
public void transact() {
System.out.println("我要取款!!!");
}
}

结果

取号排队
我要取款!!!
反馈评分
取号排队
我要存钱
反馈评分

原创技术分享,您的支持将鼓励我继续创作
0%