1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 module hunt.shiro.util.AbstractFactory;
20 
21 import hunt.Exceptions;
22 
23 /**
24  * Generics-aware interface supporting the
25  * <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method</a> design pattern.
26  *
27  * @param <T> The type of the instance returned by the Factory implementation.
28  * @since 1.0
29  */
30 interface Factory(T) {
31 
32     /**
33      * Returns an instance of the required type.  The implementation determines whether or not a new or cached
34      * instance is created every time this method is called.
35      *
36      * @return an instance of the required type.
37      */
38     T getInstance();
39 }
40 
41 
42 /**
43  * TODO - Class JavaDoc
44  *
45  */
46 abstract class AbstractFactory(T) : Factory!(T) {
47 
48     private bool singleton;
49     private T singletonInstance;
50 
51     this() {
52         this.singleton = true;
53     }
54 
55     bool isSingleton() {
56         return singleton;
57     }
58 
59     void setSingleton(bool singleton) {
60         this.singleton = singleton;
61     }
62 
63      T getInstance() {
64         T instance;
65         if (isSingleton()) {
66             if (this.singletonInstance  is null) {
67                 this.singletonInstance = createInstance();
68             }
69             instance = this.singletonInstance;
70         } else {
71             instance = createInstance();
72         }
73         if (instance  is null) {
74             string msg = "Factory 'createInstance' implementation returned a null object.";
75             throw new IllegalStateException(msg);
76         }
77         return instance;
78     }
79 
80     protected abstract T createInstance();
81 }