java 利用注解实现策略模式代码
时间: 2024-05-18 08:06:48 浏览: 10
策略模式是一种行为设计模式,它允许在运行时选择算法的行为。在Java中,可以使用注解来实现策略模式。以下是一个示例代码,展示如何使用注解实现策略模式。
首先,定义一个注解,用于标记策略类:
```
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Strategy {
String value();
}
```
这个注解有一个value属性,表示策略的名称。
接下来,定义一个策略接口:
```
public interface PaymentStrategy {
void pay(int amount);
}
```
然后,实现两个策略类:
```
@Strategy("creditCard")
public class CreditCardStrategy implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paying " + amount + " using credit card");
}
}
@Strategy("paypal")
public class PaypalStrategy implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paying " + amount + " using PayPal");
}
}
```
这两个类都使用了@Strategy注解,并且实现了PaymentStrategy接口。
现在,我们可以编写一个策略选择器来选择使用哪个策略:
```
public class PaymentContext {
private final Map<String, PaymentStrategy> strategies;
public PaymentContext() {
strategies = new HashMap<>();
ServiceLoader.load(PaymentStrategy.class).forEach(strategy -> {
Strategy strategyAnnotation = strategy.getClass().getAnnotation(Strategy.class);
if (strategyAnnotation != null) {
strategies.put(strategyAnnotation.value(), strategy);
}
});
}
public void pay(String strategyName, int amount) {
PaymentStrategy strategy = strategies.get(strategyName);
if (strategy == null) {
throw new IllegalArgumentException("Invalid strategy name: " + strategyName);
}
strategy.pay(amount);
}
}
```
这个类使用了Java的ServiceLoader来加载所有实现了PaymentStrategy接口的类,并根据它们的@Strategy注解来进行分类。然后,它提供了一个pay方法来执行支付操作,根据传入的策略名称来选择使用哪个策略。
最后,我们可以使用PaymentContext来执行支付操作:
```
PaymentContext context = new PaymentContext();
context.pay("creditCard", 100);
context.pay("paypal", 200);
```
这个代码将分别使用CreditCardStrategy和PaypalStrategy来支付100和200元。
通过使用注解来实现策略模式,我们可以避免使用大量的if-else语句或switch语句来选择使用哪个策略,使代码更加简洁、易于维护。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)