策略模式
一、什么是策略模式
Strategy模式也叫策略模式是行为模式之一,它对一系列的算法加以封装,为所有算法定义一个抽象的算法接口,并通过继承该抽象算法接口对所有的算法加以封装和实现,具体的算法选择交由客户端决定(策略)。Strategy模式主要用来平滑地处理算法的切换 。
二、策略模式的结构
三、策略模式的角色和职责
Strategy:
策略(算法)抽象。
ConcreteStrategy
各种策略(算法)的具体实现。
Context
策略的外部封装类,或者说策略的容器类。根据不同策略执行不同的行为。策略由外部环境决定。
策略模式的缺点有:
1. 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道所有的算法或行为的情况。
2. 策略模式造成很多的策略类。有时候可以通过把依赖于环境的状态保存到客户端里面,而将策略类设计成可共享的,这样策略类实例可以被不同客户端使用。换言之,可以使用享元模式来减少对象的数量。
五、代码
package org.fbm.strategy;
public interface Strategy {
public void encryption();
}
package org.fbm.strategy;
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void contextEncryption() {
this.strategy.encryption();
}
}
package org.fbm.strategy;
public class MD5Encryption implements Strategy {
public void encryption() {
System.out.println("MD5加密");
}
}
package org.fbm.strategy;
public class SEAEncryption implements Strategy {
public void encryption() {
System.out.println("SEA加密");
}
}
package org.fbm.strategy;
public class MainClass {
public static void main(String[] args) {
Context context1=new Context(new MD5Encryption());
context1.contextEncryption();
Context context2=new Context(new SEAEncryption());
context2.contextEncryption();
}
}