Guava中应用了什么设计模式
时间: 2024-03-22 14:27:56 浏览: 27
Guava是一个Java工具库,其中应用了很多设计模式。以下是一些常见的设计模式在Guava中的应用:
1. 工厂模式:Guava中的工厂模式包括:FluentIterable、FluentValidator、CacheLoader等。
2. 装饰器模式:Guava中的装饰器模式包括:ForwardingList、ForwardingMap、ForwardingSet等。
3. 观察者模式:Guava中的观察者模式包括:EventBus、Listeners、Monitor等。
4. 单例模式:Guava中的单例模式包括:Enums、Memoizer等。
5. 建造者模式:Guava中的建造者模式包括:ImmutableList.Builder、ImmutableMap.Builder、ImmutableSet.Builder等。
6. 策略模式:Guava中的策略模式包括:Equivalence、Predicate、Function等。
7. 迭代器模式:Guava中的迭代器模式包括:Iterators、PeekingIterator、AbstractIterator等。
8. 模板方法模式:Guava中的模板方法模式包括:AbstractFuture、AbstractIdleService、AbstractScheduledService等。
以上是一些常见的设计模式在Guava中的应用,当然还有其他的设计模式在Guava中也有应用。
相关问题
guava中String数组转list
在Guava中,没有提供专门实现String数组不可变的类。但是你可以使用Guava中的ImmutableList类来实现String数组转为不可变的List。
下面是使用Guava中的ImmutableList实现String数组转为不可变的List的方法:
```java
String[] arr = {"1", "2", "4", "6"};
List<String> list = ImmutableList.copyOf(arr);
```
删除guava cache中的元素
要删除 Guava Cache 中的元素,可以使用 `Cache.invalidate(key)` 方法来删除指定的键值对,或者使用 `Cache.invalidateAll(keys)` 方法来删除指定键集合中的所有键值对,或者使用 `Cache.invalidateAll()` 方法来删除缓存中的所有键值对。以下是一个示例:
```java
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
// 添加元素
cache.put("key1", "value1");
cache.put("key2", "value2");
// 删除指定元素
cache.invalidate("key1");
// 删除指定键集合中的所有元素
cache.invalidateAll(Arrays.asList("key1", "key2"));
// 删除所有元素
cache.invalidateAll();
```
请注意,Guava Cache 是一个内存缓存,不应该用于缓存大量的数据。如果您需要缓存大量数据,请考虑使用其他缓存解决方案,如 Redis 等。