lundi 19 novembre 2018

(Polymorphism) Addition parameter pass to constructor of derived class in factory pattern

In factory pattern, we use a Factory class to produce a Product class that implement 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());
}

My question is, what if today we need extract information to pass into Product_B from main(), for example a reference of a class instance.

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();
     }
}

The only solution come to my mind is...

class Factory {
     // pass the reference here
     public AbstractProduct produce(int product_id, Database db){
          if (product_id == 1){
                return Product_A();
          }
          else if (product_id == 2){
                return Product_B(db);
          }
     }
}

Is there any good solution or relative design pattern can solve this problem Elegant and Clean ? Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire