(多态性)附加参数以工厂模式传递给派生类的构造函数

时间:2018-11-19 17:34:11

标签: oop design-patterns polymorphism factory-pattern

在工厂模式中,我们使用Factory类来生成实现Product的{​​{1}}类。

Abstract Product

我的问题是,如果今天我们需要从interface AbstractProduct { public string getDetail(); } class Product_A : AbstractProduct { public string getDetail(); } class Product_B : AbstractProduct { public string getDetail(); } class Factory { public AbstractProduct produce(int product_id){ if (product_id == 1){ return Product_A(); } else if (product_id == 2){ return Product_B(); } } } int main() { Factory factory = new Factory(); int id; // a random number either 1 or 2 print(factory.produce(id).getDetail()); } 中提取信息以传递到Product_B中,例如类实例的引用。

main()

我想到的唯一解决方案是...

int main() {
     // object that need to be passed into Product_B
     Database database = new Database();

     Factory factory = new Factory();
     int id; // a random number either 1 or 2

     print(factory.produce(id).getDetail());
}

class Product_B : AbstractProduct {
     public string getDetail() {
         // I need the reference of database here.
         // I'm unable to instance a database in side Product_B.
         // I need to somehow pass it into Product_B.
         database.query();
     }
}

是否有任何好的解决方案或相对的设计模式可以解决优雅清洁的问题?非常感谢。

1 个答案:

答案 0 :(得分:0)

解决方案的缺点是,Factory的每个客户端都必须具有Database才能调用produce方法。

因此,您可以在此处使用Abstract Factory模式:

interface AbstractFactory {
    AbstractProduct produce();
}

class Factory_A implements AbstractFactory {
    AbstractProduct produce() { return new Product_A(); }
}

class Factory_B implements AbstractFactory {
    private Database db;
    public Factory_B(Database db) { this.db = db; }
    AbstractProduct produce() { return new Product_B(db); }
}

class Client {
    private AbstractFactory factory;
    public Client(AbstractFactory factory) { this.factory = factory; }
    public void foo() {
        AbstractProduct product = factory.produce();
        // ...
    }
}

void main() {
    AbstractFactory factory = random() == 1 ?
                                new Factory_A() :
                                new Factory_B(new Database(...));

    print(factory.produce().getDetail());

    Client client = new Client(factory);
    client.foo();
}

希望这会有所帮助。