1.定义
定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化不会影响到使用算法的用户。

2.优点
符合开闭原则,避免使用多重条件语句。

3.代码示例

public interface PromotionStrategy {
void doPromotion();
}
public class LijianPromotionStrategy implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("立减20促销活动");
}
}
public class ManjianPromotionStrategy implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("满200减20促销活动");
}
}
public class FanxianPromotionStrategy implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("返现20促销活动");
}
}
public class PromotionActivity {
private PromotionStrategy promotionStrategy;

public PromotionActivity(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
}

public void executePromotionActivity() {
promotionStrategy.doPromotion();
}
}
public class Test {
public static void main(String[] args) {
PromotionActivity promotionActivity = new PromotionActivity(new LijianPromotionStrategy());
promotionActivity.executePromotionActivity();
}
}
立减20促销活动

2.4 策略模式_System

4.源码解析

public class DefaultResourceLoader implements ResourceLoader {
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
//1.用户自定义协议资源解决策略,返回Resource
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}

//2.如果是以/开头,则构造ClassPathContextResource类型资源返回
if (location.startsWith("/")) {
return getResourceByPath(location);
}else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
//3.如果以classpath:开头,则构造ClassPathResource类型资源返回
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}else {
try {
//4.构造URL,尝试进行资源定位,返回FileUrlResource或者UrlResource,如果没有定位到,则抛出MalformedURLException异常,以ClassPathContextResource类型资源返回
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}catch (MalformedURLException ex) {
//构造ClassPathContextResource类型资源返回
return getResourceByPath(location);
}
}
}
}