001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    package org.apache.shiro.util;
020    
021    /**
022     * TODO - Class JavaDoc
023     *
024     * @author Les Hazlewood
025     * @since 1.0
026     */
027    public abstract class AbstractFactory<T> implements Factory<T> {
028    
029        private boolean singleton;
030        private T singletonInstance;
031    
032        public AbstractFactory() {
033            this.singleton = true;
034        }
035    
036        public boolean isSingleton() {
037            return singleton;
038        }
039    
040        public void setSingleton(boolean singleton) {
041            this.singleton = singleton;
042        }
043    
044        public T getInstance() {
045            T instance;
046            if (isSingleton()) {
047                if (this.singletonInstance == null) {
048                    this.singletonInstance = createInstance();
049                }
050                instance = this.singletonInstance;
051            } else {
052                instance = createInstance();
053            }
054            if (instance == null) {
055                String msg = "Factory 'createInstance' implementation returned a null object.";
056                throw new IllegalStateException(msg);
057            }
058            return instance;
059        }
060    
061        protected abstract T createInstance();
062    }