Unified Access Pattern Design


Motivation:

The pattern Unified Access describes a type safe access (reading and writing) to values of a map object (object that maps keys to values) for a such case where values have got different data types.

Structure (class model):

The model contains two classes: Class Diagram

Implementation in Java language

The implementation requires a generic type language support that's why the Java SE 5.0 or more must be used.
A MyMap class implements a simple map behavior and it contains two keys NAME and AGE.
import java.util.*;
public class MyMap {
    
    public static final Property<String> NAME = new Property<String>();
    public static final Property<Integer> AGE = new Property<Integer>();
    private Map<Property, Object> data = new HashMap<Property, Object>();
protected Object readValue(Property key) { return data.get(key); } protected void writeValue(Property key, Object value) { data.put(key, value); } }
All keys are an instance of a Property class, however each of them will provide a value of a different type.
If both classes (MyMap and Property) will be located in the same package, then it is possible to retain their visibility to protected so that no strange object can to use them.
public class Property<VALUE> {
public void setValue(MyMap map, VALUE value) { map.writeValue(this, value); } public VALUE getValue(MyMap map) { return (VALUE) map.readValue(this); } }
This pattern allows a value access by a methods of key only. It is possible to verify the method setValue accepts declared value type to write into map object and then method getValue returns the same data type only.
            
MyMap map = new MyMap();
MyMap.NAME.setValue(map, "Peter Prokop"); MyMap.AGE .setValue(map, 22); String name = MyMap.NAME.getValue(map); int age = MyMap.AGE.getValue(map); System.out.println(name + " is " + age);

Usage:

The pattern design can be used in place of conventional POJO object. It's meaningful in case there is to need to refer a method (set/get), no its value. Here are three samples of usage in a Java language Two projects has been built by this pattern design at first probably. There are jWorkSheet and UJO Framework.
Both projects are available include a source code on SourceForge.net under an open license since 2007-10-24.
The pattern design was slightly extended; a final solution is described by two interfaces

About Author:


PPone(c) 2007

Valid XHTML 1.0 Strict