Skip to content

Commit

Permalink
策略-2
Browse files Browse the repository at this point in the history
  • Loading branch information
fatpo committed Dec 2, 2020
1 parent a7dbc67 commit 7838333
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions source/_posts/设计模式之策略模式.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,66 @@ enum Strategy {
}

```
上面的策略很给力吧,枚举策略,优秀,炫技,但是推荐项目用起来其实效果一般,实际上项目的各个策略都是独立 java 文件,互相隔离。

每个策略都极其复杂,不解耦就完了。

RecallStrategy.java:
```java
interface RecallStrategy{
public List<String> recall(Object recallModel);
}
```
ItemCfRecall.java:
```java
@Service
public class ItemCfRecall implements RecallStrategy{
public List<String> recall(Object recallModel){
return Arrays.asList("ItemCF03", "ItemCF04");
}
}
```
UserCfRecall.java:
```java
@Service
public class UserCfRecall implements RecallStrategy{
public List<String> recall(Object recallModel){
return Arrays.asList("UserCF01", "UserCF02");
}
}
```
然后调度如下:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
class RecallContext {

@Autowired
private ApplicationContext applicationContext;

public String getBeanName(String value) {
switch (value) {
case "ITEM_CF":
return "itemCfRecall";
case "USER_CF":
return "userCfRecall";
default:
return null;
}
}

public RecallStrategy getRecallService(String beanName) {
return (RecallStrategy) applicationContext.getBean(beanName);
}

}
```

现在看来,好像可以采用枚举类替代这个 switch + 根据 bean 名字拿到 recallService,不错,值得一试。

0 comments on commit 7838333

Please sign in to comment.