Object Factories

 


Reference Example

The reference example illustrates how an instance of a Referenceable class Fruit is stored in and subsequently looked up from the directory. When the reference is looked up from the directory, Context.lookup() turned the data read from the directory into an instance of Fruit.
Fruit f2 = (Fruit) ctx.lookup("cn=favorite");
This happens because of the following.
  1. The service provider being used (Sun's LDAP service provider) invoked DirectoryManager.getObjectInstance() and supplied the method the data (a reference) that the provider read from the directory for the entry "cn=favorite".
  2. The reference identified FruitFactory as the object factory's class name.
  3. FruitFactory.getObjectInstance() returned an instance of Fruit.
FruitFactory.getObjectInstance() is simple. It first verifies that it can do something with the data. That is, it checks that the data is a Reference containing an address of type "fruit" and that the reference is for objects of class Fruit. If this verification fails, then the factory returns null so that other factories, if any, can be attempted. If it succeeds, then the content of the address (in this case "orange") is used to create a new instance of Fruit, which is then returned.

The definition of FruitFactory.getObjectInstance() is as follows.

public Object getObjectInstance(Object obj, Name name, Context ctx,
    Hashtable env) throws Exception {
    if (obj instanceof Reference) {
        Reference ref = (Reference)obj;
        if (ref.getClassName().equals(Fruit.class.getClassName())) {
	    RefAddr addr = ref.get("fruit");
	    if (addr != null) {
  	        return new Fruit((String)addr.getContent());
	    }
        }
    }
    return null;
}

Object Factories