View Javadoc
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  package org.apache.maven.di;
20  
21  import java.util.function.Supplier;
22  
23  import org.apache.maven.api.annotations.Experimental;
24  import org.apache.maven.api.annotations.Nonnull;
25  
26  /**
27   * Defines how object instances are managed within a specific scope.
28   * <p>
29   * A Scope controls the lifecycle and visibility of objects created by the injector.
30   * It determines when new instances are created and when existing instances can be
31   * reused. This allows for different caching strategies depending on the desired
32   * lifecycle of the objects.
33   * <p>
34   * Example implementation for a simple caching scope:
35   * <pre>
36   * public class CachingScope implements Scope {
37   *     private final Map&lt;Key&lt;?&gt;, Object&gt; cache = new ConcurrentHashMap&lt;&gt;();
38   *
39   *     {@literal @}Override
40   *     public &lt;T&gt; Supplier&lt;T&gt; scope(Key&lt;T&gt; key, Supplier&lt;T&gt; unscoped) {
41   *         return () -&gt; {
42   *             return (T) cache.computeIfAbsent(key, k -&gt; unscoped.get());
43   *         };
44   *     }
45   * }
46   * </pre>
47   *
48   * @see org.apache.maven.api.di.Scope
49   * @since 4.0.0
50   */
51  @Experimental
52  public interface Scope {
53  
54      /**
55       * Scopes a supplier of instances.
56       * <p>
57       * This method wraps an unscoped instance supplier with scope-specific logic
58       * that controls when new instances are created versus when existing instances
59       * are reused.
60       *
61       * @param <T> the type of instance being scoped
62       * @param key the key identifying the instance type
63       * @param unscoped the original unscoped instance supplier
64       * @return a scoped supplier that implements the scope's caching strategy
65       * @throws NullPointerException if key or unscoped is null
66       */
67      @Nonnull
68      <T> Supplier<T> scope(@Nonnull Key<T> key, @Nonnull Supplier<T> unscoped);
69  }