创建型模式

简单工厂

Pay.java

1
2
3
public interface Pay {
void pay(Integer money);
}

SimpleFactory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class SimpleFactory {

public static Pay create(String payType) {

if (payType.equals("ZFB")) {
return new ZFBPay();
} else if (payType.equals("WX")) {
return new WXPay();
}else {
return null;
}
}
}

WXPay.java

微信支付

1
2
3
4
5
public class WXPay implements Pay {
public void pay(Integer money) {
System.out.println("微信支付:"+money+"元");
}
}

ZFBPay.java

支付宝支付

1
2
3
4
5
public class ZFBPay implements Pay {
public void pay(Integer money) {
System.out.println("支付宝支付:"+money+"元");
}
}

Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 简单工厂设计模式
*/
public class Test {

public static void main(String[] args) {

Pay wx = SimpleFactory.create("WX");
wx.pay(2);

Pay zfb = SimpleFactory.create("ZFB");
zfb.pay(1);
}
}

行为模式

策略模式

基础

Strategy

1
2
3
4
5
6
7
public interface Strategy {

/**
* 策略方法
*/
public void strategyInterface();
}

ConcreteStrategyA

1
2
3
4
5
6
7
public class ConcreteStrategyA implements Strategy {

@Override
public void strategyInterface() {
System.out.println("ConcreteStrategyA");
}
}

ConcreteStrategyB

1
2
3
4
5
6
7
public class ConcreteStrategyB implements Strategy {

@Override
public void strategyInterface() {
System.out.println("ConcreteStrategyB");
}
}

ConcreteStrategyC

1
2
3
4
5
6
7
public class ConcreteStrategyC implements Strategy {

@Override
public void strategyInterface() {
System.out.println("ConcreteStrategyC");
}
}

Context

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Context {

//持有一个具体策略的对象
private Strategy strategy;

/**
* 构造函数,传入一个具体策略对象
*/
public Context(Strategy strategy){
this.strategy = strategy;
}

/**
* 策略方法
*/
public void contextInterface(){
strategy.strategyInterface();
}

}

Test.java

1
2
3
4
5
6
7
public class Test {

public static void main(String[] args) {
Context context = new Context(new ConcreteStrategyA());
context.contextInterface();
}
}

应用

MemberStrategy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 会员策略
*/
public interface MemberStrategy {

/**
* 计算图书的价格,根绝会员等级
* @param booksPrice 图书的原价
* @return 计算出打折后的价格
*/
public double calcPrice(double booksPrice);

}

PrimaryMemberStrategy.java 初级会员

1
2
3
4
5
6
7
public class PrimaryMemberStrategy implements MemberStrategy {
@Override
public double calcPrice(double booksPrice) {
System.out.println("初级会员,没有折扣");
return 0;
}
}

IntermediateMemberStrategy.java 中级会员

1
2
3
4
5
6
7
public class IntermediateMemberStrategy implements MemberStrategy {
@Override
public double calcPrice(double booksPrice) {
System.out.println("对于中级会员的折扣为10%");
return booksPrice * 0.9;
}
}

AdvancedMemberStrategy.java 高级会员

1
2
3
4
5
6
7
public class AdvancedMemberStrategy implements MemberStrategy {
@Override
public double calcPrice(double booksPrice) {
System.out.println("对于高级会员的折扣为20%");
return booksPrice * 0.8;
}
}

Price.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Price {

private MemberStrategy strategy;

public Price(MemberStrategy strategy) {
this.strategy = strategy;
}

/**
* 计算图书的价格
* @param booksPrice 图书的原价
* @return 计算出打折后的价格
*/
public double quote(double booksPrice){
return this.strategy.calcPrice(booksPrice);
}
}

Test.java

1
2
3
4
5
6
7
8
9
10
11
12
public class Test {

public static void main(String[] args) {
//选择并创建需要使用的策略对象
MemberStrategy strategy = new AdvancedMemberStrategy();
//创建环境
Price price = new Price(strategy);
//计算价格
double quote = price.quote(300);
System.out.println("图书的最终价格为:" + quote);
}
}

结构模式

装饰模式

mybatis的执行期就用的是装饰模式

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 抽象构件角色
// 比如这是一期开发的接口
public interface Shape {
void draw();
}

// 具体构件角色
// 比如这是一期开发好的实现类
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}

// 到二期开发了,发现这个Rectangle的实现不太好用了,需要添加别的功能
// 抽象装饰器
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;

public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}

public void draw(){
decoratedShape.draw();
}
}

// 具体装饰器角色
// 这里就是开发的二期的功能
public class RedShapeDecorator extends ShapeDecorator {

public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}

@Override
public void draw() {
// 调用一期的代码原本的功能
decoratedShape.draw();

// 调用二期的新代码的功能
setRedBorder(decoratedShape);
}

private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}


// 比如一个人冷了,多套了一件毛衣,发现还是冷,又多穿了一件羽绒服,一层一层的,装饰
public class DecoratorPatternDemo {
public static void main(String[] args) {
// 一期的代码
Shape circle = new Circle();
// 二期的代码
ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
redCircle.draw();
}
}

模板模式

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
36
37
38
39
40
41
42
43
44
45
46
public interface Lifecycle {
void init();
}

abstract class AbstractLifecycle implements Lifecycle{

abstract void run();

@Override
public void init() {
System.out.println("这里是公共方法");
run();
System.out.println("这里也是公共方法");
}
}

public class ServerStandard extends AbstractLifecycle {

@Override
void run() {
System.out.println("我是实现,父类将调用我");
}
}

public class ServerStandard2 extends AbstractLifecycle {

@Override
void run() {
System.out.println("我是实现2,父类将调用我");
}
}

public class Test {

public static void main(String[] args) {

ServerStandard serverStandard = new ServerStandard();
serverStandard.init();

System.out.println("============================================");

ServerStandard2 serverStandard2 = new ServerStandard2();
serverStandard2.init();

}
}

责任链模式

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
public abstract class Handler {
protected String name; // 处理者姓名

@Setter
protected Handler nextHandler; // 下一个处理者

public Handler(String name) {
this.name = name;
}

public abstract boolean process(LeaveRequest leaveRequest); // 处理请假
}

public class Director extends Handler {

public Director(String name) {
super(name);
}

@Override
public boolean process(LeaveRequest leaveRequest) {
// 随机数大于3则为批准,否则不批准
boolean result = (new Random().nextInt(10)) > 3;
String log = "主管<%s> 审批 <%s> 的请假申请,请假天数: <%d> ,审批结果:<%s> ";
System.out.println(String.format(log, this.name, leaveRequest.getName(), leaveRequest.getNumOfDays(), result == true ? "批准" : "不批准"));

if (!result) { // 不批准
return false;
} else if (leaveRequest.getNumOfDays() < 3) { // 批准且天数小于3,返回true
return true;
}
return nextHandler.process(leaveRequest); // 批准且天数大于等于3,提交给下一个处理者处理

}
}

public class Manager extends Handler {

public Manager(String name) {
super(name);
}

@Override
public boolean process(LeaveRequest leaveRequest) {
boolean result = (new Random().nextInt(10)) > 3; // 随机数大于3则为批准,否则不批准
String log = "经理<%s> 审批 <%s> 的请假申请,请假天数: <%d> ,审批结果:<%s> ";
System.out.println(String.format(log, this.name, leaveRequest.getName(), leaveRequest.getNumOfDays(), result == true ? "批准" : "不批准"));

if (!result) { // 不批准
return false;
} else if (leaveRequest.getNumOfDays() < 7) { // 批准且天数小于7
return true;
}
return nextHandler.process(leaveRequest); // 批准且天数大于等于7,提交给下一个处理者处理
}
}

public class TopManager extends Handler {

public TopManager(String name) {
super(name);
}

@Override
public boolean process(LeaveRequest leaveRequest) {
boolean result = (new Random().nextInt(10)) > 3; // 随机数大于3则为批准,否则不批准
String log = "总经理<%s> 审批 <%s> 的请假申请,请假天数: <%d> ,审批结果:<%s> ";
System.out.println(String.format(log, this.name, leaveRequest.getName(), leaveRequest.getNumOfDays(), result == true ? "批准" : "不批准"));

if (!result) { // 总经理不批准
return false;
}
return true; // 总经理最后批准
}
}

@Data
@AllArgsConstructor
public class LeaveRequest {

private String name; // 请假人姓名
private int numOfDays; // 请假天数

}

public class Test {

public static void main(String[] args) {
// 创建审批人
Handler zhangsan = new Director("张三");
Handler lisi = new Manager("李四");
Handler wangwu = new TopManager("王五");

// 创建责任链
zhangsan.setNextHandler(lisi);
lisi.setNextHandler(wangwu);

// 发起请假申请第一次
boolean result1 = zhangsan.process(new LeaveRequest("小旋锋", 1));
System.out.println("最终结果:" + result1 + "\n");

// 发起请假申请第二次
boolean result2 = zhangsan.process(new LeaveRequest("小旋锋", 4));
System.out.println("最终结果:" + result2 + "\n");

// 发起请假申请第三次
boolean result3 = zhangsan.process(new LeaveRequest("小旋锋", 8));
System.out.println("最终结果:" + result3 + "\n");
}
}

Tomcat的过滤器也使用到了责任链ApplicationFilterChain,具体的还没有读,先写完这个模式,比模板模式感觉有点复杂

参考的是:https://juejin.im/post/6844903702260629512#heading-11,

感觉举的例子的业务显示还不是特别的好理解

也参考下这个:https://www.cnblogs.com/tanshaoshenghao/p/10741160.html

适配器模式

SpringMVC的DispatchServlet的例子

具体实现

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
/**
* Description: 控制器接口
*/
public interface Controller {}

/**
* Controller 实现之1:HttpController
*/
public class HttpController implements Controller {

public void doHttpHandler() {
System.out.println("HttpController:httpMethod()");
}
}

/**
* Controller 实现之2:SimpleController
*/
public class SimpleController implements Controller {

public void doSimplerHandler() {
System.out.println("SimpleController:simpleMethod()");
}
}

/**
* Controller 实现之3:HttpController
*/
public class AnnotationController implements Controller {

public void doAnnotationHandler() {
System.out.println("AnnotationController:annotationMethod()");
}
}

处理器

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 定义一个Adapter接口
*/
public interface HandlerAdapter {

/**
* 是否支持
*
* @param handler
* @return
*/
boolean supports(Object handler);

/**
* 处理
*
* @param handler
*/
void handle(Object handler);

}

/**
* HttpController 的适配器
*/
public class HttpHandlerAdapter implements HandlerAdapter {

public boolean supports(Object handler) {
return (handler instanceof HttpController);
}

public void handle(Object handler) {
((HttpController) handler).doHttpHandler();
}
}

/**
* SimpleController的适配器
*/
public class SimpleHandlerAdapter implements HandlerAdapter {

public boolean supports(Object handler) {
return (handler instanceof SimpleController);
}

public void handle(Object handler) {
((SimpleController) handler).doSimplerHandler();
}
}

/**
* AnnotationController 的适配器
*/
public class AnnotationHandlerAdapter implements HandlerAdapter {

public boolean supports(Object handler) {
return (handler instanceof AnnotationController);
}

public void handle(Object handler) {
((AnnotationController) handler).doAnnotationHandler();
}
}

main方法

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
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 模拟一个DispatcherServlet,适配器(适配者模式)
* HandlerAdapter(适配器类) 作为适配器来适配各种 Handler(适配者类)(如Controller)
*/
public class DispatchServlet {

public static List<HandlerAdapter> handlerAdapters = new ArrayList<HandlerAdapter>();

/**
* 注册所有 HandlerAdapter
*/
public DispatchServlet() {
handlerAdapters.add(new AnnotationHandlerAdapter());
handlerAdapters.add(new HttpHandlerAdapter());
handlerAdapters.add(new SimpleHandlerAdapter());
}

/**
* 模拟DispatchServlet 中的 doDispatch()方法
*/
public void doDispatch() {
Controller handler = new AnnotationController();
// 通过handler来找到对应适配器
HandlerAdapter handlerAdapter = getHandler(handler);
// 通过执行适配器的handle,来执行对应的controller对应方法
handlerAdapter.handle(handler);
}

/**
* 找到与handler适配的适配器:通过handler 遍历 HandlerAdapter 适配器来实现
*/
public HandlerAdapter getHandler(Controller handler) {
for (HandlerAdapter adapter : handlerAdapters) {
if (adapter.supports(handler)) {
return adapter;
}
}
return null;
}

/**
* 模拟运行
*/
public static void main(String[] args) {
new DispatchServlet().doDispatch();
}
}

参考

https://refactoringguru.cn/design-patterns

装饰器模式