在工厂模式中,我们使用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();
}
}
是否有任何好的解决方案或相对的设计模式可以解决优雅和清洁的问题?非常感谢。
答案 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();
}
希望这会有所帮助。