zoukankan      html  css  js  c++  java
  • 策略模式

    的略模式概述

    问题引入

    解决方案

    代码体现

    package com.xnn.strategy;
    /**
     * 
     * 类(接口)描述:策略接口,所有的具体策略都得实现这个接口
     * @author xnn
     * 2018年11月4日下午10:31:14
     */
    public interface Strategy {
    
    	public double cost(double num);
    }
    
    package com.xnn.strategy;
    /**
     * 
     * 类(接口)描述:其中的一种策略:统统打八折
     * @author xnn
     * 2018年11月4日下午10:32:24
     */
    public class StrategyA implements Strategy{
    
    	public double cost(double num) {
    		return num * 0.8;
    	}
    
    }
    
    package com.xnn.strategy;
    /**
     * 
     * 类(接口)描述:另一种策略:超过两百的减免50元,否则原价付款
     * @author xnn
     * 2018年11月4日下午10:33:16
     */
    public class StrategyB implements Strategy {
    
    	public double cost(double num) {
    		if(num >= 200) {
    			return num - 50;
    		}
    		return num;
    	}
    
    }
    
    package com.xnn.strategy;
    /**
     * 
     * 类(接口)描述:环境类:持有一个strategy类的引用
     * @author xnn
     * 2018年11月4日下午10:34:43
     */
    public class Context {
    	private Strategy strategy;
    	
    	public Context(Strategy strategy) {
    		this.strategy = strategy;
    	}
    	
    	public double cost(double num){
    		return this.strategy.cost(num);
    	}
    	
    }
    
    package com.xnn.strategy;
    
    public class MainClass {
    	public static void main(String[] args) {
    		double num = 200;
    		Context context = new Context(new StrategyB());
    		double newNum = context.cost(num);
    		System.out.println("实际付账" + newNum + "元");
    	}
    }
    
    

    所对应的类图:

    运行结果

    由上面的例子可以看出——策略模式有三个角色:
    1、环境角色(Context类),持有一个strategy类的引用
    2、抽象策略角色(strategy类)这是一个抽象角色,通常有一个接口或者抽象类实现,此角色给出所有具体策略类所需的接口
    3、具体策略角色(StrategyA、StrategyB) 包含了相关的算法和行为

    注意:


    什么时候该用

    优缺点


  • 相关阅读:
    软件开发流程实例之四 :编码和测试
    软件开发流程实例之三 :系统设计
    jQuery入门[4]-链式代码
    jQuery入门[1]-构造函数
    jQuery入门[2]-选择器
    自编类库,添加引用,编译运行时显示“未能找到”
    SelectByShape 工具的实现
    TOC控件不显示内容列表
    鹰眼功能的实现(步骤,无代码)
    INumericFormat 接口
  • 原文地址:https://www.cnblogs.com/nnxud/p/9906417.html
Copyright © 2011-2022 走看看