两种新的创意设计模式(附代码)

255 阅读2分钟

两种新的创造型设计模式

污染工厂方法

import java.awt.*;
import java.util.function.Consumer;

public class Fish {
    private final String name;
    private final int numberOfEyes;
    private final Color color;

    private Fish(String name, Options opts) {
        this.name = name;
        this.numberOfEyes = opts.numberOfEyes;
        this.color = opts.color;
    }

    static class Options {
        int numberOfEyes = 2;
        Color color = Color.ORANGE;
    }

    public static Fish create(String name, Consumer<Options> optSetter) {
        Options opts = new Options();
        optSetter.accept(opts);
        return new Fish(name, opts);
    }

    public static void main(String[] args) {
        Fish blinky = Fish.create("Blinky", opts -> opts.numberOfEyes = 3);
    }
}

我将其命名为污染工厂方法模式,因为它依赖于突变。这种模式的奇妙之处在于,如果你仔细观察,就会发现你有命名的参数,特别是如果你使用多行lambda,它看起来几乎像一个对象字面。

我喜欢这种模式的原因是,必需的参数和可选的参数之间有明显的区别。另外,通过使用Java中最简洁的类的语法,相对来说没有什么模板。

Lockstep Builder模式

public class Sandwich {
    private final Bread.Slice bottom;
    private final Filling filling;
    private final Bread.Slice top;

    private Sandwich(Bread.Slice bottom, Filling filling, Bread.Slice top) {
        this.bottom = bottom;
        this.filling = filling;
        this.top = top;
    }

    static class OpenFacedSandwich {
        private final Bread.Slice bottom;
        private final Filling filling;

        OpenFacedSandwich(Bread.Slice bottom, Filling filling) {
            this.bottom = bottom;
            this.filling = filling;
        }

        Sandwich addTop(Bread.Slice top) {
            return new Sandwich(bottom, filling, top);
        }
    }

    public static void main(String[] args) {
        Bread wheatLoaf = new Bread();
        Sandwich turkeyOnWheat = wheatLoaf.slice()
                .addFilling(new Turkey())
                .addTop(wheatLoaf.slice());
    }
}

public class Bread {
    public static class Slice {
        Sandwich.OpenFacedSandwich addFilling(Filling filling) {
            return new Sandwich.OpenFacedSandwich(this, filling);
        }
    }

    public Slice slice() {
        return new Slice();
    }
}

public interface Filling {
}

public class Turkey implements Filling {
}

这种模式的核心是为每个需要的字段建立一个新的类,并在每个构建器类上建立一个方法,返回下一个步骤。与构建器模式相比,这个模式的方向是相反的。它是非常啰嗦的。这种模式的重点是使对象的创建尽可能的简单。通过在每个类上只有一个方法,你的IDE实际上会一步步地引导你创建对象。如果你经常实例化一个对象,最终可能值得投资以这种方式设计类。或者,如果你使用某种形式的代码生成,这也可能使你觉得这样做是值得的。