设计模式之策略模式

策略模式主要定义一些列的算法,把这些算法封装成偶共同接口的单独的类,并且使他们之间可以互换。策略模式主要有下面几部分组成:
1)  算法使用环境 (Context) 角色:算法被引用到这里和一些其它的与环境有关的操作一起 来完成任务。
2)  抽象策略 (Strategy)  角色:规定了所有具体策略角色所需的接口。在  java  它通常由接口 或者抽象类来实现。
3)  具体策略 (Concrete Strategy)  角色:实现了抽象策略角色定义的接口。
例子演示:
以普通会员和VIP会员享受的折扣为例
 
 1 package com.cnblogs.ipolaris.Strategy.test;
 2 /**
 3  * 定义抽象策略角色
 4  * @author iPolaris
 5  *
 6  */
 7 public interface Strategy {
 8         public double cost( double num);
 9 }
10 
11 package com.cnblogs.ipolaris.Strategy.test;
12 /**
13  * 普通会员策略角色
14  * @author iPolaris
15  *
16  */
17 public class StrategyCommon implements Strategy {
18 
19         @Override
20         public double cost( double num) {
21                // TODO Auto-generated method stub
22                return num*0.9;
23        }
24 
25 }
26 
27 
28 package com.cnblogs.ipolaris.Strategy.test;
29 /**
30  * 算法使用环境角色
31  * @author iPolaris
32  *
33  */
34 public class Context {
35         private Strategy strategy ;
36 
37         public Context(Strategy strategy) {
38                super ();
39                this .strategy = strategy;
40        }
41        
42         public double cost( double num){
43                return strategy .cost(num);
44        }
45 }
46 
47 
48 package com.cnblogs.ipolaris.Strategy.test;
49 
50 public class Test {
51 
52         /**
53         * @param args
54         */
55         public static void main(String[] args) {
56                double num = 1000;
57               Context context = new Context(new StrategyCommon());
58                double newNum = context.cost(num);
59               System. out .println("普通会员付账" + newNum + "元");
60               context = new Context(new StrategyVIP());
61               newNum = context.cost(num);
62               System. out .println("VIP会员付账" + newNum + "元");
63        }
64 
65 }
运行结果:
 
普通会员付账900.0元
VIP会员付账800.0元

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值