ZStack源码剖析之设计模式鉴赏——策略模式

Ral86F 6年前
   <h2>前言</h2>    <p>无论什么程序,其目的都是解决问题。而为了解决问题,我们又需要编写特定的算法。使用Strategy模式可以整体地替换算法的实现部分。能够整体地替换算法,能让我们轻松地以不同的算法去解决一个问题,这种模式就是Strategy模式。</p>    <p>在ZStack中,Strategy模式几乎是充斥在80%以上的代码中的,接下来我们就来一起看看吧。</p>    <h2>CollectionUtils</h2>    <p><a href="/misc/goto?guid=4959757280443714225" rel="nofollow,noindex">CollectionUtils</a> 这个类是在JDK8发布前常在ZStack中被使用的一个类,代码如下:</p>    <pre>  <code class="language-java">package org.zstack.utils;    import org.zstack.utils.function.ForEachFunction;  import org.zstack.utils.function.Function;  import org.zstack.utils.function.ListFunction;  import org.zstack.utils.logging.CLogger;    import java.util.*;    /**   */  public class CollectionUtils {      private static final CLogger logger = Utils.getLogger(CollectionUtils.class);        public static <K, V> List<K> transformToList(Collection<V> from, ListFunction<K, V> func) {          List<K> ret = new ArrayList<K>();          for (V v : from) {              List<K> k = func.call(v);              if (k == null) {                  continue;              }              ret.addAll(k);          }            return ret;      }        public static <K, V> List<K> transformToList(Collection<V> from, Function<K, V> func) {          List<K> ret = new ArrayList<K>();          for (V v : from) {              K k = func.call(v);              if (k == null) {                  continue;              }              ret.add(k);          }            return ret;      }        public static <K, V> Set<K> transformToSet(Collection<V> from, Function<K, V> func) {          Set<K> ret = new HashSet<K>();          for (V v : from) {              K k = func.call(v);              if (k == null) {                  continue;              }              ret.add(k);          }            return ret;      }        public static <K, V> Set<K> transformToSet(Collection<V> from, ListFunction<K, V> func) {          Set<K> ret = new HashSet<K>();          for (V v : from) {              List<K> k = func.call(v);              if (k == null) {                  continue;              }              ret.addAll(k);          }            return ret;      }        public static <K, V> K find(Collection<V> from, Function<K, V> func) {          for (V v : from) {              K k = func.call(v);              if (k != null) {                  return k;              }          }            return null;      }        public static <K> void forEach(Collection<K> cols, ForEachFunction<K> func) {          for (K c : cols) {              func.run(c);          }      }        public static <K> void safeForEach(Collection<K> cols, ForEachFunction<K> func) {          for (K c : cols) {              try {                  func.run(c);              } catch (Throwable t) {                  logger.warn(String.format("unhandled exception happened"), t);              }          }      }        public static <K> List<K> removeDuplicateFromList(List<K> lst) {          return new ArrayList<K>(new LinkedHashSet<K>(lst));      }  }</code></pre>    <p>以 public static <K, V> List<K> transformToList(Collection<V> from, Function<K, V> func) 为例,从语义上来说就是为了from中的每个元素调用func函数。没错,就像函数式编程中的 map 。</p>    <pre>  <code class="language-java">List<KVMHostAsyncHttpCallMsg> msgs = CollectionUtils.transformToList(hostUuids, new Function<KVMHostAsyncHttpCallMsg, String>() {              @Override              public KVMHostAsyncHttpCallMsg call(String huuid) {                  ScanCmd cmd = new ScanCmd();                  cmd.ip = getIpForScan(struct);                  cmd.startPort = 1;                  cmd.endPort = 65535;                  cmd.interval = struct.getInterval();                  cmd.times = struct.getMaxTimes();                  cmd.successInterval = struct.getSuccessInterval();                  cmd.successTimes = struct.getSuccessTimes();                    KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();                  msg.setHostUuid(huuid);                  msg.setPath(SCAN_HOST_PATH);                  msg.setCommandTimeout(timeoutManager.getTimeout(cmd.getClass(), TimeUnit.SECONDS.toMillis(cmd.interval *cmd.times) + TimeUnit.MINUTES.toMillis(1)));                  msg.setCommand(cmd);                  bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, huuid);                    return msg;              }          });</code></pre>    <p>从这边的代码可以看到,通过遍历hostUuids并做了一些操作,成功的组成了一组msg。</p>    <h2>Completion</h2>    <p>在异步系统中,Completion是很常见的——当一个异步行为完成时,则会调用其相应的CompletionHandle。</p>    <pre>  <code class="language-java">bus.send(amsg, new CloudBusCallBack(completion) {              @Override              public void run(MessageReply re) {                  if (!re.isSuccess()) {                      completion.fail(re.getError());                  } else {                      completion.success(re);                  }              }          });</code></pre>    <p>以 CloudBus的send 调用为例,当一个msg发送并得到回复后,便会执行传进来CallBack的run。这样的代码灵活性非常高——简单来说,传入函数的是一个行为,而不是参数。</p>    <p><a href="/misc/goto?guid=4959757280566731736" rel="nofollow,noindex">CloudBus的源码分析点击这里</a> ,有兴趣的读者可以看一下其实现</p>    <h2>小结</h2>    <p>在本片文章中,笔者和大家一起了解了Strategy在ZStack中的使用场景。通常在编程时,算法(策略)会被写在具体方法中,这样会导致具体方法中充斥着条件判断语句。但是Strategy却特意将算法与其他部分剥离开来,仅仅定义了接口,然后再以委托的方式来使用算法。然而这种做法正是让程序更加的松耦合(因为使用委托可以方便的整体替换算法),使得整个项目更加茁壮。</p>    <p> </p>    <p>来自:https://segmentfault.com/a/1190000013460437</p>    <p> </p>