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

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


 

锻炼身体,你可以选择跑步、游泳、举重,于是就有了三个策略可以选择了


 

锻炼方式策略的接口

package com.ij34.stategy;
/*

  策略模式接口
*/

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

 

三种锻炼方式

1.

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

public class run implements StrategyPattern {

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

2.

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

}

 

测试结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值