Dynamic context

From cdd
Jump to: navigation, search

A dynamic context is something that can vary at runtime within a static context:


CDD-dynamic-context.png


Static context can use concrete classes directly but with dynamic context we have to go through an interface. In this example the interface is represented by Person and the concrete classes by PersonAdmin and PersonRestricted which both implements the interface Person. Which of the two implementations that should be used is decided by the creator using the context variable "userRole".


Pretend we want to restrict access to phone numbers so that only admin users can see them. Add some code, start by UserRole (put in an arbitrary package):

public enum UserRole {
    RESTRICTED, ADMIN
}

...add these interfaces and classes:

public interface Person {
    String getPhoneNumber();
}
 
public class PersonState {
    String name;
    String phoneNumber;
}
 
public class PersonCreator {
    PersonState state;
}

...regenerate (see the Quick-start guide for instructions):

C:\Projects\MyProject>laja myproject


...create the classes PersonRestricted and PersonAdmin:

import static com.myproject.PersonCreator.PersonBehaviour;
 
public class PersonRestricted extends PersonBehaviour implements Person {
    public PersonRestricted(PersonState state) {
        super(state);
    }
 
    public String getPhoneNumber() {
        return "???";
    }
}
 
import static com.myproject.PersonCreator.PersonBehaviour;
 
public class PersonAdmin extends PersonBehaviour implements Person {
    public PersonAdmin(PersonState state) {
        super(state);
    }
 
    public String getPhoneNumber() {
        return state.getPhoneNumber();
    }
}


...add the method asPerson to PersonCreator between the state and the "Generated code" comment:

...
    public Person asPerson(UserRole role) {
        if (role == UserRole.ADMIN) {
            return new PersonAdmin(state.asImmutable());
        }
        return new PersonRestricted(state.asImmutable());
    }
...


...regenerate and add Main:

import static com.myproject.PersonCreator.createPerson;
 
public class Main {
 
    public static void main(String[] args) {
        Person adam = createPerson().name("Adam").phoneNumber("08-12345678").asPerson(UserRole.ADMIN);
        Person bert = createPerson().name("Bert").phoneNumber("08-12345678").asPerson(UserRole.RESTRICTED);
 
        System.out.println("Adams phone number: " + adam.getPhoneNumber());
        System.out.println("Berts phone number: " + bert.getPhoneNumber());
    }
}

...execute and we get the output:

Adams phone number: 08-12345678
Berts phone number: ???


< Back          Next >