All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.natpryce.makeiteasy.Maker Maven / Gradle / Ivy

There is a newer version: 4.0.1
Show newest version
package com.natpryce.makeiteasy;

import java.util.HashMap;
import java.util.Map;


/**
 * Makes objects of a given type with a specified initial state.
 *
 * @param  the type of object to make
 */
public class Maker implements PropertyLookup, Donor {
    private final Map, PropertyValue> values = newHashMap();
    private final Instantiator instantiator;

    /**
     * Creates a Maker for objects of a given type with a given initial state.
     * 
     * @param instantiator creates the new objects
     * @param propertyValues define the initial state of the new objects
     */
    public Maker(Instantiator instantiator, PropertyValue... propertyValues) {
        this.instantiator = instantiator;
        setPropertyValues(propertyValues);
    }
    
    private static  Map newHashMap() {
        return new HashMap<>();
    }
    
    private Maker(Maker that, PropertyValue... propertyValues) {
        this.instantiator = that.instantiator;
        this.values.putAll(that.values);
        setPropertyValues(propertyValues);
    }

    private void setPropertyValues(PropertyValue[] propertyValues) {
        for (PropertyValue propertyValue : propertyValues) {
            values.put(propertyValue.property(), propertyValue);
        }
    }

    /**
     * Makes a new object.
     *
     * The {@link com.natpryce.makeiteasy.MakeItEasy#make(Maker) MakeItEasy.make} method
     * is syntactic sugar to make calls to this method read more naturally in most
     * contexts.
     *
     * @return a new object
     */
    public T make() {
        return instantiator.instantiate(this);
    }

    @Override
    public T value() {
        return make();
    }
    
    /**
     * Returns a new Maker for the same type of object and with the same initial state
     * except where overridden by the given propertyValues.
     *
     * @param propertyValues those initial properties of the new Make that will differ from this Maker
     * @return a new Maker
     */
    public Maker but(PropertyValue... propertyValues) {
        return new Maker<>(this, propertyValues);
    }
    
    @Override
    public  V valueOf(Property property, V defaultValue) {
        return valueOf(property, new SameValueDonor<>(defaultValue));
    }
    
    @Override
    public  V valueOf(Property property, Donor defaultValue) {
        if (values.containsKey(property)) {
            //noinspection unchecked
            return (V) values.get(property).value();
        }
        else {
            return defaultValue.value();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy