Java函数式编程中高阶函数在设计模式中的应用场景?

Java 函数式编程中高阶函数在设计模式中的应用场景

函数式编程使用高阶函数将函数作为参数或返回值,这在设计模式中具有广泛的应用。

策略模式

策略模式定义了一个算法族,它们之间可以互换,从而让算法独立于使用它们的客户端。

使用高阶函数:

interface Strategy {
    int calculate(int a, int b);
}

Strategy addStrategy = (a, b) -> a + b;
Strategy subtractStrategy = (a, b) -> a - b;

int result = calculate(addStrategy, 10, 5); // 15
int result = calculate(subtractStrategy, 10, 5); // 5

private int calculate(Strategy strategy, int a, int b) {
    return strategy.calculate(a, b);
}

适配器模式

适配器模式将一个类的接口转换成另一个接口,使得原本不兼容的类可以协同工作。

使用高阶函数:

class LegacyClass {
    public String getOldName() {
        return "Old Name";
    }
}

interface NewInterface {
    String getNewName();
}

class Adapter implements NewInterface {
    private LegacyClass legacyClass;

    Adapter(LegacyClass legacyClass) {
        this.legacyClass = legacyClass;
    }

    @Override
    public String getNewName() {
        return legacyClass.getOldName();
    }
}

NewInterface newInterface = new Adapter(new LegacyClass());
String newName = newInterface.getNewName(); // "Old Name"

装饰器模式

装饰器模式动态地给一个对象添加新的行为,这就可以在不修改对象本身的情况下扩展其功能。

使用高阶函数:

class Decorator implements Shape {
    private Shape shape;

    Decorator(Shape shape) {
        this.shape = shape;
    }

    @Override
    pu

blic void draw() { shape.draw(); } } class ColoredShape extends Decorator { private String color; ColoredShape(Shape shape, String color) { super(shape); this.color = color; } @Override public void draw() { super.draw(); System.out.println("Color: " + color); } } Shape redCircle = new ColoredShape(new Circle(), "Red"); redCircle.draw(); // "Draw a Circle in Red color"