Strategy Pattern ava设计模式之策略模式

  简介
  
  在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。简单理解就是一组算法,可以互换,再简单点策略就是封装算法。
  
  意图 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
  
  主要解决 在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
  
  何时使用 一个系统有许多许多类,而区分它们的只是他们直接的行为。
  
  如何解决 将这些算法封装成一个一个的类,任意地替换。
  
  主要角色
  
  上下文Context,拥有一个Strategy的引用
  
  抽象策略Strategy,往往是一个接口(占大部分情况)或者抽象类,通常提供各种具体策略的接口
  
  具体策略,这就是重点了,封装了各种具体的算法
  
  UML
  
  img
  
  应用实例
  
  诸葛亮的锦囊妙计,每一个锦囊就是一个策略;
  
  旅行的出游方式,选择骑自行车、坐汽车,每一种旅行方式都是一个策略;
  
  JAVA AWT 中的 LayoutManager;
  
  优点 1、算法可以自由切换。 2、避免使用多重条件判断。 3、扩展性良好。
  
  缺点 1、策略类会增多。 2、所有策略类都需要对外暴露。
  
  使用场景
  
  如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。
  
  一个系统需要动态地在几种算法中选择一种。
  
  如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。
  
  注意事项: 如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题。
  
  项目描述
  
  跳转到我的策略模式GitHub
  
  1.操作行为
  
  simple1包,主要对操作行为包装了加减乘除方法。
  
  @Slf4j
  
  public class Application {
  
  public static void main(String[] args) {
  
  Context context = new Context(new AddStrategy());
  
  log.info("10 + 5 = {}", context.executeStrategy(10, 5));
  
  context.setStrategy(new SubstractStrategy());
  
  log.info("10 - 5 = {}", context.executeStrategy(10, 5));
  
  context.setStrategy(new MultiplyStrategy());
  
  log.info("10 * 5 = {}", context.executeStrategy(10, 5));
  
  context.setStrategy(new DivideStrategy());
  
  log.info("10 / 5 = {}", context.executeStrategy(10, 5));
  
  }
  
  }
  
  执行结果
  
  img
  
  2.出现方式
  
  simple2包描述,主要对出行方式的包装,包装了3种出行方式,
  
  执行类
  
  public class TravelApplication {
  
  public static void main(String[] args) {
  
  Context context = new Context(new BusStrategy());
  
  context.executeStrategy("老王");
  
  context.setStrategy(new BicycleStrategy());
  
  context.executeStrategy("老张");
  
  context.setStrategy(new WalkStrategy());
  
  context.executeStrategy("老李");
  
  }
  
  }
  
  执行结果
  
  <u>image-20181222104657926</u>
  
  策略上下文
  
  @Data
  
  public class Context {
  
  private Strategy strategy;
  
  public Context(Strategy strategy) {
  
  this.strategy = strategy;
  
  }
  
  /**
  
  * 出行
  
  *
  
  * @return
  
  */
  
  public void executeStrategy(String name) {
  
  strategy.travel(name);
  
  }
  
  }
  
  抽象策略
  
  public interface Strategy {
  
  /**
  
  * 出现方法
  
  *
  
  * @return
  
  */
private[spark] class Executor(
executorId: String,
executorHostname: String,
env: SparkEnv,
userClassPath: Seq[URL] = Nil,
isLocal: Boolean = false)
extends Logging {
......
// must be initialized before running startDriverHeartbeat()
//创建心跳的 EndpointRef
private val heartbeatReceiverRef = RpcUtils.makeDriverRef(www.haomem178.cn HeartbeatReceiver.ENDPOINT_NAME, conf, env.rpcEnv)
......
startDriverHeartbeater()
......
/**
* Schedules a task to report heartbeat and partial metrics for active tasks to driver.
* 用一个 task 来报告活跃任务的信息以及发送心跳。
*/
private def startDriverHeartbeater(): Unit = {
val intervalMs = conf.getTimeAsMs("spark.executor.heartbeatInterval", "10s")

// Wait a random interval so the heartbeats don't end up in sync
val initialDelay = intervalMs + (math.random * intervalMs).asInstanceOf[Int]

val heartbeatTask = new Runnable() {
override def run(): Unit = Utils.logUncaughtExceptions(reportHeartBeat())
}
//heartbeater是一个单线程线程池,scheduleAtFixedRate 是定时执行任务用的,和 schedule 类似,只是一些策略不同。
heartbeater.scheduleAtFixedRate(heartbeatTask, initialDelay, intervalMs, TimeUnit.MILLISECONDS)
}
......
}
可以看到,在 Executor 中会创建心跳的 EndpointRef ,变量名为 heartbeatReceiverRef 。

然后我们主要看 startDriverHeartbeater() 这个方法,它是关键。
我们可以看到最后部分代码

val heartbeatTask = new Runnable(www.fengshen157.com/) {
override def run(): Unit = Utils.logUncaughtExceptions(reportHeartBeat())
}
heartbeater.scheduleAtFixedRate(heartbeatTask, initialDelay, intervalMs, TimeUnit.MILLISECONDS)
heartbeatTask 是一个 Runaable,即一个线程任务。scheduleAtFixedRate 则是 java concurrent 包中用来执行定时任务的一个类,这里的意思是每隔 10s 跑一次 heartbeatTask 中的线程任务,超时时间 30s 。

为什么到这里还是没看到 heartbeatReceiverRef 呢,说好的发送心跳呢?别急,其实在 heartbeatTask 线程任务中又调用了另一个方法,我们到里面去一探究竟。

private[spark] class Executor(
executorId: String,
executorHostname: String,
env: SparkEnv,
userClassPath: Seq[URL] = Nil,
isLocal: Boolean = false)
extends Logging {
......
private def reportHeartBeat(): Unit = {
// list of (task id, accumUpdates) to send back to the driver
val accumUpdates = new ArrayBuffer[(Long, Seq[AccumulatorV2[_, _]])]()
val curGCTime = computeTotalGcTime()

for (taskRunner <- runningTasks.values().asScala) {
if (taskRunner.task != null) {
taskRunner.task.metrics.mergeShuffleReadMetrics()
taskRunner.task.metrics.setJvmGCTime(curGCTime - taskRunner.startGCTime)
accumUpdates += ((taskRunner.taskId, taskRunner.task.metrics.accumulators()))
}
}

val message = Heartbeat(executorId, accumUpdates.toArray, env.blockManager.blockManagerId)
try {
//终于看到 heartbeatReceiverRef 的身影了
val response = heartbeatReceiverRef.askWithRetry[HeartbeatResponse](
message, RpcTimeout(conf, "spark.executor.heartbeatInterval", "10s"))
if (response.reregisterBlockManager) {
logInfo("Told to re-register on heartbeat")
env.blockManager.reregister()
}
heartbeatFailures = 0
} catch {
case NonFatal(e) =>
logWarning(www.gxgjpt1.com "Issue communicating www.078881.cn/ with driver in heartbeater", e)
heartbeatFailures += 1
if (heartbeatFailures >= HEARTBEAT_MAX_FAILURES) {
logError(s"Exit as unable to send heartbeats to driver " +
s"more than $HEARTBEAT_MAX_FAILURES times")
System.exit(ExecutorExitCode.HEARTBEAT_FAILURE)
  
  }
  
  参考
  
  策略模式
  
  维基里的策略模式
  
  南乡清水的实际项目运用之Strategy模式

猜你喜欢

转载自www.cnblogs.com/qwangxiao/p/10284721.html