简单工厂模式

title

简单工厂模式(Simple Factory Pattern)属于创建型模式,用于创建对象,又称为静态工厂模式。该模式由一个工厂类负责创建对象,客户端不需要知道具体的创建细节,只需要通过工厂类来获取所需对象的实例即可。

简单工厂模式的主要角色有:

  • 工厂类(Factory Class):用于创建对象,通常是一个静态方法,根据不同的参数返回不同的对象实例。

  • 抽象产品类(Abstract Product Class):定义产品类的公共接口,用于客户端调用。

  • 具体产品类(Concrete Product Class):实现抽象产品类定义的接口,是具体的产品类。

简单工厂模式的优点在于简化了对象的创建过程,使客户端无需知道具体的创建细节。同时,通过工厂类统一管理对象的创建,也方便了代码的维护和修改。不足之处在于如果需要新增产品,就需要修改工厂类的代码,违背了开闭原则。

下面是简单工厂模式的示例代码:

// 抽象产品类
interface Product {
    void use();
}

// 具体产品类A
class ConcreteProductA implements Product {
    public void use() {
        System.out.println("使用具体产品A");
    }
}

// 具体产品类B
class ConcreteProductB implements Product {
    public void use() {
        System.out.println("使用具体产品B");
    }
}

// 工厂类
class SimpleFactory {
    public static Product createProduct(String type) {
        if (type.equals("A")) {
            return new ConcreteProductA();
        } else if (type.equals("B")) {
            return new ConcreteProductB();
        } else {
            return null;
        }
    }
}

// 客户端调用
public class Client {
    public static void main(String[] args) {
        Product productA = SimpleFactory.createProduct("A");
        productA.use();

        Product productB = SimpleFactory.createProduct("B");
        productB.use();
    }
}

输出结果为:

使用具体产品A
使用具体产品B
powered by Gitbook© 2023 编外计划 | 最后修改: 2023-11-24 03:37:01

results matching ""

    No results matching ""