Java Lambda

Lambda 示例

源码来源: Github java-design-patterns/factory-kit

基础类

1
2
public interface Weapon {
}
1
2
3
public enum WeaponType {
SWORD, AXE, BOW, SPEAR
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Sword implements Weapon {
@Override
public String toString() {
return "Sword";
}
}

public class Axe implements Weapon {
@Override
public String toString() {
return "Axe";
}
}

// Bow Spear 略
1
2
3
4
5
import java.util.function.Supplier;

public interface Builder {
void add(WeaponType name, Supplier<Weapon> supplier);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;

public interface WeaponFactory {

Weapon create(WeaponType name);

static WeaponFactory factory(Consumer<Builder> consumer) {
Map<WeaponType, Supplier<Weapon>> map = new HashMap<>();
consumer.accept(map::put);
return name -> map.get(name).get();
}
}

非 Lambda 方式实现 WeaponFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static WeaponFactory factory2(Consumer<Builder> consumer) {
Map<WeaponType, Supplier<Weapon>> map = new HashMap<>();

// accept 实现方式 1
// consumer.accept(((name, supplier) -> map.put(name, supplier)));

// accept 实现方式 2
consumer.accept(new Builder() {
@Override
public void add(WeaponType name, Supplier<Weapon> supplier) {
map.put(name, supplier);
}
});
// create 非 lambda 实现方式
return new WeaponFactory() {
@Override
public Weapon create(WeaponType name) {
return map.get(name).get();
}
};
}

Lambda 方式初始化 WeaponFactory

1
2
3
4
5
6
7
8
private static WeaponFactory getWeaponFactory_lam() {
return WeaponFactory.factory(builder -> {
builder.add(WeaponType.SWORD, Sword::new);
builder.add(WeaponType.AXE, Axe::new);
builder.add(WeaponType.SPEAR, Spear::new);
builder.add(WeaponType.BOW, Bow::new);
});
}

非 Lambda 方式初始化 WeaponFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static WeaponFactory getWeaponFactory() {
return WeaponFactory.factory(new Consumer<Builder>() {
@Override
public void accept(Builder builder) {
builder.add(WeaponType.SWORD, new Supplier<Weapon>() {
@Override
public Weapon get() {
return new Sword();
}
});
builder.add(WeaponType.AXE, () -> new Axe());
builder.add(WeaponType.SPEAR, Spear::new);
}
});
}

相关资料

听说,打赏我的人最后都找到了真爱。