Naming Operations |
The Context interface contains methods for adding, replacing, and removing a binding in a context.Adding a Binding
Context.bind() is used to add a binding to a context. It accepts as arguments the name of the object and the object to be bound.This example creates an object of class Fruit and binds it to the name "favorite" in the context ctx. If you subsequently looked up the name "favorite" in ctx, then you would get the fruit object. Note that to compile the Fruit class, you need the FruitFactory class.// Create the object to be bound Fruit fruit = new Fruit("orange"); // Perform the bind ctx.bind("favorite", fruit);If you were to run this example twice, then the second attempt would fail with a NameAlreadyBoundException. This is because the name "favorite" is already bound. For the second attempt to succeed, you would have to use rebind().
Adding or Replacing a Binding
rebind() is used to add or replace a binding. It accepts the same arguments as bind(), but the semantics are such that if the name is already bound, then it will be unbound and the newly given object will be bound.When you run this example, it will replace the binding created by the bind() example.// Create the object to be bound Fruit fruit = new Fruit("lemon"); // Perform the bind ctx.rebind("favorite", fruit);Removing a Binding
To remove a binding, you use unbind().This example, when run, removes the binding that was created by the bind() or rebind() example.// Remove the binding ctx.unbind("favorite");
Naming Operations |