3 Replies Latest reply: Apr 26, 2010 7:20 AM by 800387 RSS

    when to use the abstract factory pattern

    843853
      Hi: I want to know when we need to use the abstract factory pattern.

      Here is an example,I want to know if it is necessary.

      [The UML|http://picasaweb.google.com/101738709729819671831/Public#5463305172407569298]

      THe above is the abstract factory pattern, it is recommended by my classmate. THe following is myown implemention. I do not think it is necessary to use the pattern.

      And the following is some core codes:
      package net;
      
      import java.io.IOException;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Properties;
      
      
      
      public class Test {
          public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
              DaoRepository dr=new DaoRepository();
              AbstractDao dao=dr.findDao("sql");
              dao.insert();
          }
      }
      
      class DaoRepository {
          Map<String, AbstractDao> daoMap=new HashMap<String, AbstractDao>();
          public DaoRepository () throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException  {
              Properties p=new Properties();
              p.load(DaoRepository.class.getResourceAsStream("Test.properties"));
              initDaos(p);
          }
          public void initDaos(Properties p) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
              String[] daoarray=p.getProperty("dao").split(",");
              for(String dao:daoarray) {
                  AbstractDao ad=(AbstractDao)Class.forName(dao).newInstance();
                  daoMap.put(ad.getID(),ad);
              }
          }
          public AbstractDao findDao(String id) {return daoMap.get(id);}
      
      }
      abstract class AbstractDao {
          public abstract String getID();
          public abstract void insert();
          public abstract void update();
      }
      class SqlDao extends AbstractDao {
          public SqlDao() {}
          public String getID() {return "sql";}
          public void insert() {System.out.println("sql insert");}
          public void update() {System.out.println("sql update");}
      }
      class AccessDao extends AbstractDao {
          public AccessDao() {}
          public String getID() {return "access";}
          public void insert() {System.out.println("access insert");}
          public void update() {System.out.println("access update");}
      }
      And the content of the Test.properties is just one line:
      dao=net.SqlDao,net.SqlDao
      So any ont can tell me if this suitation is necessary?

      Edited by: apachemaven on 2010-4-23 ??1:16

      Edited by: apachemaven on 2010-4-23 ??1:17

      Edited by: apachemaven on 2010-4-23 ??1:18

      Edited by: apachemaven on 2010-4-23 ??1:19