Object Design and Composition

Object Ecosystems

Classes

What are my objects?

Object Creation

Where does the object come from?

Object Scope

Where does the object go to (live)?

Object Mediation

How does the object
interact with other object?

Object Intentions

Encapsulation

// class signature
public class Person {
	// instance variables (fields)
	private String name;
	private int age;
	private boolean isFemale;

	// constructor
	public Person(String name, int age, boolean isFemale) {
		this.name = name;
		this.age = age;
		this.isFemale = isFemale;
	}
}

Utility Classes

// static state; procedural behavior
public class RandomUtils {
    private static final Random random = new Random();

    public static Double createDouble(Double min, Double max) {
        return random.nextDouble() * (max - min) + min;
    }

    public static Integer createInteger(Integer min, Integer max) {
        return createDouble(min, max).intValue();
    }

    public static Character createCharacter(char min, char max) {
        return (char) createInteger((int) min, (int) max).intValue();
    }
}

Creational Classes

public class PersonFactory {
    public static Person createRandomPerson() {
        String name = RandomUtils.createString('a', 'z', 5);
        int age = RandomUtils.createInteger(0, 100);
        boolean isFemale = RandomUtils.createBoolean(50);

        Person randomPerson = new Person(name, age, isFemale);
        return randomPerson;
    }
}

Container Classes

public class PersonWarehouse {
    private final Logger logger = Logger.getGlobal();
    private final List<Person> people = new ArrayList<>();

    public void addPerson(Person person) {
        logger.info("Registering a new person object to the person warehouse...");
        people.add(person);
    }

    public Person[] getPeople() {
    	return this.people.toArray(new Person[people.size()]);
    }
}

Managers / Handlers / Decorators

Mediation (Scope)

public class Main {
	public static void main(String[] args) {
		Person person1 = PersonFactory.createRandomPerson();
		Person person2 = PersonFactory.createRandomPerson();
		PersonWarehouse personWarehouse = new PersonWarehouse();
		personWarehouse.addPerson(person1);
		personWarehouse.addPerson(person2);

		Person[] people = personWarehouse.getPeople();
		for(Person currentPerson : people) {
			PersonHandler handler = new PersonHandler(currentPerson);
			handler.sayAge();
		}
	}
}