返回

单例模式、工厂方法模式和建造者模式:创建型设计模式揭秘

Android

在软件工程领域,创建型设计模式是一组旨在管理对象创建过程的模式。这些模式旨在解决常见的问题,例如:如何创建单一实例(单例模式)、如何创建对象而不将依赖项暴露给客户端(工厂方法模式)以及如何将复杂对象的创建分解为多个步骤(建造者模式)。

单例模式

单例模式旨在确保某个类只有一个实例。这通常用于需要全局访问或唯一实例的场景。Java 中的单例实现通常使用静态初始化,如下所示:

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

工厂方法模式

工厂方法模式允许您创建对象而不将依赖项暴露给客户端。这使您可以轻松更改对象的创建方式,而无需修改依赖于它的代码。

interface ShapeFactory {
    Shape createShape();
}

class SquareFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Square();
    }
}

class CircleFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Circle();
    }
}

建造者模式

建造者模式允许您通过将对象的创建过程分解为多个步骤来构建复杂的对象。这使您可以将对象的创建与表示复杂对象各方面的不同组件分离。

public class Car {
    private String make;
    private String model;
    private int year;
    private Color color;

    public static class Builder {

        private String make;
        private String model;
        private int year;
        private Color color;

        public Builder(String make, String model) {
            this.make = make;
            this.model = model;
        }

        public Builder withYear(int year) {
            this.year = year;
            return this;
        }

        public Builder withColor(Color color) {
            this.color = color;
            return this;
        }

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

    private Car(Builder builder) {
        this.make = builder.make;
        this.model = builder.model;
        this.year = builder.year;
        this.color = builder.color;
    }
}

比较

模式 优势 劣势
单例 全局访问、线程安全 不支持延迟加载
工厂方法 隐藏依赖项、灵活创建 每个具体类需要自己的工厂
建造者 灵活创建复杂对象、可扩展性 代码复杂性更高