1:策略模式

2018-04-07  本文已影响0人  Spring_java

运行时根据条件的不同使用不同的策略处理一个事情。

1:创建策略类

public interface MemberStrategy {

       public double calcPrice(double booksPrice);

}

2:创建不同的策略处理对象

public class AdavaceMember implements MemberStrategy{

          @Override

           public double calcPrice(double booksPrice) {

                       System.out.println("对于高级会员的折扣为50%");

                           return booksPrice*0.5;

                  }

}

public class MediumMember implements MemberStrategy{

           @Override

             public double calcPrice(double booksPrice) {

                    System.out.println("对于高级会员的折扣为60%");

                         return booksPrice*0.6;

                   }

}

3:定义具体的场景

public class Price {

   private MemberStrategy ms;

   public Price(MemberStrategy ms){

      this.ms=ms;

   }

//场景里面也具备了策略里面的方法

public double quote(double  booksPrice){

    return this.ms.calcPrice(booksPrice);

   }

}

4:测试

public class Price {

   private MemberStrategy ms;

   public Price(MemberStrategy ms){

              this.ms=ms;

  }

  public double quote(double  booksPrice){

            return this.ms.calcPrice(booksPrice);

             }

}

上一篇下一篇

猜你喜欢

热点阅读