001// Copyright 2011 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.ioc.internal.util;
016
017import org.apache.tapestry5.ioc.Invokable;
018import org.apache.tapestry5.ioc.ObjectCreator;
019import org.apache.tapestry5.ioc.OperationTracker;
020
021import java.util.List;
022
023/**
024 * Encapsulates the initial construction of an object instance, followed by a series
025 * {@link InitializationPlan}s to initialize fields and invoke other methods of the constructed object.
026 *
027 * @since 5.3
028 */
029public class ConstructionPlan<T> implements ObjectCreator<T>
030{
031    private final OperationTracker tracker;
032
033    private final String description;
034
035    private final Invokable<T> instanceConstructor;
036
037    private List<InitializationPlan> initializationPlans;
038
039    public ConstructionPlan(OperationTracker tracker, String description, Invokable<T> instanceConstructor)
040    {
041        this.tracker = tracker;
042        this.description = description;
043        this.instanceConstructor = instanceConstructor;
044    }
045
046    public ConstructionPlan add(InitializationPlan plan)
047    {
048        if (initializationPlans == null)
049        {
050            initializationPlans = CollectionFactory.newList();
051        }
052
053        initializationPlans.add(plan);
054
055        return this;
056    }
057
058    @Override
059    public T createObject()
060    {
061        T result = tracker.invoke(description, instanceConstructor);
062
063        if (initializationPlans != null)
064        {
065            executeInitializationPLans(result);
066        }
067
068        return result;
069    }
070
071    private void executeInitializationPLans(final T newInstance)
072    {
073        for (final InitializationPlan<T> plan : initializationPlans)
074        {
075            tracker.run(plan.getDescription(), new Runnable()
076            {
077                @Override
078                public void run()
079                {
080                    plan.initialize(newInstance);
081                }
082            });
083        }
084    }
085}