设计模式----策略模式通俗实例

在Spring里,策略模式,加载资源文件的方式,使用了不一样的方法,好比:ClassPathResourece,FileSystemResource,ServletContextResource,UrlResource但他们都有共同的借口Resource;在Aop的实现中,采用了两种不一样的方式,JDK动态代理和CGLIB代理ide


 

锻炼身体,你能够选择跑步、游泳、举重,因而就有了三个策略能够选择了测试


 

锻炼方式策略的接口

package com.ij34.stategy;
/*

  策略模式接口
*/

public interface StrategyPattern {
    /*
       锻炼方式的方法
    */
    public void exercise();
}

 

三种锻炼方式

1.this

package com.ij34.stategy;
/*
  实现跑步锻炼方法
*/

public class run implements StrategyPattern {

    @Override
    public void exercise() {
        System.out.println("我正在经过跑步来锻炼身体");
    }
}

2.spa

package com.ij34.stategy;
/*
  实现游泳锻炼方法
*/

public class swim implements StrategyPattern {

    @Override
    public void exercise() {
        System.out.println("我正在经过游泳来锻炼身体");
    }
}

3.代理

package com.ij34.stategy;
/*
  实现举重锻炼方法
*/

public class lift implements StrategyPattern {

    @Override
    public void exercise() {
        System.out.println("我正在经过举重来锻炼身体");
    }
}

 

为用户选择锻炼方式的Context类

package com.ij34.stategy;
    /*
   经过该类为用户提供本身喜好的锻炼方式
*/
public class exerciseContext {
    private StrategyPattern sp;
    public exerciseContext(StrategyPattern sp){
        this.sp=sp;
    }

    public void exercise(){
        sp.exercise();
    }
}

 

测试类

package com.ij34.stategy;

public class Test {
    /*
    张三喜欢跑步,经过跑步来锻炼
    */
    public static void main(String[] args) {
        exerciseContext zhangsan=new exerciseContext(new run());
        zhangsan.exercise();
    }

}

 

测试结果

相关文章
相关标签/搜索