Factory with Prototype

Exemple pour une factory d'objets métier

But : Créer une factory d'objets métier en fonction d'un ID.

On admet que tous les objets métier dérivent d'une même classe BusinessObject.
  • Etape 1: Prototype et ObjetMetier
    • Créer un prototype BusinessObjectPrototype avec la méthode newBusinessObject() : BusinessObject
    • Faire implémenter toute les classes d'objets métier de cette interface prototype
  • Etape 2: La Factory
    • Créer une classe BusinessObjectFactory
    • Gérer un Map (key: id / value: prototype d'objet métier)
    • Ajouter une méthode addPrototype(String a_id, BusinessObjectPrototype a_prototype)
    • Créer enfin la méthode newBusinessObject(String a_id) qui à partir du prototype créra une instance typée d'objet métier.
    • Faire de la factory un singleton : Créer une méthode statique getInstance()
  • Etape 3: Utilisation
    • Créer une instance de prototype de chaque objet métier à utiliser et ajouter à la factory
    • Utiliser la factory BusinessObjectFactory.getInstance().newBusinessObject(a_id) pour créer vos objets.

The factory

public class BusinessObjectFactory { private static BusinessObjectFactory instance; private Map prototypeMap;
private BusinessObjectFactory() { super(); prototypeMap = new Hashtable(); }
public void addPrototype( String a_id, BusinessObjectPrototype a_prototype) { prototypeMap.put(a_id, a_prototype); }
public BusinessObject newBusinessObject( String a_id) { BusinessObjectPrototype l_prototype = (BusinessObjectPrototype) prototypeMap.get(a_id); if (l_prototype != null) { return l_prototype.newBusinessObject(); } return null(); // or return a default instance }
public static BusinessObjectFactory getInstance() { if (instance == null) { instance = new BusinessObjectFactory(); } return instance; } }

The BusinessObject

public class Person extends BusinessObject implements BusinessObjectPrototype { ....
public BusinessObject newBusinessObject() { return new Person(); } }

Utilisation

BusinessObjectFactory l_factory = BusinessObjectFactory.getInstance(); l_factory.addPrototype("Person", new Person()); l_factory.addPrototype("Adress", new Adress()); ...
BusinessObject l_person1 = l_factory.newBusinessObject("Person"); BusinessObject l_person2 = l_factory.newBusinessObject("Person");


Article extrait du site Loribel.com.
https://loribel.com/java/patterns/factory_prototype.html