設計模式----策略模式通俗實例

在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();
    }

}

 

測試結果

相關文章
相關標籤/搜索