概述
在平时出门的时候,可能我们会为了选择穿什么鞋子而犹豫,因为出门的目的不同,所以就会选择不同的鞋子,而穿上不同的鞋子出门。今天为大家带来的设计模式是策略模式,它与上述的情景很类似,比如在图片缓存策略中,我们可以根据需要(本地缓存或本地缓存+内存缓存)而传入不同的缓存类。策略模式的定义为:有一系列的算法,将每个算法封装起来,各个算法可以替换。可能定义有点抽象,以下为具体的代码实现简单的策略模式。
策略模式
以最开始的场景
//鞋子的最上层接口
public interface IShoes {
void use(String name);
}
//运动用的鞋子
public class SportShoes implements IShoes {
@Override
public void use(String name) {
System.out.println(name);
}
}
//参加婚礼用的鞋子
public class WeddingShoes implements IShoes {
@Override
public void use(String name) {
System.out.println(name);
}
}
//人的最上层接口
public abstract class IPerson {
public IShoes shoes;
abstract void setShoesName(String shoesName);
abstract void wear(IShoes shoes);
}
//要去运动的人
public class SportPerson extends IPerson {
@Override
public void setShoesName(String shoesName) {
System.out.print("sport----");
shoes.use(shoesName);
}
@Override
void wear(IShoes shoes) {
this.shoes=shoes;
}
}
//要去参加婚礼的人
public class WeddingPerson extends IPerson {
@Override
void setShoesName(String shoesName) {
System.out.print("wedding----");
shoes.use(shoesName);
}
@Override
void wear(IShoes shoes) {
this.shoes=shoes;
}
}
//客户端
IPerson weddingPerson=new WeddingPerson();//参加婚礼
IPerson sportPerson=new SportPerson();//运动
weddingPerson.wear(new WeddingShoes());//选择适合参加婚礼的鞋子(策略)
weddingPerson.setShoesName("皮鞋");
sportPerson.wear(new SportShoes());//选择适合运动的鞋子(策略)
sportPerson.setShoesName("puma");
//打印结果
wedding----皮鞋
sport----puma
优点:提高了程序的扩展性,提供了可替换的办法。可避免使用多重条件语句。
缺点:客户必须知道所有的策略类,并且每个策略对应着一类,如果策略多的情况下会造成很多个类。