简单工厂模式

用到了继承和聚合,不同的方法继承于统一的接口,方法的对象聚合于工厂中

class Operator
{
public:
    Operator() {};
    ~Operator() {};

public:
    virtual int oper()
    {
        return 0;
    }
    void set_a(double a_input)
    {
        a = a_input;
    }
    double get_a()
    {
        return a;
    }
    void set_b(double b_input)
    {
        b = b_input;
    }
    double get_b()
    {
        return b;
    }

private:

    double a;
    double b;
};

class AddMethod:public Operator
{
public:
    AddMethod() {};
    ~AddMethod() {};

public:
    virtual int oper()
    {
        return get_a()+ get_b();
    }
};
class SubMethod :public Operator
{
public:
    SubMethod() {};
    ~SubMethod() {};

public:
    virtual int oper()
    {
        return get_a() - get_b();
    }
};

class OperatorFactory
{
public:
    OperatorFactory() {};
    ~OperatorFactory() {};

public:
    Operator* createOperator(char  data)
    {
        switch (data)
        {
        case '+':
            return new AddMethod();
        case '-':
            return new SubMethod();
        }
    }
};

int main()
{

    OperatorFactory operFactory;
    Operator* add_obj = operFactory.createOperator('+');


    add_obj->set_a(10);
    add_obj->set_b(5);
    double value = add_obj->oper();
    std::cout << value << "\n";
}

优点: 对工厂方法对比,该方法简单、所需要的文件较少,适合方法种类较为固定的问题。

缺点:违反了开闭原则,在增添新的方法的时候,需要在工厂类中添加改方法的实例;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python简单工厂模式是一种创建型设计模式,它提供了一种创建对象的方式,而无需直接暴露对象的创建逻辑。简单工厂模式通过一个工厂类来封装对象的创建过程,客户端只需要通过工厂类来获取所需的对象,而无需关心对象的具体创建细节。 在Python中,实现简单工厂模式通常包括以下几个步骤: 1. 定义一个抽象基类或接口,用于表示所要创建的对象的共同特征。 2. 创建具体的产品类,它们实现了抽象基类或接口,并提供了具体的功能实现。 3. 创建一个工厂类,该类包含一个静态方法或类方法,用于根据客户端的需求创建具体的产品对象。 4. 客户端通过调用工厂类的方法来获取所需的产品对象。 下面是一个简单的Python简单工厂模式的示例: ```python from abc import ABC, abstractmethod # 定义抽象基类 class Product(ABC): @abstractmethod def operation(self): pass # 具体产品类A class ConcreteProductA(Product): def operation(self): return "ConcreteProductA operation" # 具体产品类B class ConcreteProductB(Product): def operation(self): return "ConcreteProductB operation" # 工厂类 class SimpleFactory: @staticmethod def create_product(product_type): if product_type == "A": return ConcreteProductA() elif product_type == "B": return ConcreteProductB() else: raise ValueError("Invalid product type") # 客户端代码 product_a = SimpleFactory.create_product("A") print(product_a.operation()) # 输出:ConcreteProductA operation product_b = SimpleFactory.create_product("B") print(product_b.operation()) # 输出:ConcreteProductB operation ``` 在上述示例中,抽象基类`Product`定义了产品的共同特征,具体产品类`ConcreteProductA`和`ConcreteProductB`分别实现了抽象基类,并提供了具体的功能实现。工厂类`SimpleFactory`包含一个静态方法`create_product`,根据客户端传入的产品类型来创建具体的产品对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值