设计模式

设计模式

策略模式

示例代码

1
2
3
4
5
6
7
8
9
10
11
public class TestMain {
public static void main(String[] args) {
Computer computer = new Computer();
AddComputer addComputer = new AddComputer();
SubComputer subComputer = new SubComputer();

computer
.setOperation(subComputer);
System.out.println(computer.doOperation(1, 2));
}
}

接口

1
2
3
4
5
public interface Operation {

public int calculate(int n1, int n2);

}

具体算法实现类

1
2
3
4
5
6
7
8
9
10
11
12
public class AddComputer implements Operation{
@Override
public int calculate(int n1, int n2) {
return n1 + n2;
}
}
public class SubComputer implements Operation{
@Override
public int calculate(int n1, int n2) {
return n1 - n2;
}
}

操作类

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

private Operation operation;

public void setOperation(Operation operation) {
this.operation = operation;
}

public int doOperation(int n1, int n2){
return this.operation.calculate(n1, n2);
}

}

建造者模式

示例代码

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
public class Product {
private String attribute1;
private String attribute2;
private String attribute3;

private Product(Builder builder) {
this.attribute1 = builder.attribute1;
this.attribute2 = builder.attribute2;
this.attribute3 = builder.attribute3;
}

// Getter methods

public static class Builder {
private String attribute1;
private String attribute2;
private String attribute3;

public Builder attribute1(String value) {
this.attribute1 = value;
return this;
}

public Builder attribute2(String value) {
this.attribute2 = value;
return this;
}

public Builder attribute3(String value) {
this.attribute3 = value;
return this;
}

public Product build() {
return new Product(this);
}
}
}

用法

1
2
3
4
5
Product product = new Product.Builder()
.attribute1("Value 1")
.attribute2("Value 2")
.attribute3("Value 3")
.build();

设计模式
http://cxycsx.vip/2023/08/30/设计模式/设计模式/
作者
程序员陈师兄
发布于
2023年8月30日
许可协议