博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
策略模式
阅读量:4067 次
发布时间:2019-05-25

本文共 1377 字,大约阅读时间需要 4 分钟。

一、类图:

三个角色:

使用环境角色:

抽象策略角色:
具体策略角色:
在这里插入图片描述

二、举例:例如:TreeSet中:

UseContext : TreeSet

IStrategy : Comparator

TreeSet
treeSet = new TreeSet
(new Comparator
() {
@Override public int compare(Integer num1, Integer num2) {
if(num1 > num2){
return 1; }else {
return 0; } } });

三、使用策略模式

//   public interface ICountStrategy{
int count(int num1, int num2); } // public class CountContext{
private ICountStrategy mICountStrategy; CountContext(ICountStrategy iCountStrategy){
mICountStrategy = iCountStrategy; } public int count(int num1, int num2){
return mICountStrategy.count(num1, num2); } } // public class AddStrategy implements ICountStrategy{
@Override public int count(int num1, int num2) {
return num1 + num2; } } // public class SubtractStrategy implements ICountStrategy{
@Override public int count(int num1, int num2) {
return num1 - num2; } } // public void test(){
CountContext countContext = new CountContext(new AddStrategy()); int result = countContext.count(1, 3); }

转载地址:http://weaji.baihongyu.com/

你可能感兴趣的文章
Struts2类型转换器
查看>>
struts2 使用注解、反射、拦截器实现基于方法的权限控制
查看>>
maven 架设 struts2 注解方式 权限控制
查看>>
struts2之多个文件上传
查看>>
struts2之单个文件上传
查看>>
struts2自定义拦截器 模拟session超时的处理
查看>>
面试技巧
查看>>
struts2之防止表单重复提交
查看>>
人不成熟的几大特征
查看>>
《礼仪73》、《处事22计》、《心态24条》、《伤心50句》、《学会长大20》
查看>>
人人都会变老
查看>>
oracle connect by用法
查看>>
Oracle 树操作(select…start with…connect by…prior)
查看>>
maven struts2中,使用ModelDriven
查看>>
通过web.xml传递初始参数
查看>>
过滤器与拦截器
查看>>
maven 下成功搭建hibernate
查看>>
maven hibernate 实现对mysql简单的CRUD操作
查看>>
Java 线程池学习
查看>>
j2ee中的listener、 filter、servlet 加载顺序及其详解
查看>>