常用设计模式----策略模式

package org.design.patterns;

import java.io.File;
import java.io.FilenameFilter;


/**
 *策略模式:定义了算法族,分别封装起来,让它们之间可以相互替换,
 *         此模式让算法的变化独立于使用算法的客户。 
 *
 *策略模式使用多个类来区分不同的行为,使用策略模式避免暴露复杂的、与算法相关的
 *内部数据结构。
 *当一个类中的操作以多个条件分支语句的形式出现的时候,可以使用策略模式
 *将相关的条件分支移入各自的具体策略类中以代替这些条件语句,从而减少系统的复杂度。
 *
 */

//行动算法的顶层接口
interface IBehave{
 public void doSomeThing();
}
//行为算法的实现类1
class BehaveImp1 implements IBehave{
 @Override
 public void doSomeThing() {
         System.out.println(" BehaveImp1 do some thing!");  
 }
}

//行为算法的实现类2
class BehaveImp2 implements IBehave{
 @Override
 public void doSomeThing() {
         System.out.println(" BehaveImp2 do some thing!");  
 }
}

public class Strategy {
 IBehave behave;
 
    public Strategy() {}
 
 public void realDo(){//客户端调用的方法
  behave.doSomeThing();
 }
 //可以通过set注入的方式动态的改变行为算法
 public void setBehave(IBehave behave){
  this.behave=behave;
 } 
}
//====================================
/*
 * java中使用策略模式的地方非常多,下面以java.io.File中的例子进行说明:
 */
class SampleAboutFile{
 public static void main(String[] args) {
  File file=new File(".");
  file.list();//该方法会返回file所在目录中的所有文件的列表

  //该方法就是策略模式的一个例子,list可以通过传参的形式使用不同的策略算法
  file.list(new JavaFileFilter());//带有文件名过滤器的list,会返回特定的文件
 }
}

//不同策略的实现类
class JavaFileFilter implements FilenameFilter{
 @Override
 public boolean accept(File dir, String name) {
    name = name.toLowerCase();
    return name.endsWith(".jave");  
 }
}

class ZipOrJarFileFilter implements FilenameFilter{
 @Override
 public boolean accept(File dir, String name) {
    name = name.toLowerCase();
    return name.endsWith(".zip") || name.endsWith(".jar");  
 }
}

//FilenameFilter接口的实现(相当于策略的接口)
// package java.io;
// public interface FilenameFilter {
//     boolean accept(File dir, String name);
// }

你可能感兴趣的:(设计模式)