策略模式:
策略模式是一种行为型设计模式,它允许你定义一系列算法,把它们封装起来,并且使它们可以互相替换。这样,使用算法的客户端代码可以独立于具体的算法实现方式。
就好像是你要去旅行,你可以选择多种不同的交通工具(比如汽车、飞机、火车),每种交通工具都是一种策略。你根据自己的需求和情况选择最适合的交通方式,这就是策略模式的思想。
在策略模式中,通常有三个角色:
- 上下文(Context):包含一个策略对象,负责和客户端交互。上下文知道策略对象,并能根据需要调用具体的策略来完成任务。
- 策略接口(Strategy Interface):定义了一系列算法的共同行为。通常是一个接口或者抽象类,规定了具体策略类所必须实现的方法。
- 具体策略类(Concrete Strategies):实现了策略接口,在具体的策略类中实现了算法。
同样的,来实现一个计算器,他拥有加法、减法、乘法等运算。
策略接口
public interface BaseStratege {int compute(int x,int y);
}
具体策略类
class Add implements BaseStratege {@Overridepublic int compute(int x, int y) {return x+y;}
}class Sub implements BaseStratege {@Overridepublic int compute(int x, int y) {return x-y;}
}
上下文Context
public class Context {private BaseStratege stratege;public Context(BaseStratege stratege) {this.stratege = stratege;}public int compute(int x,int y){return stratege.compute(x,y);}public BaseStratege getStratege() {return stratege;}public void setStratege(BaseStratege stratege) {this.stratege = stratege;}
}
和工厂模式类似,同样先创建一个接口,然后创建对应的实现类,再使用一个Context类来计算结果,但是Context中获取特定实现类的操作,是需要我们手动给定的,也就是说策略模式需要我们记住所需的实现类
public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int x = scanner.nextInt();int y = scanner.nextInt();int result = new Context(new Add()).compute(x, y);System.out.println(result);}
以上的 Add()类就是需要我们记住的,而不是像工厂一样只需要给定一个特定的条件.
总结:
工厂模式和策略模式在形式上比较相似,但是在实际使用场景中有很大的不同,工厂模式用在能通过某些条件得到确定的实现类,策略模式用在需要我们来判断所需的实现类。